babylon.viewer.max.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835
  1. (function universalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define("babylonjs-viewer", [], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-viewer"] = factory();
  8. else {
  9. root["BabylonViewer"] = factory(root["BABYLON"]);
  10. }
  11. })(this, function() {
  12. var BabylonViewer =
  13. /******/ (function(modules) { // webpackBootstrap
  14. /******/ // The module cache
  15. /******/ var installedModules = {};
  16. /******/
  17. /******/ // The require function
  18. /******/ function __webpack_require__(moduleId) {
  19. /******/
  20. /******/ // Check if module is in cache
  21. /******/ if(installedModules[moduleId]) {
  22. /******/ return installedModules[moduleId].exports;
  23. /******/ }
  24. /******/ // Create a new module (and put it into the cache)
  25. /******/ var module = installedModules[moduleId] = {
  26. /******/ i: moduleId,
  27. /******/ l: false,
  28. /******/ exports: {}
  29. /******/ };
  30. /******/
  31. /******/ // Execute the module function
  32. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  33. /******/
  34. /******/ // Flag the module as loaded
  35. /******/ module.l = true;
  36. /******/
  37. /******/ // Return the exports of the module
  38. /******/ return module.exports;
  39. /******/ }
  40. /******/
  41. /******/
  42. /******/ // expose the modules object (__webpack_modules__)
  43. /******/ __webpack_require__.m = modules;
  44. /******/
  45. /******/ // expose the module cache
  46. /******/ __webpack_require__.c = installedModules;
  47. /******/
  48. /******/ // define getter function for harmony exports
  49. /******/ __webpack_require__.d = function(exports, name, getter) {
  50. /******/ if(!__webpack_require__.o(exports, name)) {
  51. /******/ Object.defineProperty(exports, name, {
  52. /******/ configurable: false,
  53. /******/ enumerable: true,
  54. /******/ get: getter
  55. /******/ });
  56. /******/ }
  57. /******/ };
  58. /******/
  59. /******/ // getDefaultExport function for compatibility with non-harmony modules
  60. /******/ __webpack_require__.n = function(module) {
  61. /******/ var getter = module && module.__esModule ?
  62. /******/ function getDefault() { return module['default']; } :
  63. /******/ function getModuleExports() { return module; };
  64. /******/ __webpack_require__.d(getter, 'a', getter);
  65. /******/ return getter;
  66. /******/ };
  67. /******/
  68. /******/ // Object.prototype.hasOwnProperty.call
  69. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  70. /******/
  71. /******/ // __webpack_public_path__
  72. /******/ __webpack_require__.p = "";
  73. /******/
  74. /******/ // Load entry module and return exports
  75. /******/ return __webpack_require__(__webpack_require__.s = 14);
  76. /******/ })
  77. /************************************************************************/
  78. /******/ ([
  79. /* 0 */
  80. /***/ (function(module, exports, __webpack_require__) {
  81. /* WEBPACK VAR INJECTION */(function(global) {var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  82. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  83. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  84. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  85. return c > 3 && r && Object.defineProperty(target, key, r), r;
  86. };
  87. var __extends = (this && this.__extends) || (function () {
  88. var extendStatics = Object.setPrototypeOf ||
  89. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  90. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91. return function (d, b) {
  92. extendStatics(d, b);
  93. function __() { this.constructor = d; }
  94. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  95. };
  96. })();
  97. (function universalModuleDefinition(root, factory) {
  98. if(true)
  99. module.exports = factory();
  100. else if(typeof define === 'function' && define.amd)
  101. define("babylonjs", [], factory);
  102. else if(typeof exports === 'object')
  103. exports["babylonjs"] = factory();
  104. else {
  105. root["BABYLON"] = factory(root["BABYLON"]);
  106. }
  107. })(this, function() {
  108. "use strict";
  109. var BABYLON;
  110. (function (BABYLON) {
  111. /**
  112. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  113. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  114. */
  115. var EffectFallbacks = /** @class */ (function () {
  116. function EffectFallbacks() {
  117. this._defines = {};
  118. this._currentRank = 32;
  119. this._maxRank = -1;
  120. }
  121. /**
  122. * Removes the fallback from the bound mesh.
  123. */
  124. EffectFallbacks.prototype.unBindMesh = function () {
  125. this._mesh = null;
  126. };
  127. /**
  128. * Adds a fallback on the specified property.
  129. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  130. * @param define The name of the define in the shader
  131. */
  132. EffectFallbacks.prototype.addFallback = function (rank, define) {
  133. if (!this._defines[rank]) {
  134. if (rank < this._currentRank) {
  135. this._currentRank = rank;
  136. }
  137. if (rank > this._maxRank) {
  138. this._maxRank = rank;
  139. }
  140. this._defines[rank] = new Array();
  141. }
  142. this._defines[rank].push(define);
  143. };
  144. /**
  145. * Sets the mesh to use CPU skinning when needing to fallback.
  146. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  147. * @param mesh The mesh to use the fallbacks.
  148. */
  149. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  150. this._mesh = mesh;
  151. if (rank < this._currentRank) {
  152. this._currentRank = rank;
  153. }
  154. if (rank > this._maxRank) {
  155. this._maxRank = rank;
  156. }
  157. };
  158. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  159. /**
  160. * Checks to see if more fallbacks are still availible.
  161. */
  162. get: function () {
  163. return this._currentRank <= this._maxRank;
  164. },
  165. enumerable: true,
  166. configurable: true
  167. });
  168. /**
  169. * Removes the defines that shoould be removed when falling back.
  170. * @param currentDefines defines the current define statements for the shader.
  171. * @param effect defines the current effect we try to compile
  172. * @returns The resulting defines with defines of the current rank removed.
  173. */
  174. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  175. // First we try to switch to CPU skinning
  176. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  177. this._mesh.computeBonesUsingShaders = false;
  178. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  179. var scene = this._mesh.getScene();
  180. for (var index = 0; index < scene.meshes.length; index++) {
  181. var otherMesh = scene.meshes[index];
  182. if (!otherMesh.material) {
  183. continue;
  184. }
  185. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  186. continue;
  187. }
  188. if (otherMesh.material.getEffect() === effect) {
  189. otherMesh.computeBonesUsingShaders = false;
  190. }
  191. else {
  192. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  193. var subMesh = _a[_i];
  194. var subMeshEffect = subMesh.effect;
  195. if (subMeshEffect === effect) {
  196. otherMesh.computeBonesUsingShaders = false;
  197. break;
  198. }
  199. }
  200. }
  201. }
  202. }
  203. else {
  204. var currentFallbacks = this._defines[this._currentRank];
  205. if (currentFallbacks) {
  206. for (var index = 0; index < currentFallbacks.length; index++) {
  207. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  208. }
  209. }
  210. this._currentRank++;
  211. }
  212. return currentDefines;
  213. };
  214. return EffectFallbacks;
  215. }());
  216. BABYLON.EffectFallbacks = EffectFallbacks;
  217. /**
  218. * Options to be used when creating an effect.
  219. */
  220. var EffectCreationOptions = /** @class */ (function () {
  221. function EffectCreationOptions() {
  222. }
  223. return EffectCreationOptions;
  224. }());
  225. BABYLON.EffectCreationOptions = EffectCreationOptions;
  226. /**
  227. * Effect containing vertex and fragment shader that can be executed on an object.
  228. */
  229. var Effect = /** @class */ (function () {
  230. /**
  231. * Instantiates an effect.
  232. * An effect can be used to create/manage/execute vertex and fragment shaders.
  233. * @param baseName Name of the effect.
  234. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  235. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  236. * @param samplers List of sampler variables that will be passed to the shader.
  237. * @param engine Engine to be used to render the effect
  238. * @param defines Define statements to be added to the shader.
  239. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  240. * @param onCompiled Callback that will be called when the shader is compiled.
  241. * @param onError Callback that will be called if an error occurs during shader compilation.
  242. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  243. */
  244. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  245. if (samplers === void 0) { samplers = null; }
  246. if (defines === void 0) { defines = null; }
  247. if (fallbacks === void 0) { fallbacks = null; }
  248. if (onCompiled === void 0) { onCompiled = null; }
  249. if (onError === void 0) { onError = null; }
  250. var _this = this;
  251. /**
  252. * Unique ID of the effect.
  253. */
  254. this.uniqueId = 0;
  255. /**
  256. * Observable that will be called when the shader is compiled.
  257. */
  258. this.onCompileObservable = new BABYLON.Observable();
  259. /**
  260. * Observable that will be called if an error occurs during shader compilation.
  261. */
  262. this.onErrorObservable = new BABYLON.Observable();
  263. /**
  264. * Observable that will be called when effect is bound.
  265. */
  266. this.onBindObservable = new BABYLON.Observable();
  267. this._uniformBuffersNames = {};
  268. this._isReady = false;
  269. this._compilationError = "";
  270. this.name = baseName;
  271. if (attributesNamesOrOptions.attributes) {
  272. var options = attributesNamesOrOptions;
  273. this._engine = uniformsNamesOrEngine;
  274. this._attributesNames = options.attributes;
  275. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  276. this._samplers = options.samplers;
  277. this.defines = options.defines;
  278. this.onError = options.onError;
  279. this.onCompiled = options.onCompiled;
  280. this._fallbacks = options.fallbacks;
  281. this._indexParameters = options.indexParameters;
  282. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  283. if (options.uniformBuffersNames) {
  284. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  285. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  286. }
  287. }
  288. }
  289. else {
  290. this._engine = engine;
  291. this.defines = defines;
  292. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  293. this._samplers = samplers;
  294. this._attributesNames = attributesNamesOrOptions;
  295. this.onError = onError;
  296. this.onCompiled = onCompiled;
  297. this._indexParameters = indexParameters;
  298. this._fallbacks = fallbacks;
  299. }
  300. this.uniqueId = Effect._uniqueIdSeed++;
  301. if (this._getFromCache(baseName)) {
  302. this._prepareEffect();
  303. return;
  304. }
  305. var vertexSource;
  306. var fragmentSource;
  307. if (baseName.vertexElement) {
  308. vertexSource = document.getElementById(baseName.vertexElement);
  309. if (!vertexSource) {
  310. vertexSource = baseName.vertexElement;
  311. }
  312. }
  313. else {
  314. vertexSource = baseName.vertex || baseName;
  315. }
  316. if (baseName.fragmentElement) {
  317. fragmentSource = document.getElementById(baseName.fragmentElement);
  318. if (!fragmentSource) {
  319. fragmentSource = baseName.fragmentElement;
  320. }
  321. }
  322. else {
  323. fragmentSource = baseName.fragment || baseName;
  324. }
  325. var finalVertexCode;
  326. this._loadVertexShaderAsync(vertexSource)
  327. .then(function (vertexCode) {
  328. return _this._processIncludesAsync(vertexCode);
  329. })
  330. .then(function (vertexCodeWithIncludes) {
  331. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  332. return _this._loadFragmentShaderAsync(fragmentSource);
  333. })
  334. .then(function (fragmentCode) {
  335. return _this._processIncludesAsync(fragmentCode);
  336. })
  337. .then(function (fragmentCodeWithIncludes) {
  338. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  339. if (baseName) {
  340. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  341. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  342. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  343. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  344. }
  345. else {
  346. _this._vertexSourceCode = finalVertexCode;
  347. _this._fragmentSourceCode = migratedFragmentCode;
  348. }
  349. _this._setInCache(baseName);
  350. _this._prepareEffect();
  351. });
  352. }
  353. Effect.prototype._getSourceCacheKey = function (baseName) {
  354. var cacheKey = baseName;
  355. if (this._indexParameters) {
  356. for (var key in this._indexParameters) {
  357. if (this._indexParameters.hasOwnProperty(key)) {
  358. cacheKey += "|";
  359. cacheKey += key;
  360. cacheKey += "_";
  361. cacheKey += this._indexParameters[key];
  362. }
  363. }
  364. }
  365. return cacheKey;
  366. };
  367. Effect.prototype._getFromCache = function (baseName) {
  368. if (typeof baseName !== "string") {
  369. return false;
  370. }
  371. var cacheKey = this._getSourceCacheKey(baseName);
  372. var sources = Effect._sourceCache[cacheKey];
  373. if (!sources) {
  374. return false;
  375. }
  376. this._vertexSourceCode = sources.vertex;
  377. this._fragmentSourceCode = sources.fragment;
  378. return true;
  379. };
  380. Effect.prototype._setInCache = function (baseName) {
  381. if (typeof baseName !== "string") {
  382. return;
  383. }
  384. var cacheKey = this._getSourceCacheKey(baseName);
  385. Effect._sourceCache[cacheKey] = {
  386. vertex: this._vertexSourceCode,
  387. fragment: this._fragmentSourceCode
  388. };
  389. };
  390. Object.defineProperty(Effect.prototype, "key", {
  391. /**
  392. * Unique key for this effect
  393. */
  394. get: function () {
  395. return this._key;
  396. },
  397. enumerable: true,
  398. configurable: true
  399. });
  400. /**
  401. * If the effect has been compiled and prepared.
  402. * @returns if the effect is compiled and prepared.
  403. */
  404. Effect.prototype.isReady = function () {
  405. return this._isReady;
  406. };
  407. /**
  408. * The engine the effect was initialized with.
  409. * @returns the engine.
  410. */
  411. Effect.prototype.getEngine = function () {
  412. return this._engine;
  413. };
  414. /**
  415. * The compiled webGL program for the effect
  416. * @returns the webGL program.
  417. */
  418. Effect.prototype.getProgram = function () {
  419. return this._program;
  420. };
  421. /**
  422. * The set of names of attribute variables for the shader.
  423. * @returns An array of attribute names.
  424. */
  425. Effect.prototype.getAttributesNames = function () {
  426. return this._attributesNames;
  427. };
  428. /**
  429. * Returns the attribute at the given index.
  430. * @param index The index of the attribute.
  431. * @returns The location of the attribute.
  432. */
  433. Effect.prototype.getAttributeLocation = function (index) {
  434. return this._attributes[index];
  435. };
  436. /**
  437. * Returns the attribute based on the name of the variable.
  438. * @param name of the attribute to look up.
  439. * @returns the attribute location.
  440. */
  441. Effect.prototype.getAttributeLocationByName = function (name) {
  442. var index = this._attributesNames.indexOf(name);
  443. return this._attributes[index];
  444. };
  445. /**
  446. * The number of attributes.
  447. * @returns the numnber of attributes.
  448. */
  449. Effect.prototype.getAttributesCount = function () {
  450. return this._attributes.length;
  451. };
  452. /**
  453. * Gets the index of a uniform variable.
  454. * @param uniformName of the uniform to look up.
  455. * @returns the index.
  456. */
  457. Effect.prototype.getUniformIndex = function (uniformName) {
  458. return this._uniformsNames.indexOf(uniformName);
  459. };
  460. /**
  461. * Returns the attribute based on the name of the variable.
  462. * @param uniformName of the uniform to look up.
  463. * @returns the location of the uniform.
  464. */
  465. Effect.prototype.getUniform = function (uniformName) {
  466. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  467. };
  468. /**
  469. * Returns an array of sampler variable names
  470. * @returns The array of sampler variable neames.
  471. */
  472. Effect.prototype.getSamplers = function () {
  473. return this._samplers;
  474. };
  475. /**
  476. * The error from the last compilation.
  477. * @returns the error string.
  478. */
  479. Effect.prototype.getCompilationError = function () {
  480. return this._compilationError;
  481. };
  482. /**
  483. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  484. * @param func The callback to be used.
  485. */
  486. Effect.prototype.executeWhenCompiled = function (func) {
  487. if (this.isReady()) {
  488. func(this);
  489. return;
  490. }
  491. this.onCompileObservable.add(function (effect) {
  492. func(effect);
  493. });
  494. };
  495. /** @ignore */
  496. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  497. if (BABYLON.Tools.IsWindowObjectExist()) {
  498. // DOM element ?
  499. if (vertex instanceof HTMLElement) {
  500. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  501. return Promise.resolve(vertexCode);
  502. }
  503. }
  504. // Base64 encoded ?
  505. if (vertex.substr(0, 7) === "base64:") {
  506. var vertexBinary = window.atob(vertex.substr(7));
  507. return Promise.resolve(vertexBinary);
  508. }
  509. // Is in local store ?
  510. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  511. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  512. }
  513. var vertexShaderUrl;
  514. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  515. vertexShaderUrl = vertex;
  516. }
  517. else {
  518. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  519. }
  520. // Vertex shader
  521. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  522. };
  523. /** @ignore */
  524. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  525. if (BABYLON.Tools.IsWindowObjectExist()) {
  526. // DOM element ?
  527. if (fragment instanceof HTMLElement) {
  528. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  529. return Promise.resolve(fragmentCode);
  530. }
  531. }
  532. // Base64 encoded ?
  533. if (fragment.substr(0, 7) === "base64:") {
  534. var fragmentBinary = window.atob(fragment.substr(7));
  535. return Promise.resolve(fragmentBinary);
  536. }
  537. // Is in local store ?
  538. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  539. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  540. }
  541. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  542. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  543. }
  544. var fragmentShaderUrl;
  545. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  546. fragmentShaderUrl = fragment;
  547. }
  548. else {
  549. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  550. }
  551. // Fragment shader
  552. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  553. };
  554. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  555. // Rebuild shaders source code
  556. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  557. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  558. vertexCode = prefix + vertexCode;
  559. fragmentCode = prefix + fragmentCode;
  560. // Number lines of shaders source code
  561. var i = 2;
  562. var regex = /\n/gm;
  563. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  564. i = 2;
  565. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  566. // Dump shaders name and formatted source code
  567. if (this.name.vertexElement) {
  568. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  569. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  570. }
  571. else if (this.name.vertex) {
  572. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  573. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  574. }
  575. else {
  576. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  577. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  578. }
  579. };
  580. ;
  581. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  582. var preparedSourceCode = this._processPrecision(sourceCode);
  583. if (this._engine.webGLVersion == 1) {
  584. return preparedSourceCode;
  585. }
  586. // Already converted
  587. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  588. return preparedSourceCode.replace("#version 300 es", "");
  589. }
  590. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  591. // Remove extensions
  592. // #extension GL_OES_standard_derivatives : enable
  593. // #extension GL_EXT_shader_texture_lod : enable
  594. // #extension GL_EXT_frag_depth : enable
  595. // #extension GL_EXT_draw_buffers : require
  596. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  597. var result = preparedSourceCode.replace(regex, "");
  598. // Migrate to GLSL v300
  599. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  600. result = result.replace(/attribute[ \t]/g, "in ");
  601. result = result.replace(/[ \t]attribute/g, " in");
  602. if (isFragment) {
  603. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  604. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  605. result = result.replace(/texture2D\s*\(/g, "texture(");
  606. result = result.replace(/textureCube\s*\(/g, "texture(");
  607. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  608. result = result.replace(/gl_FragColor/g, "glFragColor");
  609. result = result.replace(/gl_FragData/g, "glFragData");
  610. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  611. }
  612. return result;
  613. };
  614. Effect.prototype._processIncludesAsync = function (sourceCode) {
  615. var _this = this;
  616. return new Promise(function (resolve, reject) {
  617. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  618. var match = regex.exec(sourceCode);
  619. var returnValue = sourceCode;
  620. while (match != null) {
  621. var includeFile = match[1];
  622. // Uniform declaration
  623. if (includeFile.indexOf("__decl__") !== -1) {
  624. includeFile = includeFile.replace(/__decl__/, "");
  625. if (_this._engine.supportsUniformBuffers) {
  626. includeFile = includeFile.replace(/Vertex/, "Ubo");
  627. includeFile = includeFile.replace(/Fragment/, "Ubo");
  628. }
  629. includeFile = includeFile + "Declaration";
  630. }
  631. if (Effect.IncludesShadersStore[includeFile]) {
  632. // Substitution
  633. var includeContent = Effect.IncludesShadersStore[includeFile];
  634. if (match[2]) {
  635. var splits = match[3].split(",");
  636. for (var index = 0; index < splits.length; index += 2) {
  637. var source = new RegExp(splits[index], "g");
  638. var dest = splits[index + 1];
  639. includeContent = includeContent.replace(source, dest);
  640. }
  641. }
  642. if (match[4]) {
  643. var indexString = match[5];
  644. if (indexString.indexOf("..") !== -1) {
  645. var indexSplits = indexString.split("..");
  646. var minIndex = parseInt(indexSplits[0]);
  647. var maxIndex = parseInt(indexSplits[1]);
  648. var sourceIncludeContent = includeContent.slice(0);
  649. includeContent = "";
  650. if (isNaN(maxIndex)) {
  651. maxIndex = _this._indexParameters[indexSplits[1]];
  652. }
  653. for (var i = minIndex; i < maxIndex; i++) {
  654. if (!_this._engine.supportsUniformBuffers) {
  655. // Ubo replacement
  656. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  657. return p1 + "{X}";
  658. });
  659. }
  660. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  661. }
  662. }
  663. else {
  664. if (!_this._engine.supportsUniformBuffers) {
  665. // Ubo replacement
  666. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  667. return p1 + "{X}";
  668. });
  669. }
  670. includeContent = includeContent.replace(/\{X\}/g, indexString);
  671. }
  672. }
  673. // Replace
  674. returnValue = returnValue.replace(match[0], includeContent);
  675. }
  676. else {
  677. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  678. _this._engine._loadFileAsync(includeShaderUrl)
  679. .then(function (fileContent) {
  680. Effect.IncludesShadersStore[includeFile] = fileContent;
  681. return _this._processIncludesAsync(returnValue);
  682. })
  683. .then(function (returnValue) {
  684. resolve(returnValue);
  685. });
  686. return;
  687. }
  688. match = regex.exec(sourceCode);
  689. }
  690. resolve(returnValue);
  691. });
  692. };
  693. Effect.prototype._processPrecision = function (source) {
  694. if (source.indexOf("precision highp float") === -1) {
  695. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  696. source = "precision mediump float;\n" + source;
  697. }
  698. else {
  699. source = "precision highp float;\n" + source;
  700. }
  701. }
  702. else {
  703. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  704. source = source.replace("precision highp float", "precision mediump float");
  705. }
  706. }
  707. return source;
  708. };
  709. /**
  710. * Recompiles the webGL program
  711. * @param vertexSourceCode The source code for the vertex shader.
  712. * @param fragmentSourceCode The source code for the fragment shader.
  713. * @param onCompiled Callback called when completed.
  714. * @param onError Callback called on error.
  715. */
  716. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  717. var _this = this;
  718. this._isReady = false;
  719. this._vertexSourceCodeOverride = vertexSourceCode;
  720. this._fragmentSourceCodeOverride = fragmentSourceCode;
  721. this.onError = function (effect, error) {
  722. if (onError) {
  723. onError(error);
  724. }
  725. };
  726. this.onCompiled = function () {
  727. var scenes = _this.getEngine().scenes;
  728. for (var i = 0; i < scenes.length; i++) {
  729. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  730. }
  731. if (onCompiled) {
  732. onCompiled(_this._program);
  733. }
  734. };
  735. this._fallbacks = null;
  736. this._prepareEffect();
  737. };
  738. /**
  739. * Gets the uniform locations of the the specified variable names
  740. * @param names THe names of the variables to lookup.
  741. * @returns Array of locations in the same order as variable names.
  742. */
  743. Effect.prototype.getSpecificUniformLocations = function (names) {
  744. var engine = this._engine;
  745. return engine.getUniforms(this._program, names);
  746. };
  747. /**
  748. * Prepares the effect
  749. */
  750. Effect.prototype._prepareEffect = function () {
  751. var attributesNames = this._attributesNames;
  752. var defines = this.defines;
  753. var fallbacks = this._fallbacks;
  754. this._valueCache = {};
  755. var previousProgram = this._program;
  756. try {
  757. var engine = this._engine;
  758. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  759. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  760. }
  761. else {
  762. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  763. }
  764. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  765. if (engine.supportsUniformBuffers) {
  766. for (var name in this._uniformBuffersNames) {
  767. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  768. }
  769. }
  770. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  771. this._attributes = engine.getAttributes(this._program, attributesNames);
  772. var index;
  773. for (index = 0; index < this._samplers.length; index++) {
  774. var sampler = this.getUniform(this._samplers[index]);
  775. if (sampler == null) {
  776. this._samplers.splice(index, 1);
  777. index--;
  778. }
  779. }
  780. engine.bindSamplers(this);
  781. this._compilationError = "";
  782. this._isReady = true;
  783. if (this.onCompiled) {
  784. this.onCompiled(this);
  785. }
  786. this.onCompileObservable.notifyObservers(this);
  787. this.onCompileObservable.clear();
  788. // Unbind mesh reference in fallbacks
  789. if (this._fallbacks) {
  790. this._fallbacks.unBindMesh();
  791. }
  792. if (previousProgram) {
  793. this.getEngine()._deleteProgram(previousProgram);
  794. }
  795. }
  796. catch (e) {
  797. this._compilationError = e.message;
  798. // Let's go through fallbacks then
  799. BABYLON.Tools.Error("Unable to compile effect:");
  800. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  801. return " " + uniform;
  802. }));
  803. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  804. return " " + attribute;
  805. }));
  806. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  807. BABYLON.Tools.Error("Error: " + this._compilationError);
  808. if (previousProgram) {
  809. this._program = previousProgram;
  810. this._isReady = true;
  811. if (this.onError) {
  812. this.onError(this, this._compilationError);
  813. }
  814. this.onErrorObservable.notifyObservers(this);
  815. }
  816. if (fallbacks && fallbacks.isMoreFallbacks) {
  817. BABYLON.Tools.Error("Trying next fallback.");
  818. this.defines = fallbacks.reduce(this.defines, this);
  819. this._prepareEffect();
  820. }
  821. else {
  822. if (this.onError) {
  823. this.onError(this, this._compilationError);
  824. }
  825. this.onErrorObservable.notifyObservers(this);
  826. this.onErrorObservable.clear();
  827. // Unbind mesh reference in fallbacks
  828. if (this._fallbacks) {
  829. this._fallbacks.unBindMesh();
  830. }
  831. }
  832. }
  833. };
  834. Object.defineProperty(Effect.prototype, "isSupported", {
  835. /**
  836. * Checks if the effect is supported. (Must be called after compilation)
  837. */
  838. get: function () {
  839. return this._compilationError === "";
  840. },
  841. enumerable: true,
  842. configurable: true
  843. });
  844. /**
  845. * Binds a texture to the engine to be used as output of the shader.
  846. * @param channel Name of the output variable.
  847. * @param texture Texture to bind.
  848. */
  849. Effect.prototype._bindTexture = function (channel, texture) {
  850. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  851. };
  852. /**
  853. * Sets a texture on the engine to be used in the shader.
  854. * @param channel Name of the sampler variable.
  855. * @param texture Texture to set.
  856. */
  857. Effect.prototype.setTexture = function (channel, texture) {
  858. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  859. };
  860. /**
  861. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  862. * @param channel Name of the sampler variable.
  863. * @param texture Texture to set.
  864. */
  865. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  866. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  867. };
  868. /**
  869. * Sets an array of textures on the engine to be used in the shader.
  870. * @param channel Name of the variable.
  871. * @param textures Textures to set.
  872. */
  873. Effect.prototype.setTextureArray = function (channel, textures) {
  874. if (this._samplers.indexOf(channel + "Ex") === -1) {
  875. var initialPos = this._samplers.indexOf(channel);
  876. for (var index = 1; index < textures.length; index++) {
  877. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  878. }
  879. }
  880. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  881. };
  882. /**
  883. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  884. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  885. * @param channel Name of the sampler variable.
  886. * @param postProcess Post process to get the input texture from.
  887. */
  888. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  889. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  890. };
  891. /**
  892. * Sets the output texture of the passed in post process to be input of this effect.
  893. * @param channel Name of the sampler variable.
  894. * @param postProcess Post process to get the output texture from.
  895. */
  896. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  897. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  898. };
  899. /** @ignore */
  900. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  901. var cache = this._valueCache[uniformName];
  902. var flag = matrix.updateFlag;
  903. if (cache !== undefined && cache === flag) {
  904. return false;
  905. }
  906. this._valueCache[uniformName] = flag;
  907. return true;
  908. };
  909. /** @ignore */
  910. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  911. var cache = this._valueCache[uniformName];
  912. if (!cache) {
  913. cache = [x, y];
  914. this._valueCache[uniformName] = cache;
  915. return true;
  916. }
  917. var changed = false;
  918. if (cache[0] !== x) {
  919. cache[0] = x;
  920. changed = true;
  921. }
  922. if (cache[1] !== y) {
  923. cache[1] = y;
  924. changed = true;
  925. }
  926. return changed;
  927. };
  928. /** @ignore */
  929. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  930. var cache = this._valueCache[uniformName];
  931. if (!cache) {
  932. cache = [x, y, z];
  933. this._valueCache[uniformName] = cache;
  934. return true;
  935. }
  936. var changed = false;
  937. if (cache[0] !== x) {
  938. cache[0] = x;
  939. changed = true;
  940. }
  941. if (cache[1] !== y) {
  942. cache[1] = y;
  943. changed = true;
  944. }
  945. if (cache[2] !== z) {
  946. cache[2] = z;
  947. changed = true;
  948. }
  949. return changed;
  950. };
  951. /** @ignore */
  952. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  953. var cache = this._valueCache[uniformName];
  954. if (!cache) {
  955. cache = [x, y, z, w];
  956. this._valueCache[uniformName] = cache;
  957. return true;
  958. }
  959. var changed = false;
  960. if (cache[0] !== x) {
  961. cache[0] = x;
  962. changed = true;
  963. }
  964. if (cache[1] !== y) {
  965. cache[1] = y;
  966. changed = true;
  967. }
  968. if (cache[2] !== z) {
  969. cache[2] = z;
  970. changed = true;
  971. }
  972. if (cache[3] !== w) {
  973. cache[3] = w;
  974. changed = true;
  975. }
  976. return changed;
  977. };
  978. /**
  979. * Binds a buffer to a uniform.
  980. * @param buffer Buffer to bind.
  981. * @param name Name of the uniform variable to bind to.
  982. */
  983. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  984. var bufferName = this._uniformBuffersNames[name];
  985. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  986. return;
  987. }
  988. Effect._baseCache[bufferName] = buffer;
  989. this._engine.bindUniformBufferBase(buffer, bufferName);
  990. };
  991. /**
  992. * Binds block to a uniform.
  993. * @param blockName Name of the block to bind.
  994. * @param index Index to bind.
  995. */
  996. Effect.prototype.bindUniformBlock = function (blockName, index) {
  997. this._engine.bindUniformBlock(this._program, blockName, index);
  998. };
  999. /**
  1000. * Sets an interger value on a uniform variable.
  1001. * @param uniformName Name of the variable.
  1002. * @param value Value to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setInt = function (uniformName, value) {
  1006. var cache = this._valueCache[uniformName];
  1007. if (cache !== undefined && cache === value)
  1008. return this;
  1009. this._valueCache[uniformName] = value;
  1010. this._engine.setInt(this.getUniform(uniformName), value);
  1011. return this;
  1012. };
  1013. /**
  1014. * Sets an int array on a uniform variable.
  1015. * @param uniformName Name of the variable.
  1016. * @param array array to be set.
  1017. * @returns this effect.
  1018. */
  1019. Effect.prototype.setIntArray = function (uniformName, array) {
  1020. this._valueCache[uniformName] = null;
  1021. this._engine.setIntArray(this.getUniform(uniformName), array);
  1022. return this;
  1023. };
  1024. /**
  1025. * 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)
  1026. * @param uniformName Name of the variable.
  1027. * @param array array to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setIntArray2 = function (uniformName, array) {
  1031. this._valueCache[uniformName] = null;
  1032. this._engine.setIntArray2(this.getUniform(uniformName), array);
  1033. return this;
  1034. };
  1035. /**
  1036. * 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)
  1037. * @param uniformName Name of the variable.
  1038. * @param array array to be set.
  1039. * @returns this effect.
  1040. */
  1041. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1042. this._valueCache[uniformName] = null;
  1043. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1044. return this;
  1045. };
  1046. /**
  1047. * 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)
  1048. * @param uniformName Name of the variable.
  1049. * @param array array to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1053. this._valueCache[uniformName] = null;
  1054. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1055. return this;
  1056. };
  1057. /**
  1058. * Sets an float array on a uniform variable.
  1059. * @param uniformName Name of the variable.
  1060. * @param array array to be set.
  1061. * @returns this effect.
  1062. */
  1063. Effect.prototype.setFloatArray = function (uniformName, array) {
  1064. this._valueCache[uniformName] = null;
  1065. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1066. return this;
  1067. };
  1068. /**
  1069. * 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)
  1070. * @param uniformName Name of the variable.
  1071. * @param array array to be set.
  1072. * @returns this effect.
  1073. */
  1074. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1075. this._valueCache[uniformName] = null;
  1076. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1077. return this;
  1078. };
  1079. /**
  1080. * 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)
  1081. * @param uniformName Name of the variable.
  1082. * @param array array to be set.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1086. this._valueCache[uniformName] = null;
  1087. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1088. return this;
  1089. };
  1090. /**
  1091. * 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)
  1092. * @param uniformName Name of the variable.
  1093. * @param array array to be set.
  1094. * @returns this effect.
  1095. */
  1096. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1097. this._valueCache[uniformName] = null;
  1098. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets an array on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param array array to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setArray = function (uniformName, array) {
  1108. this._valueCache[uniformName] = null;
  1109. this._engine.setArray(this.getUniform(uniformName), array);
  1110. return this;
  1111. };
  1112. /**
  1113. * 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)
  1114. * @param uniformName Name of the variable.
  1115. * @param array array to be set.
  1116. * @returns this effect.
  1117. */
  1118. Effect.prototype.setArray2 = function (uniformName, array) {
  1119. this._valueCache[uniformName] = null;
  1120. this._engine.setArray2(this.getUniform(uniformName), array);
  1121. return this;
  1122. };
  1123. /**
  1124. * 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)
  1125. * @param uniformName Name of the variable.
  1126. * @param array array to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setArray3 = function (uniformName, array) {
  1130. this._valueCache[uniformName] = null;
  1131. this._engine.setArray3(this.getUniform(uniformName), array);
  1132. return this;
  1133. };
  1134. /**
  1135. * 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)
  1136. * @param uniformName Name of the variable.
  1137. * @param array array to be set.
  1138. * @returns this effect.
  1139. */
  1140. Effect.prototype.setArray4 = function (uniformName, array) {
  1141. this._valueCache[uniformName] = null;
  1142. this._engine.setArray4(this.getUniform(uniformName), array);
  1143. return this;
  1144. };
  1145. /**
  1146. * Sets matrices on a uniform variable.
  1147. * @param uniformName Name of the variable.
  1148. * @param matrices matrices to be set.
  1149. * @returns this effect.
  1150. */
  1151. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1152. if (!matrices) {
  1153. return this;
  1154. }
  1155. this._valueCache[uniformName] = null;
  1156. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1157. return this;
  1158. };
  1159. /**
  1160. * Sets matrix on a uniform variable.
  1161. * @param uniformName Name of the variable.
  1162. * @param matrix matrix to be set.
  1163. * @returns this effect.
  1164. */
  1165. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1166. if (this._cacheMatrix(uniformName, matrix)) {
  1167. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1168. }
  1169. return this;
  1170. };
  1171. /**
  1172. * 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)
  1173. * @param uniformName Name of the variable.
  1174. * @param matrix matrix to be set.
  1175. * @returns this effect.
  1176. */
  1177. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1178. this._valueCache[uniformName] = null;
  1179. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1180. return this;
  1181. };
  1182. /**
  1183. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1184. * @param uniformName Name of the variable.
  1185. * @param matrix matrix to be set.
  1186. * @returns this effect.
  1187. */
  1188. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1189. this._valueCache[uniformName] = null;
  1190. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a float on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param value value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setFloat = function (uniformName, value) {
  1200. var cache = this._valueCache[uniformName];
  1201. if (cache !== undefined && cache === value)
  1202. return this;
  1203. this._valueCache[uniformName] = value;
  1204. this._engine.setFloat(this.getUniform(uniformName), value);
  1205. return this;
  1206. };
  1207. /**
  1208. * Sets a boolean on a uniform variable.
  1209. * @param uniformName Name of the variable.
  1210. * @param bool value to be set.
  1211. * @returns this effect.
  1212. */
  1213. Effect.prototype.setBool = function (uniformName, bool) {
  1214. var cache = this._valueCache[uniformName];
  1215. if (cache !== undefined && cache === bool)
  1216. return this;
  1217. this._valueCache[uniformName] = bool;
  1218. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1219. return this;
  1220. };
  1221. /**
  1222. * Sets a Vector2 on a uniform variable.
  1223. * @param uniformName Name of the variable.
  1224. * @param vector2 vector2 to be set.
  1225. * @returns this effect.
  1226. */
  1227. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1228. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1229. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1230. }
  1231. return this;
  1232. };
  1233. /**
  1234. * Sets a float2 on a uniform variable.
  1235. * @param uniformName Name of the variable.
  1236. * @param x First float in float2.
  1237. * @param y Second float in float2.
  1238. * @returns this effect.
  1239. */
  1240. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1241. if (this._cacheFloat2(uniformName, x, y)) {
  1242. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1243. }
  1244. return this;
  1245. };
  1246. /**
  1247. * Sets a Vector3 on a uniform variable.
  1248. * @param uniformName Name of the variable.
  1249. * @param vector3 Value to be set.
  1250. * @returns this effect.
  1251. */
  1252. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1253. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1254. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1255. }
  1256. return this;
  1257. };
  1258. /**
  1259. * Sets a float3 on a uniform variable.
  1260. * @param uniformName Name of the variable.
  1261. * @param x First float in float3.
  1262. * @param y Second float in float3.
  1263. * @param z Third float in float3.
  1264. * @returns this effect.
  1265. */
  1266. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1267. if (this._cacheFloat3(uniformName, x, y, z)) {
  1268. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1269. }
  1270. return this;
  1271. };
  1272. /**
  1273. * Sets a Vector4 on a uniform variable.
  1274. * @param uniformName Name of the variable.
  1275. * @param vector4 Value to be set.
  1276. * @returns this effect.
  1277. */
  1278. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1279. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1280. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1281. }
  1282. return this;
  1283. };
  1284. /**
  1285. * Sets a float4 on a uniform variable.
  1286. * @param uniformName Name of the variable.
  1287. * @param x First float in float4.
  1288. * @param y Second float in float4.
  1289. * @param z Third float in float4.
  1290. * @param w Fourth float in float4.
  1291. * @returns this effect.
  1292. */
  1293. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1294. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1295. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1296. }
  1297. return this;
  1298. };
  1299. /**
  1300. * Sets a Color3 on a uniform variable.
  1301. * @param uniformName Name of the variable.
  1302. * @param color3 Value to be set.
  1303. * @returns this effect.
  1304. */
  1305. Effect.prototype.setColor3 = function (uniformName, color3) {
  1306. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1307. this._engine.setColor3(this.getUniform(uniformName), color3);
  1308. }
  1309. return this;
  1310. };
  1311. /**
  1312. * Sets a Color4 on a uniform variable.
  1313. * @param uniformName Name of the variable.
  1314. * @param color3 Value to be set.
  1315. * @param alpha Alpha value to be set.
  1316. * @returns this effect.
  1317. */
  1318. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1319. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1320. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1321. }
  1322. return this;
  1323. };
  1324. /**
  1325. * Sets a Color4 on a uniform variable
  1326. * @param uniformName defines the name of the variable
  1327. * @param color4 defines the value to be set
  1328. * @returns this effect.
  1329. */
  1330. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1331. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1332. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1333. }
  1334. return this;
  1335. };
  1336. /**
  1337. * Resets the cache of effects.
  1338. */
  1339. Effect.ResetCache = function () {
  1340. Effect._baseCache = {};
  1341. };
  1342. Effect._uniqueIdSeed = 0;
  1343. Effect._baseCache = {};
  1344. Effect._sourceCache = {};
  1345. // Statics
  1346. /**
  1347. * Store of each shader (The can be looked up using effect.key)
  1348. */
  1349. Effect.ShadersStore = {};
  1350. /**
  1351. * Store of each included file for a shader (The can be looked up using effect.key)
  1352. */
  1353. Effect.IncludesShadersStore = {};
  1354. return Effect;
  1355. }());
  1356. BABYLON.Effect = Effect;
  1357. })(BABYLON || (BABYLON = {}));
  1358. //# sourceMappingURL=babylon.effect.js.map
  1359. "use strict";
  1360. //# sourceMappingURL=babylon.types.js.map
  1361. "use strict";
  1362. var BABYLON;
  1363. (function (BABYLON) {
  1364. var KeyboardEventTypes = /** @class */ (function () {
  1365. function KeyboardEventTypes() {
  1366. }
  1367. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1368. get: function () {
  1369. return KeyboardEventTypes._KEYDOWN;
  1370. },
  1371. enumerable: true,
  1372. configurable: true
  1373. });
  1374. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1375. get: function () {
  1376. return KeyboardEventTypes._KEYUP;
  1377. },
  1378. enumerable: true,
  1379. configurable: true
  1380. });
  1381. KeyboardEventTypes._KEYDOWN = 0x01;
  1382. KeyboardEventTypes._KEYUP = 0x02;
  1383. return KeyboardEventTypes;
  1384. }());
  1385. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1386. var KeyboardInfo = /** @class */ (function () {
  1387. function KeyboardInfo(type, event) {
  1388. this.type = type;
  1389. this.event = event;
  1390. }
  1391. return KeyboardInfo;
  1392. }());
  1393. BABYLON.KeyboardInfo = KeyboardInfo;
  1394. /**
  1395. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1396. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1397. */
  1398. var KeyboardInfoPre = /** @class */ (function (_super) {
  1399. __extends(KeyboardInfoPre, _super);
  1400. function KeyboardInfoPre(type, event) {
  1401. var _this = _super.call(this, type, event) || this;
  1402. _this.skipOnPointerObservable = false;
  1403. return _this;
  1404. }
  1405. return KeyboardInfoPre;
  1406. }(KeyboardInfo));
  1407. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1408. })(BABYLON || (BABYLON = {}));
  1409. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1410. "use strict";
  1411. var BABYLON;
  1412. (function (BABYLON) {
  1413. var PointerEventTypes = /** @class */ (function () {
  1414. function PointerEventTypes() {
  1415. }
  1416. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1417. get: function () {
  1418. return PointerEventTypes._POINTERDOWN;
  1419. },
  1420. enumerable: true,
  1421. configurable: true
  1422. });
  1423. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1424. get: function () {
  1425. return PointerEventTypes._POINTERUP;
  1426. },
  1427. enumerable: true,
  1428. configurable: true
  1429. });
  1430. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1431. get: function () {
  1432. return PointerEventTypes._POINTERMOVE;
  1433. },
  1434. enumerable: true,
  1435. configurable: true
  1436. });
  1437. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1438. get: function () {
  1439. return PointerEventTypes._POINTERWHEEL;
  1440. },
  1441. enumerable: true,
  1442. configurable: true
  1443. });
  1444. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1445. get: function () {
  1446. return PointerEventTypes._POINTERPICK;
  1447. },
  1448. enumerable: true,
  1449. configurable: true
  1450. });
  1451. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1452. get: function () {
  1453. return PointerEventTypes._POINTERTAP;
  1454. },
  1455. enumerable: true,
  1456. configurable: true
  1457. });
  1458. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1459. get: function () {
  1460. return PointerEventTypes._POINTERDOUBLETAP;
  1461. },
  1462. enumerable: true,
  1463. configurable: true
  1464. });
  1465. PointerEventTypes._POINTERDOWN = 0x01;
  1466. PointerEventTypes._POINTERUP = 0x02;
  1467. PointerEventTypes._POINTERMOVE = 0x04;
  1468. PointerEventTypes._POINTERWHEEL = 0x08;
  1469. PointerEventTypes._POINTERPICK = 0x10;
  1470. PointerEventTypes._POINTERTAP = 0x20;
  1471. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1472. return PointerEventTypes;
  1473. }());
  1474. BABYLON.PointerEventTypes = PointerEventTypes;
  1475. var PointerInfoBase = /** @class */ (function () {
  1476. function PointerInfoBase(type, event) {
  1477. this.type = type;
  1478. this.event = event;
  1479. }
  1480. return PointerInfoBase;
  1481. }());
  1482. BABYLON.PointerInfoBase = PointerInfoBase;
  1483. /**
  1484. * This class is used to store pointer related info for the onPrePointerObservable event.
  1485. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1486. */
  1487. var PointerInfoPre = /** @class */ (function (_super) {
  1488. __extends(PointerInfoPre, _super);
  1489. function PointerInfoPre(type, event, localX, localY) {
  1490. var _this = _super.call(this, type, event) || this;
  1491. _this.skipOnPointerObservable = false;
  1492. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1493. return _this;
  1494. }
  1495. return PointerInfoPre;
  1496. }(PointerInfoBase));
  1497. BABYLON.PointerInfoPre = PointerInfoPre;
  1498. /**
  1499. * This type contains all the data related to a pointer event in Babylon.js.
  1500. * 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.
  1501. */
  1502. var PointerInfo = /** @class */ (function (_super) {
  1503. __extends(PointerInfo, _super);
  1504. function PointerInfo(type, event, pickInfo) {
  1505. var _this = _super.call(this, type, event) || this;
  1506. _this.pickInfo = pickInfo;
  1507. return _this;
  1508. }
  1509. return PointerInfo;
  1510. }(PointerInfoBase));
  1511. BABYLON.PointerInfo = PointerInfo;
  1512. })(BABYLON || (BABYLON = {}));
  1513. //# sourceMappingURL=babylon.pointerEvents.js.map
  1514. "use strict";
  1515. var BABYLON;
  1516. (function (BABYLON) {
  1517. BABYLON.ToGammaSpace = 1 / 2.2;
  1518. BABYLON.ToLinearSpace = 2.2;
  1519. BABYLON.Epsilon = 0.001;
  1520. /**
  1521. * Class used to hold a RBG color
  1522. */
  1523. var Color3 = /** @class */ (function () {
  1524. /**
  1525. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1526. * @param r defines the red component (between 0 and 1, default is 0)
  1527. * @param g defines the green component (between 0 and 1, default is 0)
  1528. * @param b defines the blue component (between 0 and 1, default is 0)
  1529. */
  1530. function Color3(
  1531. /**
  1532. * Defines the red component (between 0 and 1, default is 0)
  1533. */
  1534. r,
  1535. /**
  1536. * Defines the green component (between 0 and 1, default is 0)
  1537. */
  1538. g,
  1539. /**
  1540. * Defines the blue component (between 0 and 1, default is 0)
  1541. */
  1542. b) {
  1543. if (r === void 0) { r = 0; }
  1544. if (g === void 0) { g = 0; }
  1545. if (b === void 0) { b = 0; }
  1546. this.r = r;
  1547. this.g = g;
  1548. this.b = b;
  1549. }
  1550. /**
  1551. * Creates a string with the Color3 current values
  1552. * @returns the string representation of the Color3 object
  1553. */
  1554. Color3.prototype.toString = function () {
  1555. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1556. };
  1557. /**
  1558. * Returns the string "Color3"
  1559. * @returns "Color3"
  1560. */
  1561. Color3.prototype.getClassName = function () {
  1562. return "Color3";
  1563. };
  1564. /**
  1565. * Compute the Color3 hash code
  1566. * @returns an unique number that can be used to hash Color3 objects
  1567. */
  1568. Color3.prototype.getHashCode = function () {
  1569. var hash = this.r || 0;
  1570. hash = (hash * 397) ^ (this.g || 0);
  1571. hash = (hash * 397) ^ (this.b || 0);
  1572. return hash;
  1573. };
  1574. // Operators
  1575. /**
  1576. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1577. * @param array defines the array where to store the r,g,b components
  1578. * @param index defines an optional index in the target array to define where to start storing values
  1579. * @returns the current Color3 object
  1580. */
  1581. Color3.prototype.toArray = function (array, index) {
  1582. if (index === undefined) {
  1583. index = 0;
  1584. }
  1585. array[index] = this.r;
  1586. array[index + 1] = this.g;
  1587. array[index + 2] = this.b;
  1588. return this;
  1589. };
  1590. /**
  1591. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1592. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1593. * @returns a new {BABYLON.Color4} object
  1594. */
  1595. Color3.prototype.toColor4 = function (alpha) {
  1596. if (alpha === void 0) { alpha = 1; }
  1597. return new Color4(this.r, this.g, this.b, alpha);
  1598. };
  1599. /**
  1600. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1601. * @returns the new array
  1602. */
  1603. Color3.prototype.asArray = function () {
  1604. var result = new Array();
  1605. this.toArray(result, 0);
  1606. return result;
  1607. };
  1608. /**
  1609. * Returns the luminance value
  1610. * @returns a float value
  1611. */
  1612. Color3.prototype.toLuminance = function () {
  1613. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1614. };
  1615. /**
  1616. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1617. * @param otherColor defines the second operand
  1618. * @returns the new Color3 object
  1619. */
  1620. Color3.prototype.multiply = function (otherColor) {
  1621. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1622. };
  1623. /**
  1624. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1625. * @param otherColor defines the second operand
  1626. * @param result defines the Color3 object where to store the result
  1627. * @returns the current Color3
  1628. */
  1629. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1630. result.r = this.r * otherColor.r;
  1631. result.g = this.g * otherColor.g;
  1632. result.b = this.b * otherColor.b;
  1633. return this;
  1634. };
  1635. /**
  1636. * Determines equality between Color3 objects
  1637. * @param otherColor defines the second operand
  1638. * @returns true if the rgb values are equal to the passed ones
  1639. */
  1640. Color3.prototype.equals = function (otherColor) {
  1641. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1642. };
  1643. /**
  1644. * Determines equality between the current Color3 object and a set of r,b,g values
  1645. * @param r defines the red component to check
  1646. * @param g defines the green component to check
  1647. * @param b defines the blue component to check
  1648. * @returns true if the rgb values are equal to the passed ones
  1649. */
  1650. Color3.prototype.equalsFloats = function (r, g, b) {
  1651. return this.r === r && this.g === g && this.b === b;
  1652. };
  1653. /**
  1654. * Multiplies in place each rgb value by scale
  1655. * @param scale defines the scaling factor
  1656. * @returns the updated Color3
  1657. */
  1658. Color3.prototype.scale = function (scale) {
  1659. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1660. };
  1661. /**
  1662. * Multiplies the rgb values by scale and stores the result into "result"
  1663. * @param scale defines the scaling factor
  1664. * @param result defines the Color3 object where to store the result
  1665. * @returns the unmodified current Color3
  1666. */
  1667. Color3.prototype.scaleToRef = function (scale, result) {
  1668. result.r = this.r * scale;
  1669. result.g = this.g * scale;
  1670. result.b = this.b * scale;
  1671. return this;
  1672. };
  1673. /**
  1674. * Scale the current Color3 values by a factor and add the result to a given Color3
  1675. * @param scale defines the scale factor
  1676. * @param result defines color to store the result into
  1677. * @returns the unmodified current Color3
  1678. */
  1679. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1680. result.r += this.r * scale;
  1681. result.g += this.g * scale;
  1682. result.b += this.b * scale;
  1683. return this;
  1684. };
  1685. /**
  1686. * Clamps the rgb values by the min and max values and stores the result into "result"
  1687. * @param min defines minimum clamping value (default is 0)
  1688. * @param max defines maximum clamping value (default is 1)
  1689. * @param result defines color to store the result into
  1690. * @returns the original Color3
  1691. */
  1692. Color3.prototype.clampToRef = function (min, max, result) {
  1693. if (min === void 0) { min = 0; }
  1694. if (max === void 0) { max = 1; }
  1695. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1696. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1697. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1698. return this;
  1699. };
  1700. /**
  1701. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1702. * @param otherColor defines the second operand
  1703. * @returns the new Color3
  1704. */
  1705. Color3.prototype.add = function (otherColor) {
  1706. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1707. };
  1708. /**
  1709. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1710. * @param otherColor defines the second operand
  1711. * @param result defines Color3 object to store the result into
  1712. * @returns the unmodified current Color3
  1713. */
  1714. Color3.prototype.addToRef = function (otherColor, result) {
  1715. result.r = this.r + otherColor.r;
  1716. result.g = this.g + otherColor.g;
  1717. result.b = this.b + otherColor.b;
  1718. return this;
  1719. };
  1720. /**
  1721. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1722. * @param otherColor defines the second operand
  1723. * @returns the new Color3
  1724. */
  1725. Color3.prototype.subtract = function (otherColor) {
  1726. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1727. };
  1728. /**
  1729. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1730. * @param otherColor defines the second operand
  1731. * @param result defines Color3 object to store the result into
  1732. * @returns the unmodified current Color3
  1733. */
  1734. Color3.prototype.subtractToRef = function (otherColor, result) {
  1735. result.r = this.r - otherColor.r;
  1736. result.g = this.g - otherColor.g;
  1737. result.b = this.b - otherColor.b;
  1738. return this;
  1739. };
  1740. /**
  1741. * Copy the current object
  1742. * @returns a new Color3 copied the current one
  1743. */
  1744. Color3.prototype.clone = function () {
  1745. return new Color3(this.r, this.g, this.b);
  1746. };
  1747. /**
  1748. * Copies the rgb values from the source in the current Color3
  1749. * @param source defines the source Color3 object
  1750. * @returns the updated Color3 object
  1751. */
  1752. Color3.prototype.copyFrom = function (source) {
  1753. this.r = source.r;
  1754. this.g = source.g;
  1755. this.b = source.b;
  1756. return this;
  1757. };
  1758. /**
  1759. * Updates the Color3 rgb values from the passed floats
  1760. * @param r defines the red component to read from
  1761. * @param g defines the green component to read from
  1762. * @param b defines the blue component to read from
  1763. * @returns the current Color3 object
  1764. */
  1765. Color3.prototype.copyFromFloats = function (r, g, b) {
  1766. this.r = r;
  1767. this.g = g;
  1768. this.b = b;
  1769. return this;
  1770. };
  1771. /**
  1772. * Updates the Color3 rgb values from the passed floats
  1773. * @param r defines the red component to read from
  1774. * @param g defines the green component to read from
  1775. * @param b defines the blue component to read from
  1776. * @returns the current Color3 object
  1777. */
  1778. Color3.prototype.set = function (r, g, b) {
  1779. return this.copyFromFloats(r, g, b);
  1780. };
  1781. /**
  1782. * Compute the Color3 hexadecimal code as a string
  1783. * @returns a string containing the hexadecimal representation of the Color3 object
  1784. */
  1785. Color3.prototype.toHexString = function () {
  1786. var intR = (this.r * 255) | 0;
  1787. var intG = (this.g * 255) | 0;
  1788. var intB = (this.b * 255) | 0;
  1789. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1790. };
  1791. /**
  1792. * Computes a new Color3 converted from the current one to linear space
  1793. * @returns a new Color3 object
  1794. */
  1795. Color3.prototype.toLinearSpace = function () {
  1796. var convertedColor = new Color3();
  1797. this.toLinearSpaceToRef(convertedColor);
  1798. return convertedColor;
  1799. };
  1800. /**
  1801. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1802. * @param convertedColor defines the Color3 object where to store the linear space version
  1803. * @returns the unmodified Color3
  1804. */
  1805. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1806. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1807. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1808. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1809. return this;
  1810. };
  1811. /**
  1812. * Computes a new Color3 converted from the current one to gamma space
  1813. * @returns a new Color3 object
  1814. */
  1815. Color3.prototype.toGammaSpace = function () {
  1816. var convertedColor = new Color3();
  1817. this.toGammaSpaceToRef(convertedColor);
  1818. return convertedColor;
  1819. };
  1820. /**
  1821. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1822. * @param convertedColor defines the Color3 object where to store the gamma space version
  1823. * @returns the unmodified Color3
  1824. */
  1825. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1826. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1827. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1828. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1829. return this;
  1830. };
  1831. // Statics
  1832. /**
  1833. * Creates a new Color3 from the string containing valid hexadecimal values
  1834. * @param hex defines a string containing valid hexadecimal values
  1835. * @returns a new Color3 object
  1836. */
  1837. Color3.FromHexString = function (hex) {
  1838. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1839. return new Color3(0, 0, 0);
  1840. }
  1841. var r = parseInt(hex.substring(1, 3), 16);
  1842. var g = parseInt(hex.substring(3, 5), 16);
  1843. var b = parseInt(hex.substring(5, 7), 16);
  1844. return Color3.FromInts(r, g, b);
  1845. };
  1846. /**
  1847. * Creates a new Vector3 from the starting index of the passed array
  1848. * @param array defines the source array
  1849. * @param offset defines an offset in the source array
  1850. * @returns a new Color3 object
  1851. */
  1852. Color3.FromArray = function (array, offset) {
  1853. if (offset === void 0) { offset = 0; }
  1854. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1855. };
  1856. /**
  1857. * Creates a new Color3 from integer values (< 256)
  1858. * @param r defines the red component to read from (value between 0 and 255)
  1859. * @param g defines the green component to read from (value between 0 and 255)
  1860. * @param b defines the blue component to read from (value between 0 and 255)
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.FromInts = function (r, g, b) {
  1864. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1865. };
  1866. /**
  1867. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1868. * @param start defines the start Color3 value
  1869. * @param end defines the end Color3 value
  1870. * @param amount defines the gradient value between start and end
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Lerp = function (start, end, amount) {
  1874. var r = start.r + ((end.r - start.r) * amount);
  1875. var g = start.g + ((end.g - start.g) * amount);
  1876. var b = start.b + ((end.b - start.b) * amount);
  1877. return new Color3(r, g, b);
  1878. };
  1879. /**
  1880. * Returns a Color3 value containing a red color
  1881. * @returns a new Color3 object
  1882. */
  1883. Color3.Red = function () { return new Color3(1, 0, 0); };
  1884. /**
  1885. * Returns a Color3 value containing a green color
  1886. * @returns a new Color3 object
  1887. */
  1888. Color3.Green = function () { return new Color3(0, 1, 0); };
  1889. /**
  1890. * Returns a Color3 value containing a blue color
  1891. * @returns a new Color3 object
  1892. */
  1893. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1894. /**
  1895. * Returns a Color3 value containing a black color
  1896. * @returns a new Color3 object
  1897. */
  1898. Color3.Black = function () { return new Color3(0, 0, 0); };
  1899. /**
  1900. * Returns a Color3 value containing a white color
  1901. * @returns a new Color3 object
  1902. */
  1903. Color3.White = function () { return new Color3(1, 1, 1); };
  1904. /**
  1905. * Returns a Color3 value containing a purple color
  1906. * @returns a new Color3 object
  1907. */
  1908. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1909. /**
  1910. * Returns a Color3 value containing a magenta color
  1911. * @returns a new Color3 object
  1912. */
  1913. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1914. /**
  1915. * Returns a Color3 value containing a yellow color
  1916. * @returns a new Color3 object
  1917. */
  1918. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1919. /**
  1920. * Returns a Color3 value containing a gray color
  1921. * @returns a new Color3 object
  1922. */
  1923. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1924. /**
  1925. * Returns a Color3 value containing a teal color
  1926. * @returns a new Color3 object
  1927. */
  1928. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1929. /**
  1930. * Returns a Color3 value containing a random color
  1931. * @returns a new Color3 object
  1932. */
  1933. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1934. return Color3;
  1935. }());
  1936. BABYLON.Color3 = Color3;
  1937. /**
  1938. * Class used to hold a RBGA color
  1939. */
  1940. var Color4 = /** @class */ (function () {
  1941. /**
  1942. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1943. * @param r defines the red component (between 0 and 1, default is 0)
  1944. * @param g defines the green component (between 0 and 1, default is 0)
  1945. * @param b defines the blue component (between 0 and 1, default is 0)
  1946. * @param a defines the alpha component (between 0 and 1, default is 1)
  1947. */
  1948. function Color4(
  1949. /**
  1950. * Defines the red component (between 0 and 1, default is 0)
  1951. */
  1952. r,
  1953. /**
  1954. * Defines the green component (between 0 and 1, default is 0)
  1955. */
  1956. g,
  1957. /**
  1958. * Defines the blue component (between 0 and 1, default is 0)
  1959. */
  1960. b,
  1961. /**
  1962. * Defines the alpha component (between 0 and 1, default is 1)
  1963. */
  1964. a) {
  1965. if (r === void 0) { r = 0; }
  1966. if (g === void 0) { g = 0; }
  1967. if (b === void 0) { b = 0; }
  1968. if (a === void 0) { a = 1; }
  1969. this.r = r;
  1970. this.g = g;
  1971. this.b = b;
  1972. this.a = a;
  1973. }
  1974. // Operators
  1975. /**
  1976. * Adds in place the passed Color4 values to the current Color4 object
  1977. * @param right defines the second operand
  1978. * @returns the current updated Color4 object
  1979. */
  1980. Color4.prototype.addInPlace = function (right) {
  1981. this.r += right.r;
  1982. this.g += right.g;
  1983. this.b += right.b;
  1984. this.a += right.a;
  1985. return this;
  1986. };
  1987. /**
  1988. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1989. * @returns the new array
  1990. */
  1991. Color4.prototype.asArray = function () {
  1992. var result = new Array();
  1993. this.toArray(result, 0);
  1994. return result;
  1995. };
  1996. /**
  1997. * Stores from the starting index in the passed array the Color4 successive values
  1998. * @param array defines the array where to store the r,g,b components
  1999. * @param index defines an optional index in the target array to define where to start storing values
  2000. * @returns the current Color4 object
  2001. */
  2002. Color4.prototype.toArray = function (array, index) {
  2003. if (index === undefined) {
  2004. index = 0;
  2005. }
  2006. array[index] = this.r;
  2007. array[index + 1] = this.g;
  2008. array[index + 2] = this.b;
  2009. array[index + 3] = this.a;
  2010. return this;
  2011. };
  2012. /**
  2013. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  2014. * @param right defines the second operand
  2015. * @returns a new Color4 object
  2016. */
  2017. Color4.prototype.add = function (right) {
  2018. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  2019. };
  2020. /**
  2021. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  2022. * @param right defines the second operand
  2023. * @returns a new Color4 object
  2024. */
  2025. Color4.prototype.subtract = function (right) {
  2026. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  2027. };
  2028. /**
  2029. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  2030. * @param right defines the second operand
  2031. * @param result defines the Color4 object where to store the result
  2032. * @returns the current Color4 object
  2033. */
  2034. Color4.prototype.subtractToRef = function (right, result) {
  2035. result.r = this.r - right.r;
  2036. result.g = this.g - right.g;
  2037. result.b = this.b - right.b;
  2038. result.a = this.a - right.a;
  2039. return this;
  2040. };
  2041. /**
  2042. * Creates a new Color4 with the current Color4 values multiplied by scale
  2043. * @param scale defines the scaling factor to apply
  2044. * @returns a new Color4 object
  2045. */
  2046. Color4.prototype.scale = function (scale) {
  2047. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2048. };
  2049. /**
  2050. * Multiplies the current Color4 values by scale and stores the result in "result"
  2051. * @param scale defines the scaling factor to apply
  2052. * @param result defines the Color4 object where to store the result
  2053. * @returns the current unmodified Color4
  2054. */
  2055. Color4.prototype.scaleToRef = function (scale, result) {
  2056. result.r = this.r * scale;
  2057. result.g = this.g * scale;
  2058. result.b = this.b * scale;
  2059. result.a = this.a * scale;
  2060. return this;
  2061. };
  2062. /**
  2063. * Scale the current Color4 values by a factor and add the result to a given Color4
  2064. * @param scale defines the scale factor
  2065. * @param result defines the Color4 object where to store the result
  2066. * @returns the unmodified current Color4
  2067. */
  2068. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2069. result.r += this.r * scale;
  2070. result.g += this.g * scale;
  2071. result.b += this.b * scale;
  2072. result.a += this.a * scale;
  2073. return this;
  2074. };
  2075. /**
  2076. * Clamps the rgb values by the min and max values and stores the result into "result"
  2077. * @param min defines minimum clamping value (default is 0)
  2078. * @param max defines maximum clamping value (default is 1)
  2079. * @param result defines color to store the result into.
  2080. * @returns the cuurent Color4
  2081. */
  2082. Color4.prototype.clampToRef = function (min, max, result) {
  2083. if (min === void 0) { min = 0; }
  2084. if (max === void 0) { max = 1; }
  2085. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2086. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2087. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2088. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2089. return this;
  2090. };
  2091. /**
  2092. * Multipy an Color4 value by another and return a new Color4 object
  2093. * @param color defines the Color4 value to multiply by
  2094. * @returns a new Color4 object
  2095. */
  2096. Color4.prototype.multiply = function (color) {
  2097. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2098. };
  2099. /**
  2100. * Multipy a Color4 value by another and push the result in a reference value
  2101. * @param color defines the Color4 value to multiply by
  2102. * @param result defines the Color4 to fill the result in
  2103. * @returns the result Color4
  2104. */
  2105. Color4.prototype.multiplyToRef = function (color, result) {
  2106. result.r = this.r * color.r;
  2107. result.g = this.g * color.g;
  2108. result.b = this.b * color.b;
  2109. result.a = this.a * color.a;
  2110. return result;
  2111. };
  2112. /**
  2113. * Creates a string with the Color4 current values
  2114. * @returns the string representation of the Color4 object
  2115. */
  2116. Color4.prototype.toString = function () {
  2117. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2118. };
  2119. /**
  2120. * Returns the string "Color4"
  2121. * @returns "Color4"
  2122. */
  2123. Color4.prototype.getClassName = function () {
  2124. return "Color4";
  2125. };
  2126. /**
  2127. * Compute the Color4 hash code
  2128. * @returns an unique number that can be used to hash Color4 objects
  2129. */
  2130. Color4.prototype.getHashCode = function () {
  2131. var hash = this.r || 0;
  2132. hash = (hash * 397) ^ (this.g || 0);
  2133. hash = (hash * 397) ^ (this.b || 0);
  2134. hash = (hash * 397) ^ (this.a || 0);
  2135. return hash;
  2136. };
  2137. /**
  2138. * Creates a new Color4 copied from the current one
  2139. * @returns a new Color4 object
  2140. */
  2141. Color4.prototype.clone = function () {
  2142. return new Color4(this.r, this.g, this.b, this.a);
  2143. };
  2144. /**
  2145. * Copies the passed Color4 values into the current one
  2146. * @param source defines the source Color4 object
  2147. * @returns the current updated Color4 object
  2148. */
  2149. Color4.prototype.copyFrom = function (source) {
  2150. this.r = source.r;
  2151. this.g = source.g;
  2152. this.b = source.b;
  2153. this.a = source.a;
  2154. return this;
  2155. };
  2156. /**
  2157. * Copies the passed float values into the current one
  2158. * @param r defines the red component to read from
  2159. * @param g defines the green component to read from
  2160. * @param b defines the blue component to read from
  2161. * @param a defines the alpha component to read from
  2162. * @returns the current updated Color4 object
  2163. */
  2164. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2165. this.r = r;
  2166. this.g = g;
  2167. this.b = b;
  2168. this.a = a;
  2169. return this;
  2170. };
  2171. /**
  2172. * Copies the passed float values into the current one
  2173. * @param r defines the red component to read from
  2174. * @param g defines the green component to read from
  2175. * @param b defines the blue component to read from
  2176. * @param a defines the alpha component to read from
  2177. * @returns the current updated Color4 object
  2178. */
  2179. Color4.prototype.set = function (r, g, b, a) {
  2180. return this.copyFromFloats(r, g, b, a);
  2181. };
  2182. /**
  2183. * Compute the Color4 hexadecimal code as a string
  2184. * @returns a string containing the hexadecimal representation of the Color4 object
  2185. */
  2186. Color4.prototype.toHexString = function () {
  2187. var intR = (this.r * 255) | 0;
  2188. var intG = (this.g * 255) | 0;
  2189. var intB = (this.b * 255) | 0;
  2190. var intA = (this.a * 255) | 0;
  2191. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2192. };
  2193. /**
  2194. * Computes a new Color4 converted from the current one to linear space
  2195. * @returns a new Color4 object
  2196. */
  2197. Color4.prototype.toLinearSpace = function () {
  2198. var convertedColor = new Color4();
  2199. this.toLinearSpaceToRef(convertedColor);
  2200. return convertedColor;
  2201. };
  2202. /**
  2203. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2204. * @param convertedColor defines the Color4 object where to store the linear space version
  2205. * @returns the unmodified Color4
  2206. */
  2207. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2208. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2209. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2210. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2211. convertedColor.a = this.a;
  2212. return this;
  2213. };
  2214. /**
  2215. * Computes a new Color4 converted from the current one to gamma space
  2216. * @returns a new Color4 object
  2217. */
  2218. Color4.prototype.toGammaSpace = function () {
  2219. var convertedColor = new Color4();
  2220. this.toGammaSpaceToRef(convertedColor);
  2221. return convertedColor;
  2222. };
  2223. /**
  2224. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2225. * @param convertedColor defines the Color4 object where to store the gamma space version
  2226. * @returns the unmodified Color4
  2227. */
  2228. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2229. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2230. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2231. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2232. convertedColor.a = this.a;
  2233. return this;
  2234. };
  2235. // Statics
  2236. /**
  2237. * Creates a new Color4 from the string containing valid hexadecimal values
  2238. * @param hex defines a string containing valid hexadecimal values
  2239. * @returns a new Color4 object
  2240. */
  2241. Color4.FromHexString = function (hex) {
  2242. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2243. return new Color4(0.0, 0.0, 0.0, 0.0);
  2244. }
  2245. var r = parseInt(hex.substring(1, 3), 16);
  2246. var g = parseInt(hex.substring(3, 5), 16);
  2247. var b = parseInt(hex.substring(5, 7), 16);
  2248. var a = parseInt(hex.substring(7, 9), 16);
  2249. return Color4.FromInts(r, g, b, a);
  2250. };
  2251. /**
  2252. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2253. * @param left defines the start value
  2254. * @param right defines the end value
  2255. * @param amount defines the gradient factor
  2256. * @returns a new Color4 object
  2257. */
  2258. Color4.Lerp = function (left, right, amount) {
  2259. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2260. Color4.LerpToRef(left, right, amount, result);
  2261. return result;
  2262. };
  2263. /**
  2264. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2265. * @param left defines the start value
  2266. * @param right defines the end value
  2267. * @param amount defines the gradient factor
  2268. * @param result defines the Color4 object where to store data
  2269. */
  2270. Color4.LerpToRef = function (left, right, amount, result) {
  2271. result.r = left.r + (right.r - left.r) * amount;
  2272. result.g = left.g + (right.g - left.g) * amount;
  2273. result.b = left.b + (right.b - left.b) * amount;
  2274. result.a = left.a + (right.a - left.a) * amount;
  2275. };
  2276. /**
  2277. * Creates a new Color4 from the starting index element of the passed array
  2278. * @param array defines the source array to read from
  2279. * @param offset defines the offset in the source array
  2280. * @returns a new Color4 object
  2281. */
  2282. Color4.FromArray = function (array, offset) {
  2283. if (offset === void 0) { offset = 0; }
  2284. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2285. };
  2286. /**
  2287. * Creates a new Color3 from integer values (< 256)
  2288. * @param r defines the red component to read from (value between 0 and 255)
  2289. * @param g defines the green component to read from (value between 0 and 255)
  2290. * @param b defines the blue component to read from (value between 0 and 255)
  2291. * @param a defines the alpha component to read from (value between 0 and 255)
  2292. * @returns a new Color3 object
  2293. */
  2294. Color4.FromInts = function (r, g, b, a) {
  2295. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2296. };
  2297. /**
  2298. * Check the content of a given array and convert it to an array containing RGBA data
  2299. * If the original array was already containing count * 4 values then it is returned directly
  2300. * @param colors defines the array to check
  2301. * @param count defines the number of RGBA data to expect
  2302. * @returns an array containing count * 4 values (RGBA)
  2303. */
  2304. Color4.CheckColors4 = function (colors, count) {
  2305. // Check if color3 was used
  2306. if (colors.length === count * 3) {
  2307. var colors4 = [];
  2308. for (var index = 0; index < colors.length; index += 3) {
  2309. var newIndex = (index / 3) * 4;
  2310. colors4[newIndex] = colors[index];
  2311. colors4[newIndex + 1] = colors[index + 1];
  2312. colors4[newIndex + 2] = colors[index + 2];
  2313. colors4[newIndex + 3] = 1.0;
  2314. }
  2315. return colors4;
  2316. }
  2317. return colors;
  2318. };
  2319. return Color4;
  2320. }());
  2321. BABYLON.Color4 = Color4;
  2322. var Vector2 = /** @class */ (function () {
  2323. /**
  2324. * Creates a new Vector2 from the passed x and y coordinates.
  2325. */
  2326. function Vector2(x, y) {
  2327. this.x = x;
  2328. this.y = y;
  2329. }
  2330. /**
  2331. * Returns a string with the Vector2 coordinates.
  2332. */
  2333. Vector2.prototype.toString = function () {
  2334. return "{X: " + this.x + " Y:" + this.y + "}";
  2335. };
  2336. /**
  2337. * Returns the string "Vector2"
  2338. */
  2339. Vector2.prototype.getClassName = function () {
  2340. return "Vector2";
  2341. };
  2342. /**
  2343. * Returns the Vector2 hash code as a number.
  2344. */
  2345. Vector2.prototype.getHashCode = function () {
  2346. var hash = this.x || 0;
  2347. hash = (hash * 397) ^ (this.y || 0);
  2348. return hash;
  2349. };
  2350. // Operators
  2351. /**
  2352. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2353. * Returns the Vector2.
  2354. */
  2355. Vector2.prototype.toArray = function (array, index) {
  2356. if (index === void 0) { index = 0; }
  2357. array[index] = this.x;
  2358. array[index + 1] = this.y;
  2359. return this;
  2360. };
  2361. /**
  2362. * Returns a new array with 2 elements : the Vector2 coordinates.
  2363. */
  2364. Vector2.prototype.asArray = function () {
  2365. var result = new Array();
  2366. this.toArray(result, 0);
  2367. return result;
  2368. };
  2369. /**
  2370. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2371. * Returns the updated Vector2.
  2372. */
  2373. Vector2.prototype.copyFrom = function (source) {
  2374. this.x = source.x;
  2375. this.y = source.y;
  2376. return this;
  2377. };
  2378. /**
  2379. * Sets the Vector2 coordinates with the passed floats.
  2380. * Returns the updated Vector2.
  2381. */
  2382. Vector2.prototype.copyFromFloats = function (x, y) {
  2383. this.x = x;
  2384. this.y = y;
  2385. return this;
  2386. };
  2387. /**
  2388. * Sets the Vector2 coordinates with the passed floats.
  2389. * Returns the updated Vector2.
  2390. */
  2391. Vector2.prototype.set = function (x, y) {
  2392. return this.copyFromFloats(x, y);
  2393. };
  2394. /**
  2395. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2396. */
  2397. Vector2.prototype.add = function (otherVector) {
  2398. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2399. };
  2400. /**
  2401. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2402. * Returns the Vector2.
  2403. */
  2404. Vector2.prototype.addToRef = function (otherVector, result) {
  2405. result.x = this.x + otherVector.x;
  2406. result.y = this.y + otherVector.y;
  2407. return this;
  2408. };
  2409. /**
  2410. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2411. * Returns the updated Vector2.
  2412. */
  2413. Vector2.prototype.addInPlace = function (otherVector) {
  2414. this.x += otherVector.x;
  2415. this.y += otherVector.y;
  2416. return this;
  2417. };
  2418. /**
  2419. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2420. */
  2421. Vector2.prototype.addVector3 = function (otherVector) {
  2422. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2423. };
  2424. /**
  2425. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2426. */
  2427. Vector2.prototype.subtract = function (otherVector) {
  2428. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2429. };
  2430. /**
  2431. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2432. * Returns the Vector2.
  2433. */
  2434. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2435. result.x = this.x - otherVector.x;
  2436. result.y = this.y - otherVector.y;
  2437. return this;
  2438. };
  2439. /**
  2440. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2441. * Returns the updated Vector2.
  2442. */
  2443. Vector2.prototype.subtractInPlace = function (otherVector) {
  2444. this.x -= otherVector.x;
  2445. this.y -= otherVector.y;
  2446. return this;
  2447. };
  2448. /**
  2449. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2450. * Returns the updated Vector2.
  2451. */
  2452. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2453. this.x *= otherVector.x;
  2454. this.y *= otherVector.y;
  2455. return this;
  2456. };
  2457. /**
  2458. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2459. */
  2460. Vector2.prototype.multiply = function (otherVector) {
  2461. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2462. };
  2463. /**
  2464. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2465. * Returns the Vector2.
  2466. */
  2467. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2468. result.x = this.x * otherVector.x;
  2469. result.y = this.y * otherVector.y;
  2470. return this;
  2471. };
  2472. /**
  2473. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2474. */
  2475. Vector2.prototype.multiplyByFloats = function (x, y) {
  2476. return new Vector2(this.x * x, this.y * y);
  2477. };
  2478. /**
  2479. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2480. */
  2481. Vector2.prototype.divide = function (otherVector) {
  2482. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2483. };
  2484. /**
  2485. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2486. * Returns the Vector2.
  2487. */
  2488. Vector2.prototype.divideToRef = function (otherVector, result) {
  2489. result.x = this.x / otherVector.x;
  2490. result.y = this.y / otherVector.y;
  2491. return this;
  2492. };
  2493. /**
  2494. * Divides the current Vector3 coordinates by the passed ones.
  2495. * Returns the updated Vector3.
  2496. */
  2497. Vector2.prototype.divideInPlace = function (otherVector) {
  2498. return this.divideToRef(otherVector, this);
  2499. };
  2500. /**
  2501. * Returns a new Vector2 with current Vector2 negated coordinates.
  2502. */
  2503. Vector2.prototype.negate = function () {
  2504. return new Vector2(-this.x, -this.y);
  2505. };
  2506. /**
  2507. * Multiply the Vector2 coordinates by scale.
  2508. * Returns the updated Vector2.
  2509. */
  2510. Vector2.prototype.scaleInPlace = function (scale) {
  2511. this.x *= scale;
  2512. this.y *= scale;
  2513. return this;
  2514. };
  2515. /**
  2516. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2517. */
  2518. Vector2.prototype.scale = function (scale) {
  2519. var result = new Vector2(0, 0);
  2520. this.scaleToRef(scale, result);
  2521. return result;
  2522. };
  2523. /**
  2524. * Scale the current Vector2 values by a factor to a given Vector2
  2525. * @param scale defines the scale factor
  2526. * @param result defines the Vector2 object where to store the result
  2527. * @returns the unmodified current Vector2
  2528. */
  2529. Vector2.prototype.scaleToRef = function (scale, result) {
  2530. result.x = this.x * scale;
  2531. result.y = this.y * scale;
  2532. return this;
  2533. };
  2534. /**
  2535. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2536. * @param scale defines the scale factor
  2537. * @param result defines the Vector2 object where to store the result
  2538. * @returns the unmodified current Vector2
  2539. */
  2540. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2541. result.x += this.x * scale;
  2542. result.y += this.y * scale;
  2543. return this;
  2544. };
  2545. /**
  2546. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2547. */
  2548. Vector2.prototype.equals = function (otherVector) {
  2549. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2550. };
  2551. /**
  2552. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2553. */
  2554. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2555. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2556. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2557. };
  2558. // Properties
  2559. /**
  2560. * Returns the vector length (float).
  2561. */
  2562. Vector2.prototype.length = function () {
  2563. return Math.sqrt(this.x * this.x + this.y * this.y);
  2564. };
  2565. /**
  2566. * Returns the vector squared length (float);
  2567. */
  2568. Vector2.prototype.lengthSquared = function () {
  2569. return (this.x * this.x + this.y * this.y);
  2570. };
  2571. // Methods
  2572. /**
  2573. * Normalize the vector.
  2574. * Returns the updated Vector2.
  2575. */
  2576. Vector2.prototype.normalize = function () {
  2577. var len = this.length();
  2578. if (len === 0)
  2579. return this;
  2580. var num = 1.0 / len;
  2581. this.x *= num;
  2582. this.y *= num;
  2583. return this;
  2584. };
  2585. /**
  2586. * Returns a new Vector2 copied from the Vector2.
  2587. */
  2588. Vector2.prototype.clone = function () {
  2589. return new Vector2(this.x, this.y);
  2590. };
  2591. // Statics
  2592. /**
  2593. * Returns a new Vector2(0, 0)
  2594. */
  2595. Vector2.Zero = function () {
  2596. return new Vector2(0, 0);
  2597. };
  2598. /**
  2599. * Returns a new Vector2(1, 1)
  2600. */
  2601. Vector2.One = function () {
  2602. return new Vector2(1, 1);
  2603. };
  2604. /**
  2605. * Returns a new Vector2 set from the passed index element of the passed array.
  2606. */
  2607. Vector2.FromArray = function (array, offset) {
  2608. if (offset === void 0) { offset = 0; }
  2609. return new Vector2(array[offset], array[offset + 1]);
  2610. };
  2611. /**
  2612. * Sets "result" from the passed index element of the passed array.
  2613. */
  2614. Vector2.FromArrayToRef = function (array, offset, result) {
  2615. result.x = array[offset];
  2616. result.y = array[offset + 1];
  2617. };
  2618. /**
  2619. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2620. */
  2621. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2622. var squared = amount * amount;
  2623. var cubed = amount * squared;
  2624. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2625. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2626. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2627. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2628. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2629. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2630. return new Vector2(x, y);
  2631. };
  2632. /**
  2633. * 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".
  2634. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2635. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2636. */
  2637. Vector2.Clamp = function (value, min, max) {
  2638. var x = value.x;
  2639. x = (x > max.x) ? max.x : x;
  2640. x = (x < min.x) ? min.x : x;
  2641. var y = value.y;
  2642. y = (y > max.y) ? max.y : y;
  2643. y = (y < min.y) ? min.y : y;
  2644. return new Vector2(x, y);
  2645. };
  2646. /**
  2647. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2648. */
  2649. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2650. var squared = amount * amount;
  2651. var cubed = amount * squared;
  2652. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2653. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2654. var part3 = (cubed - (2.0 * squared)) + amount;
  2655. var part4 = cubed - squared;
  2656. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2657. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2658. return new Vector2(x, y);
  2659. };
  2660. /**
  2661. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2662. */
  2663. Vector2.Lerp = function (start, end, amount) {
  2664. var x = start.x + ((end.x - start.x) * amount);
  2665. var y = start.y + ((end.y - start.y) * amount);
  2666. return new Vector2(x, y);
  2667. };
  2668. /**
  2669. * Returns the dot product (float) of the vector "left" and the vector "right".
  2670. */
  2671. Vector2.Dot = function (left, right) {
  2672. return left.x * right.x + left.y * right.y;
  2673. };
  2674. /**
  2675. * Returns a new Vector2 equal to the normalized passed vector.
  2676. */
  2677. Vector2.Normalize = function (vector) {
  2678. var newVector = vector.clone();
  2679. newVector.normalize();
  2680. return newVector;
  2681. };
  2682. /**
  2683. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2684. */
  2685. Vector2.Minimize = function (left, right) {
  2686. var x = (left.x < right.x) ? left.x : right.x;
  2687. var y = (left.y < right.y) ? left.y : right.y;
  2688. return new Vector2(x, y);
  2689. };
  2690. /**
  2691. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2692. */
  2693. Vector2.Maximize = function (left, right) {
  2694. var x = (left.x > right.x) ? left.x : right.x;
  2695. var y = (left.y > right.y) ? left.y : right.y;
  2696. return new Vector2(x, y);
  2697. };
  2698. /**
  2699. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2700. */
  2701. Vector2.Transform = function (vector, transformation) {
  2702. var r = Vector2.Zero();
  2703. Vector2.TransformToRef(vector, transformation, r);
  2704. return r;
  2705. };
  2706. /**
  2707. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2708. */
  2709. Vector2.TransformToRef = function (vector, transformation, result) {
  2710. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2711. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2712. result.x = x;
  2713. result.y = y;
  2714. };
  2715. /**
  2716. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2717. */
  2718. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2719. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2720. var sign = a < 0 ? -1 : 1;
  2721. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2722. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2723. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2724. };
  2725. /**
  2726. * Returns the distance (float) between the vectors "value1" and "value2".
  2727. */
  2728. Vector2.Distance = function (value1, value2) {
  2729. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2730. };
  2731. /**
  2732. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2733. */
  2734. Vector2.DistanceSquared = function (value1, value2) {
  2735. var x = value1.x - value2.x;
  2736. var y = value1.y - value2.y;
  2737. return (x * x) + (y * y);
  2738. };
  2739. /**
  2740. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2741. */
  2742. Vector2.Center = function (value1, value2) {
  2743. var center = value1.add(value2);
  2744. center.scaleInPlace(0.5);
  2745. return center;
  2746. };
  2747. /**
  2748. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2749. */
  2750. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2751. var l2 = Vector2.DistanceSquared(segA, segB);
  2752. if (l2 === 0.0) {
  2753. return Vector2.Distance(p, segA);
  2754. }
  2755. var v = segB.subtract(segA);
  2756. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2757. var proj = segA.add(v.multiplyByFloats(t, t));
  2758. return Vector2.Distance(p, proj);
  2759. };
  2760. return Vector2;
  2761. }());
  2762. BABYLON.Vector2 = Vector2;
  2763. /**
  2764. * Classed used to store (x,y,z) vector representation
  2765. * A Vector3 is the main object used in 3D geometry
  2766. * It can represent etiher the coordinates of a point the space, either a direction
  2767. * Reminder: Babylon.js uses a left handed forward facing system
  2768. */
  2769. var Vector3 = /** @class */ (function () {
  2770. /**
  2771. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2772. * @param x defines the first coordinates (on X axis)
  2773. * @param y defines the second coordinates (on Y axis)
  2774. * @param z defines the third coordinates (on Z axis)
  2775. */
  2776. function Vector3(
  2777. /**
  2778. * Defines the first coordinates (on X axis)
  2779. */
  2780. x,
  2781. /**
  2782. * Defines the second coordinates (on Y axis)
  2783. */
  2784. y,
  2785. /**
  2786. * Defines the third coordinates (on Z axis)
  2787. */
  2788. z) {
  2789. this.x = x;
  2790. this.y = y;
  2791. this.z = z;
  2792. }
  2793. /**
  2794. * Creates a string representation of the Vector3
  2795. * @returns a string with the Vector3 coordinates.
  2796. */
  2797. Vector3.prototype.toString = function () {
  2798. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2799. };
  2800. /**
  2801. * Gets the class name
  2802. * @returns the string "Vector3"
  2803. */
  2804. Vector3.prototype.getClassName = function () {
  2805. return "Vector3";
  2806. };
  2807. /**
  2808. * Creates the Vector3 hash code
  2809. * @returns a number which tends to be unique between Vector3 instances
  2810. */
  2811. Vector3.prototype.getHashCode = function () {
  2812. var hash = this.x || 0;
  2813. hash = (hash * 397) ^ (this.y || 0);
  2814. hash = (hash * 397) ^ (this.z || 0);
  2815. return hash;
  2816. };
  2817. // Operators
  2818. /**
  2819. * Creates an array containing three elements : the coordinates of the Vector3
  2820. * @returns a new array of numbers
  2821. */
  2822. Vector3.prototype.asArray = function () {
  2823. var result = [];
  2824. this.toArray(result, 0);
  2825. return result;
  2826. };
  2827. /**
  2828. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2829. * @param array defines the destination array
  2830. * @param index defines the offset in the destination array
  2831. * @returns the current Vector3
  2832. */
  2833. Vector3.prototype.toArray = function (array, index) {
  2834. if (index === void 0) { index = 0; }
  2835. array[index] = this.x;
  2836. array[index + 1] = this.y;
  2837. array[index + 2] = this.z;
  2838. return this;
  2839. };
  2840. /**
  2841. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2842. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2843. */
  2844. Vector3.prototype.toQuaternion = function () {
  2845. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2846. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2847. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2848. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2849. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2850. var cosy = Math.cos(this.y * 0.5);
  2851. var siny = Math.sin(this.y * 0.5);
  2852. result.x = coszMinusx * siny;
  2853. result.y = -sinzMinusx * siny;
  2854. result.z = sinxPlusz * cosy;
  2855. result.w = cosxPlusz * cosy;
  2856. return result;
  2857. };
  2858. /**
  2859. * Adds the passed vector to the current Vector3
  2860. * @param otherVector defines the second operand
  2861. * @returns the current updated Vector3
  2862. */
  2863. Vector3.prototype.addInPlace = function (otherVector) {
  2864. this.x += otherVector.x;
  2865. this.y += otherVector.y;
  2866. this.z += otherVector.z;
  2867. return this;
  2868. };
  2869. /**
  2870. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2871. * @param otherVector defines the second operand
  2872. * @returns the resulting Vector3
  2873. */
  2874. Vector3.prototype.add = function (otherVector) {
  2875. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2876. };
  2877. /**
  2878. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2879. * @param otherVector defines the second operand
  2880. * @param result defines the Vector3 object where to store the result
  2881. * @returns the current Vector3
  2882. */
  2883. Vector3.prototype.addToRef = function (otherVector, result) {
  2884. result.x = this.x + otherVector.x;
  2885. result.y = this.y + otherVector.y;
  2886. result.z = this.z + otherVector.z;
  2887. return this;
  2888. };
  2889. /**
  2890. * Subtract the passed vector from the current Vector3
  2891. * @param otherVector defines the second operand
  2892. * @returns the current updated Vector3
  2893. */
  2894. Vector3.prototype.subtractInPlace = function (otherVector) {
  2895. this.x -= otherVector.x;
  2896. this.y -= otherVector.y;
  2897. this.z -= otherVector.z;
  2898. return this;
  2899. };
  2900. /**
  2901. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2902. * @param otherVector defines the second operand
  2903. * @returns the resulting Vector3
  2904. */
  2905. Vector3.prototype.subtract = function (otherVector) {
  2906. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2907. };
  2908. /**
  2909. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2910. * @param otherVector defines the second operand
  2911. * @param result defines the Vector3 object where to store the result
  2912. * @returns the current Vector3
  2913. */
  2914. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2915. result.x = this.x - otherVector.x;
  2916. result.y = this.y - otherVector.y;
  2917. result.z = this.z - otherVector.z;
  2918. return this;
  2919. };
  2920. /**
  2921. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2922. * @param x defines the x coordinate of the operand
  2923. * @param y defines the y coordinate of the operand
  2924. * @param z defines the z coordinate of the operand
  2925. * @returns the resulting Vector3
  2926. */
  2927. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2928. return new Vector3(this.x - x, this.y - y, this.z - z);
  2929. };
  2930. /**
  2931. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2932. * @param x defines the x coordinate of the operand
  2933. * @param y defines the y coordinate of the operand
  2934. * @param z defines the z coordinate of the operand
  2935. * @param result defines the Vector3 object where to store the result
  2936. * @returns the current Vector3
  2937. */
  2938. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2939. result.x = this.x - x;
  2940. result.y = this.y - y;
  2941. result.z = this.z - z;
  2942. return this;
  2943. };
  2944. /**
  2945. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2946. * @returns a new Vector3
  2947. */
  2948. Vector3.prototype.negate = function () {
  2949. return new Vector3(-this.x, -this.y, -this.z);
  2950. };
  2951. /**
  2952. * Multiplies the Vector3 coordinates by the float "scale"
  2953. * @param scale defines the multiplier factor
  2954. * @returns the current updated Vector3
  2955. */
  2956. Vector3.prototype.scaleInPlace = function (scale) {
  2957. this.x *= scale;
  2958. this.y *= scale;
  2959. this.z *= scale;
  2960. return this;
  2961. };
  2962. /**
  2963. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2964. * @param scale defines the multiplier factor
  2965. * @returns a new Vector3
  2966. */
  2967. Vector3.prototype.scale = function (scale) {
  2968. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2969. };
  2970. /**
  2971. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2972. * @param scale defines the multiplier factor
  2973. * @param result defines the Vector3 object where to store the result
  2974. * @returns the current Vector3
  2975. */
  2976. Vector3.prototype.scaleToRef = function (scale, result) {
  2977. result.x = this.x * scale;
  2978. result.y = this.y * scale;
  2979. result.z = this.z * scale;
  2980. return this;
  2981. };
  2982. /**
  2983. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2984. * @param scale defines the scale factor
  2985. * @param result defines the Vector3 object where to store the result
  2986. * @returns the unmodified current Vector3
  2987. */
  2988. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2989. result.x += this.x * scale;
  2990. result.y += this.y * scale;
  2991. result.z += this.z * scale;
  2992. return this;
  2993. };
  2994. /**
  2995. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2996. * @param otherVector defines the second operand
  2997. * @returns true if both vectors are equals
  2998. */
  2999. Vector3.prototype.equals = function (otherVector) {
  3000. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3001. };
  3002. /**
  3003. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  3004. * @param otherVector defines the second operand
  3005. * @param epsilon defines the minimal distance to define values as equals
  3006. * @returns true if both vectors are distant less than epsilon
  3007. */
  3008. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3009. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3010. 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);
  3011. };
  3012. /**
  3013. * Returns true if the current Vector3 coordinates equals the passed floats
  3014. * @param x defines the x coordinate of the operand
  3015. * @param y defines the y coordinate of the operand
  3016. * @param z defines the z coordinate of the operand
  3017. * @returns true if both vectors are equals
  3018. */
  3019. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3020. return this.x === x && this.y === y && this.z === z;
  3021. };
  3022. /**
  3023. * Multiplies the current Vector3 coordinates by the passed ones
  3024. * @param otherVector defines the second operand
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3028. this.x *= otherVector.x;
  3029. this.y *= otherVector.y;
  3030. this.z *= otherVector.z;
  3031. return this;
  3032. };
  3033. /**
  3034. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  3035. * @param otherVector defines the second operand
  3036. * @returns the new Vector3
  3037. */
  3038. Vector3.prototype.multiply = function (otherVector) {
  3039. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3040. };
  3041. /**
  3042. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  3043. * @param otherVector defines the second operand
  3044. * @param result defines the Vector3 object where to store the result
  3045. * @returns the current Vector3
  3046. */
  3047. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3048. result.x = this.x * otherVector.x;
  3049. result.y = this.y * otherVector.y;
  3050. result.z = this.z * otherVector.z;
  3051. return this;
  3052. };
  3053. /**
  3054. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  3055. * @param x defines the x coordinate of the operand
  3056. * @param y defines the y coordinate of the operand
  3057. * @param z defines the z coordinate of the operand
  3058. * @returns the new Vector3
  3059. */
  3060. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3061. return new Vector3(this.x * x, this.y * y, this.z * z);
  3062. };
  3063. /**
  3064. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  3065. * @param otherVector defines the second operand
  3066. * @returns the new Vector3
  3067. */
  3068. Vector3.prototype.divide = function (otherVector) {
  3069. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3070. };
  3071. /**
  3072. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  3073. * @param otherVector defines the second operand
  3074. * @param result defines the Vector3 object where to store the result
  3075. * @returns the current Vector3
  3076. */
  3077. Vector3.prototype.divideToRef = function (otherVector, result) {
  3078. result.x = this.x / otherVector.x;
  3079. result.y = this.y / otherVector.y;
  3080. result.z = this.z / otherVector.z;
  3081. return this;
  3082. };
  3083. /**
  3084. * Divides the current Vector3 coordinates by the passed ones.
  3085. * @param otherVector defines the second operand
  3086. * @returns the current updated Vector3
  3087. */
  3088. Vector3.prototype.divideInPlace = function (otherVector) {
  3089. return this.divideToRef(otherVector, this);
  3090. };
  3091. /**
  3092. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3093. * @param other defines the second operand
  3094. * @returns the current updated Vector3
  3095. */
  3096. Vector3.prototype.minimizeInPlace = function (other) {
  3097. if (other.x < this.x)
  3098. this.x = other.x;
  3099. if (other.y < this.y)
  3100. this.y = other.y;
  3101. if (other.z < this.z)
  3102. this.z = other.z;
  3103. return this;
  3104. };
  3105. /**
  3106. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3107. * @param other defines the second operand
  3108. * @returns the current updated Vector3
  3109. */
  3110. Vector3.prototype.maximizeInPlace = function (other) {
  3111. if (other.x > this.x)
  3112. this.x = other.x;
  3113. if (other.y > this.y)
  3114. this.y = other.y;
  3115. if (other.z > this.z)
  3116. this.z = other.z;
  3117. return this;
  3118. };
  3119. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3120. /**
  3121. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3122. */
  3123. get: function () {
  3124. var absX = Math.abs(this.x);
  3125. var absY = Math.abs(this.y);
  3126. if (absX !== absY) {
  3127. return true;
  3128. }
  3129. var absZ = Math.abs(this.z);
  3130. if (absX !== absZ) {
  3131. return true;
  3132. }
  3133. if (absY !== absZ) {
  3134. return true;
  3135. }
  3136. return false;
  3137. },
  3138. enumerable: true,
  3139. configurable: true
  3140. });
  3141. // Properties
  3142. /**
  3143. * Gets the length of the Vector3
  3144. * @returns the length of the Vecto3
  3145. */
  3146. Vector3.prototype.length = function () {
  3147. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3148. };
  3149. /**
  3150. * Gets the squared length of the Vector3
  3151. * @returns squared length of the Vector3
  3152. */
  3153. Vector3.prototype.lengthSquared = function () {
  3154. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3155. };
  3156. /**
  3157. * Normalize the current Vector3.
  3158. * Please note that this is an in place operation.
  3159. * @returns the current updated Vector3
  3160. */
  3161. Vector3.prototype.normalize = function () {
  3162. var len = this.length();
  3163. if (len === 0 || len === 1.0)
  3164. return this;
  3165. var num = 1.0 / len;
  3166. this.x *= num;
  3167. this.y *= num;
  3168. this.z *= num;
  3169. return this;
  3170. };
  3171. /**
  3172. * Normalize the current Vector3 to a new vector
  3173. * @returns the new Vector3
  3174. */
  3175. Vector3.prototype.normalizeToNew = function () {
  3176. var normalized = new Vector3(0, 0, 0);
  3177. this.normalizeToRef(normalized);
  3178. return normalized;
  3179. };
  3180. /**
  3181. * Normalize the current Vector3 to the reference
  3182. * @param reference define the Vector3 to update
  3183. * @returns the updated Vector3
  3184. */
  3185. Vector3.prototype.normalizeToRef = function (reference) {
  3186. var len = this.length();
  3187. if (len === 0 || len === 1.0) {
  3188. reference.set(this.x, this.y, this.z);
  3189. return reference;
  3190. }
  3191. var scale = 1.0 / len;
  3192. this.scaleToRef(scale, reference);
  3193. return reference;
  3194. };
  3195. /**
  3196. * Creates a new Vector3 copied from the current Vector3
  3197. * @returns the new Vector3
  3198. */
  3199. Vector3.prototype.clone = function () {
  3200. return new Vector3(this.x, this.y, this.z);
  3201. };
  3202. /**
  3203. * Copies the passed vector coordinates to the current Vector3 ones
  3204. * @param source defines the source Vector3
  3205. * @returns the current updated Vector3
  3206. */
  3207. Vector3.prototype.copyFrom = function (source) {
  3208. this.x = source.x;
  3209. this.y = source.y;
  3210. this.z = source.z;
  3211. return this;
  3212. };
  3213. /**
  3214. * Copies the passed floats to the current Vector3 coordinates
  3215. * @param x defines the x coordinate of the operand
  3216. * @param y defines the y coordinate of the operand
  3217. * @param z defines the z coordinate of the operand
  3218. * @returns the current updated Vector3
  3219. */
  3220. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3221. this.x = x;
  3222. this.y = y;
  3223. this.z = z;
  3224. return this;
  3225. };
  3226. /**
  3227. * Copies the passed floats to the current Vector3 coordinates
  3228. * @param x defines the x coordinate of the operand
  3229. * @param y defines the y coordinate of the operand
  3230. * @param z defines the z coordinate of the operand
  3231. * @returns the current updated Vector3
  3232. */
  3233. Vector3.prototype.set = function (x, y, z) {
  3234. return this.copyFromFloats(x, y, z);
  3235. };
  3236. // Statics
  3237. /**
  3238. * Get the clip factor between two vectors
  3239. * @param vector0 defines the first operand
  3240. * @param vector1 defines the second operand
  3241. * @param axis defines the axis to use
  3242. * @param size defines the size along the axis
  3243. * @returns the clip factor
  3244. */
  3245. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3246. var d0 = Vector3.Dot(vector0, axis) - size;
  3247. var d1 = Vector3.Dot(vector1, axis) - size;
  3248. var s = d0 / (d0 - d1);
  3249. return s;
  3250. };
  3251. /**
  3252. * Get angle between two vectors
  3253. * @param vector0 angle between vector0 and vector1
  3254. * @param vector1 angle between vector0 and vector1
  3255. * @param normal direction of the normal
  3256. * @return the angle between vector0 and vector1
  3257. */
  3258. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3259. var v0 = vector0.clone().normalize();
  3260. var v1 = vector1.clone().normalize();
  3261. var dot = Vector3.Dot(v0, v1);
  3262. var n = Vector3.Cross(v0, v1);
  3263. if (Vector3.Dot(n, normal) > 0) {
  3264. return Math.acos(dot);
  3265. }
  3266. return -Math.acos(dot);
  3267. };
  3268. /**
  3269. * Returns a new Vector3 set from the index "offset" of the passed array
  3270. * @param array defines the source array
  3271. * @param offset defines the offset in the source array
  3272. * @returns the new Vector3
  3273. */
  3274. Vector3.FromArray = function (array, offset) {
  3275. if (!offset) {
  3276. offset = 0;
  3277. }
  3278. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3279. };
  3280. /**
  3281. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3282. * This function is deprecated. Use FromArray instead
  3283. * @param array defines the source array
  3284. * @param offset defines the offset in the source array
  3285. * @returns the new Vector3
  3286. */
  3287. Vector3.FromFloatArray = function (array, offset) {
  3288. return Vector3.FromArray(array, offset);
  3289. };
  3290. /**
  3291. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3292. * @param array defines the source array
  3293. * @param offset defines the offset in the source array
  3294. * @param result defines the Vector3 where to store the result
  3295. */
  3296. Vector3.FromArrayToRef = function (array, offset, result) {
  3297. result.x = array[offset];
  3298. result.y = array[offset + 1];
  3299. result.z = array[offset + 2];
  3300. };
  3301. /**
  3302. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3303. * This function is deprecated. Use FromArrayToRef instead.
  3304. * @param array defines the source array
  3305. * @param offset defines the offset in the source array
  3306. * @param result defines the Vector3 where to store the result
  3307. */
  3308. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3309. return Vector3.FromArrayToRef(array, offset, result);
  3310. };
  3311. /**
  3312. * Sets the passed vector "result" with the passed floats.
  3313. * @param x defines the x coordinate of the source
  3314. * @param y defines the y coordinate of the source
  3315. * @param z defines the z coordinate of the source
  3316. * @param result defines the Vector3 where to store the result
  3317. */
  3318. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3319. result.x = x;
  3320. result.y = y;
  3321. result.z = z;
  3322. };
  3323. /**
  3324. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3325. * @returns a new empty Vector3
  3326. */
  3327. Vector3.Zero = function () {
  3328. return new Vector3(0.0, 0.0, 0.0);
  3329. };
  3330. /**
  3331. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3332. * @returns a new unit Vector3
  3333. */
  3334. Vector3.One = function () {
  3335. return new Vector3(1.0, 1.0, 1.0);
  3336. };
  3337. /**
  3338. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3339. * @returns a new up Vector3
  3340. */
  3341. Vector3.Up = function () {
  3342. return new Vector3(0.0, 1.0, 0.0);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3346. * @returns a new forward Vector3
  3347. */
  3348. Vector3.Forward = function () {
  3349. return new Vector3(0.0, 0.0, 1.0);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3353. * @returns a new right Vector3
  3354. */
  3355. Vector3.Right = function () {
  3356. return new Vector3(1.0, 0.0, 0.0);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3360. * @returns a new left Vector3
  3361. */
  3362. Vector3.Left = function () {
  3363. return new Vector3(-1.0, 0.0, 0.0);
  3364. };
  3365. /**
  3366. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3367. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3368. * @param vector defines the Vector3 to transform
  3369. * @param transformation defines the transformation matrix
  3370. * @returns the transformed Vector3
  3371. */
  3372. Vector3.TransformCoordinates = function (vector, transformation) {
  3373. var result = Vector3.Zero();
  3374. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3375. return result;
  3376. };
  3377. /**
  3378. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3379. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3380. * @param vector defines the Vector3 to transform
  3381. * @param transformation defines the transformation matrix
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3385. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3386. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3387. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3388. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3389. result.x = x / w;
  3390. result.y = y / w;
  3391. result.z = z / w;
  3392. };
  3393. /**
  3394. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3395. * This method computes tranformed coordinates only, not transformed direction vectors
  3396. * @param x define the x coordinate of the source vector
  3397. * @param y define the y coordinate of the source vector
  3398. * @param z define the z coordinate of the source vector
  3399. * @param transformation defines the transformation matrix
  3400. * @param result defines the Vector3 where to store the result
  3401. */
  3402. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3403. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3404. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3405. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3406. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3407. result.x = rx / rw;
  3408. result.y = ry / rw;
  3409. result.z = rz / rw;
  3410. };
  3411. /**
  3412. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3413. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3414. * @param vector defines the Vector3 to transform
  3415. * @param transformation defines the transformation matrix
  3416. * @returns the new Vector3
  3417. */
  3418. Vector3.TransformNormal = function (vector, transformation) {
  3419. var result = Vector3.Zero();
  3420. Vector3.TransformNormalToRef(vector, transformation, result);
  3421. return result;
  3422. };
  3423. /**
  3424. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3425. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3426. * @param vector defines the Vector3 to transform
  3427. * @param transformation defines the transformation matrix
  3428. * @param result defines the Vector3 where to store the result
  3429. */
  3430. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3431. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3432. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3433. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3434. result.x = x;
  3435. result.y = y;
  3436. result.z = z;
  3437. };
  3438. /**
  3439. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3440. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3441. * @param x define the x coordinate of the source vector
  3442. * @param y define the y coordinate of the source vector
  3443. * @param z define the z coordinate of the source vector
  3444. * @param transformation defines the transformation matrix
  3445. * @param result defines the Vector3 where to store the result
  3446. */
  3447. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3448. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3449. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3450. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3451. };
  3452. /**
  3453. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3454. * @param value1 defines the first control point
  3455. * @param value2 defines the second control point
  3456. * @param value3 defines the third control point
  3457. * @param value4 defines the fourth control point
  3458. * @param amount defines the amount on the spline to use
  3459. * @returns the new Vector3
  3460. */
  3461. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3462. var squared = amount * amount;
  3463. var cubed = amount * squared;
  3464. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3465. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3466. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3467. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3468. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3469. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3470. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3471. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3472. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3473. return new Vector3(x, y, z);
  3474. };
  3475. /**
  3476. * 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"
  3477. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3478. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3479. * @param value defines the current value
  3480. * @param min defines the lower range value
  3481. * @param max defines the upper range value
  3482. * @returns the new Vector3
  3483. */
  3484. Vector3.Clamp = function (value, min, max) {
  3485. var x = value.x;
  3486. x = (x > max.x) ? max.x : x;
  3487. x = (x < min.x) ? min.x : x;
  3488. var y = value.y;
  3489. y = (y > max.y) ? max.y : y;
  3490. y = (y < min.y) ? min.y : y;
  3491. var z = value.z;
  3492. z = (z > max.z) ? max.z : z;
  3493. z = (z < min.z) ? min.z : z;
  3494. return new Vector3(x, y, z);
  3495. };
  3496. /**
  3497. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3498. * @param value1 defines the first control point
  3499. * @param tangent1 defines the first tangent vector
  3500. * @param value2 defines the second control point
  3501. * @param tangent2 defines the second tangent vector
  3502. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3503. * @returns the new Vector3
  3504. */
  3505. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3506. var squared = amount * amount;
  3507. var cubed = amount * squared;
  3508. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3509. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3510. var part3 = (cubed - (2.0 * squared)) + amount;
  3511. var part4 = cubed - squared;
  3512. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3513. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3514. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3515. return new Vector3(x, y, z);
  3516. };
  3517. /**
  3518. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3519. * @param start defines the start value
  3520. * @param end defines the end value
  3521. * @param amount max defines amount between both (between 0 and 1)
  3522. * @returns the new Vector3
  3523. */
  3524. Vector3.Lerp = function (start, end, amount) {
  3525. var result = new Vector3(0, 0, 0);
  3526. Vector3.LerpToRef(start, end, amount, result);
  3527. return result;
  3528. };
  3529. /**
  3530. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3531. * @param start defines the start value
  3532. * @param end defines the end value
  3533. * @param amount max defines amount between both (between 0 and 1)
  3534. * @param result defines the Vector3 where to store the result
  3535. */
  3536. Vector3.LerpToRef = function (start, end, amount, result) {
  3537. result.x = start.x + ((end.x - start.x) * amount);
  3538. result.y = start.y + ((end.y - start.y) * amount);
  3539. result.z = start.z + ((end.z - start.z) * amount);
  3540. };
  3541. /**
  3542. * Returns the dot product (float) between the vectors "left" and "right"
  3543. * @param left defines the left operand
  3544. * @param right defines the right operand
  3545. * @returns the dot product
  3546. */
  3547. Vector3.Dot = function (left, right) {
  3548. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3549. };
  3550. /**
  3551. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3552. * The cross product is then orthogonal to both "left" and "right"
  3553. * @param left defines the left operand
  3554. * @param right defines the right operand
  3555. * @returns the cross product
  3556. */
  3557. Vector3.Cross = function (left, right) {
  3558. var result = Vector3.Zero();
  3559. Vector3.CrossToRef(left, right, result);
  3560. return result;
  3561. };
  3562. /**
  3563. * Sets the passed vector "result" with the cross product of "left" and "right"
  3564. * The cross product is then orthogonal to both "left" and "right"
  3565. * @param left defines the left operand
  3566. * @param right defines the right operand
  3567. * @param result defines the Vector3 where to store the result
  3568. */
  3569. Vector3.CrossToRef = function (left, right, result) {
  3570. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3571. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3572. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3573. result.copyFrom(MathTmp.Vector3[0]);
  3574. };
  3575. /**
  3576. * Returns a new Vector3 as the normalization of the passed vector
  3577. * @param vector defines the Vector3 to normalize
  3578. * @returns the new Vector3
  3579. */
  3580. Vector3.Normalize = function (vector) {
  3581. var result = Vector3.Zero();
  3582. Vector3.NormalizeToRef(vector, result);
  3583. return result;
  3584. };
  3585. /**
  3586. * Sets the passed vector "result" with the normalization of the passed first vector
  3587. * @param vector defines the Vector3 to normalize
  3588. * @param result defines the Vector3 where to store the result
  3589. */
  3590. Vector3.NormalizeToRef = function (vector, result) {
  3591. result.copyFrom(vector);
  3592. result.normalize();
  3593. };
  3594. /**
  3595. * Project a Vector3 onto screen space
  3596. * @param vector defines the Vector3 to project
  3597. * @param world defines the world matrix to use
  3598. * @param transform defines the transform (view x projection) matrix to use
  3599. * @param viewport defines the screen viewport to use
  3600. * @returns the new Vector3
  3601. */
  3602. Vector3.Project = function (vector, world, transform, viewport) {
  3603. var cw = viewport.width;
  3604. var ch = viewport.height;
  3605. var cx = viewport.x;
  3606. var cy = viewport.y;
  3607. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3608. 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);
  3609. var matrix = MathTmp.Matrix[0];
  3610. world.multiplyToRef(transform, matrix);
  3611. matrix.multiplyToRef(viewportMatrix, matrix);
  3612. return Vector3.TransformCoordinates(vector, matrix);
  3613. };
  3614. /**
  3615. * Unproject from screen space to object space
  3616. * @param source defines the screen space Vector3 to use
  3617. * @param viewportWidth defines the current width of the viewport
  3618. * @param viewportHeight defines the current height of the viewport
  3619. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3620. * @param transform defines the transform (view x projection) matrix to use
  3621. * @returns the new Vector3
  3622. */
  3623. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3624. var matrix = MathTmp.Matrix[0];
  3625. world.multiplyToRef(transform, matrix);
  3626. matrix.invert();
  3627. source.x = source.x / viewportWidth * 2 - 1;
  3628. source.y = -(source.y / viewportHeight * 2 - 1);
  3629. var vector = Vector3.TransformCoordinates(source, matrix);
  3630. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3631. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3632. vector = vector.scale(1.0 / num);
  3633. }
  3634. return vector;
  3635. };
  3636. /**
  3637. * Unproject from screen space to object space
  3638. * @param source defines the screen space Vector3 to use
  3639. * @param viewportWidth defines the current width of the viewport
  3640. * @param viewportHeight defines the current height of the viewport
  3641. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3642. * @param view defines the view matrix to use
  3643. * @param projection defines the projection matrix to use
  3644. * @returns the new Vector3
  3645. */
  3646. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3647. var result = Vector3.Zero();
  3648. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3649. return result;
  3650. };
  3651. /**
  3652. * Unproject from screen space to object space
  3653. * @param source defines the screen space Vector3 to use
  3654. * @param viewportWidth defines the current width of the viewport
  3655. * @param viewportHeight defines the current height of the viewport
  3656. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3657. * @param view defines the view matrix to use
  3658. * @param projection defines the projection matrix to use
  3659. * @param result defines the Vector3 where to store the result
  3660. */
  3661. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3662. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3663. };
  3664. /**
  3665. * Unproject from screen space to object space
  3666. * @param sourceX defines the screen space x coordinate to use
  3667. * @param sourceY defines the screen space y coordinate to use
  3668. * @param sourceZ defines the screen space z coordinate to use
  3669. * @param viewportWidth defines the current width of the viewport
  3670. * @param viewportHeight defines the current height of the viewport
  3671. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3672. * @param view defines the view matrix to use
  3673. * @param projection defines the projection matrix to use
  3674. * @param result defines the Vector3 where to store the result
  3675. */
  3676. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3677. var matrix = MathTmp.Matrix[0];
  3678. world.multiplyToRef(view, matrix);
  3679. matrix.multiplyToRef(projection, matrix);
  3680. matrix.invert();
  3681. var screenSource = MathTmp.Vector3[0];
  3682. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3683. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3684. screenSource.z = 2 * sourceZ - 1.0;
  3685. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3686. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3687. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3688. result.scaleInPlace(1.0 / num);
  3689. }
  3690. };
  3691. /**
  3692. * Gets the minimal coordinate values between two Vector3
  3693. * @param left defines the first operand
  3694. * @param right defines the second operand
  3695. * @returns the new Vector3
  3696. */
  3697. Vector3.Minimize = function (left, right) {
  3698. var min = left.clone();
  3699. min.minimizeInPlace(right);
  3700. return min;
  3701. };
  3702. /**
  3703. * Gets the maximal coordinate values between two Vector3
  3704. * @param left defines the first operand
  3705. * @param right defines the second operand
  3706. * @returns the new Vector3
  3707. */
  3708. Vector3.Maximize = function (left, right) {
  3709. var max = left.clone();
  3710. max.maximizeInPlace(right);
  3711. return max;
  3712. };
  3713. /**
  3714. * Returns the distance between the vectors "value1" and "value2"
  3715. * @param value1 defines the first operand
  3716. * @param value2 defines the second operand
  3717. * @returns the distance
  3718. */
  3719. Vector3.Distance = function (value1, value2) {
  3720. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3721. };
  3722. /**
  3723. * Returns the squared distance between the vectors "value1" and "value2"
  3724. * @param value1 defines the first operand
  3725. * @param value2 defines the second operand
  3726. * @returns the squared distance
  3727. */
  3728. Vector3.DistanceSquared = function (value1, value2) {
  3729. var x = value1.x - value2.x;
  3730. var y = value1.y - value2.y;
  3731. var z = value1.z - value2.z;
  3732. return (x * x) + (y * y) + (z * z);
  3733. };
  3734. /**
  3735. * Returns a new Vector3 located at the center between "value1" and "value2"
  3736. * @param value1 defines the first operand
  3737. * @param value2 defines the second operand
  3738. * @returns the new Vector3
  3739. */
  3740. Vector3.Center = function (value1, value2) {
  3741. var center = value1.add(value2);
  3742. center.scaleInPlace(0.5);
  3743. return center;
  3744. };
  3745. /**
  3746. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3747. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3748. * to something in order to rotate it from its local system to the given target system
  3749. * Note: axis1, axis2 and axis3 are normalized during this operation
  3750. * @param axis1 defines the first axis
  3751. * @param axis2 defines the second axis
  3752. * @param axis3 defines the third axis
  3753. * @returns a new Vector3
  3754. */
  3755. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3756. var rotation = Vector3.Zero();
  3757. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3758. return rotation;
  3759. };
  3760. /**
  3761. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3762. * @param axis1 defines the first axis
  3763. * @param axis2 defines the second axis
  3764. * @param axis3 defines the third axis
  3765. * @param ref defines the Vector3 where to store the result
  3766. */
  3767. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3768. var quat = MathTmp.Quaternion[0];
  3769. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3770. quat.toEulerAnglesToRef(ref);
  3771. };
  3772. return Vector3;
  3773. }());
  3774. BABYLON.Vector3 = Vector3;
  3775. //Vector4 class created for EulerAngle class conversion to Quaternion
  3776. var Vector4 = /** @class */ (function () {
  3777. /**
  3778. * Creates a Vector4 object from the passed floats.
  3779. */
  3780. function Vector4(x, y, z, w) {
  3781. this.x = x;
  3782. this.y = y;
  3783. this.z = z;
  3784. this.w = w;
  3785. }
  3786. /**
  3787. * Returns the string with the Vector4 coordinates.
  3788. */
  3789. Vector4.prototype.toString = function () {
  3790. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3791. };
  3792. /**
  3793. * Returns the string "Vector4".
  3794. */
  3795. Vector4.prototype.getClassName = function () {
  3796. return "Vector4";
  3797. };
  3798. /**
  3799. * Returns the Vector4 hash code.
  3800. */
  3801. Vector4.prototype.getHashCode = function () {
  3802. var hash = this.x || 0;
  3803. hash = (hash * 397) ^ (this.y || 0);
  3804. hash = (hash * 397) ^ (this.z || 0);
  3805. hash = (hash * 397) ^ (this.w || 0);
  3806. return hash;
  3807. };
  3808. // Operators
  3809. /**
  3810. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3811. */
  3812. Vector4.prototype.asArray = function () {
  3813. var result = new Array();
  3814. this.toArray(result, 0);
  3815. return result;
  3816. };
  3817. /**
  3818. * Populates the passed array from the passed index with the Vector4 coordinates.
  3819. * Returns the Vector4.
  3820. */
  3821. Vector4.prototype.toArray = function (array, index) {
  3822. if (index === undefined) {
  3823. index = 0;
  3824. }
  3825. array[index] = this.x;
  3826. array[index + 1] = this.y;
  3827. array[index + 2] = this.z;
  3828. array[index + 3] = this.w;
  3829. return this;
  3830. };
  3831. /**
  3832. * Adds the passed vector to the current Vector4.
  3833. * Returns the updated Vector4.
  3834. */
  3835. Vector4.prototype.addInPlace = function (otherVector) {
  3836. this.x += otherVector.x;
  3837. this.y += otherVector.y;
  3838. this.z += otherVector.z;
  3839. this.w += otherVector.w;
  3840. return this;
  3841. };
  3842. /**
  3843. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3844. */
  3845. Vector4.prototype.add = function (otherVector) {
  3846. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3847. };
  3848. /**
  3849. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3850. * Returns the current Vector4.
  3851. */
  3852. Vector4.prototype.addToRef = function (otherVector, result) {
  3853. result.x = this.x + otherVector.x;
  3854. result.y = this.y + otherVector.y;
  3855. result.z = this.z + otherVector.z;
  3856. result.w = this.w + otherVector.w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Subtract in place the passed vector from the current Vector4.
  3861. * Returns the updated Vector4.
  3862. */
  3863. Vector4.prototype.subtractInPlace = function (otherVector) {
  3864. this.x -= otherVector.x;
  3865. this.y -= otherVector.y;
  3866. this.z -= otherVector.z;
  3867. this.w -= otherVector.w;
  3868. return this;
  3869. };
  3870. /**
  3871. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3872. */
  3873. Vector4.prototype.subtract = function (otherVector) {
  3874. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3875. };
  3876. /**
  3877. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3878. * Returns the current Vector4.
  3879. */
  3880. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3881. result.x = this.x - otherVector.x;
  3882. result.y = this.y - otherVector.y;
  3883. result.z = this.z - otherVector.z;
  3884. result.w = this.w - otherVector.w;
  3885. return this;
  3886. };
  3887. /**
  3888. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3889. */
  3890. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3891. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3892. };
  3893. /**
  3894. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3895. * Returns the current Vector4.
  3896. */
  3897. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3898. result.x = this.x - x;
  3899. result.y = this.y - y;
  3900. result.z = this.z - z;
  3901. result.w = this.w - w;
  3902. return this;
  3903. };
  3904. /**
  3905. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3906. */
  3907. Vector4.prototype.negate = function () {
  3908. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3909. };
  3910. /**
  3911. * Multiplies the current Vector4 coordinates by scale (float).
  3912. * Returns the updated Vector4.
  3913. */
  3914. Vector4.prototype.scaleInPlace = function (scale) {
  3915. this.x *= scale;
  3916. this.y *= scale;
  3917. this.z *= scale;
  3918. this.w *= scale;
  3919. return this;
  3920. };
  3921. /**
  3922. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3923. */
  3924. Vector4.prototype.scale = function (scale) {
  3925. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3926. };
  3927. /**
  3928. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3929. * Returns the current Vector4.
  3930. */
  3931. Vector4.prototype.scaleToRef = function (scale, result) {
  3932. result.x = this.x * scale;
  3933. result.y = this.y * scale;
  3934. result.z = this.z * scale;
  3935. result.w = this.w * scale;
  3936. return this;
  3937. };
  3938. /**
  3939. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3940. * @param scale defines the scale factor
  3941. * @param result defines the Vector4 object where to store the result
  3942. * @returns the unmodified current Vector4
  3943. */
  3944. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3945. result.x += this.x * scale;
  3946. result.y += this.y * scale;
  3947. result.z += this.z * scale;
  3948. result.w += this.w * scale;
  3949. return this;
  3950. };
  3951. /**
  3952. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3953. */
  3954. Vector4.prototype.equals = function (otherVector) {
  3955. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3956. };
  3957. /**
  3958. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3959. */
  3960. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3961. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3962. return otherVector
  3963. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3964. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3965. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3966. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3967. };
  3968. /**
  3969. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3970. */
  3971. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3972. return this.x === x && this.y === y && this.z === z && this.w === w;
  3973. };
  3974. /**
  3975. * Multiplies in place the current Vector4 by the passed one.
  3976. * Returns the updated Vector4.
  3977. */
  3978. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3979. this.x *= otherVector.x;
  3980. this.y *= otherVector.y;
  3981. this.z *= otherVector.z;
  3982. this.w *= otherVector.w;
  3983. return this;
  3984. };
  3985. /**
  3986. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3987. */
  3988. Vector4.prototype.multiply = function (otherVector) {
  3989. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3990. };
  3991. /**
  3992. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3993. * Returns the current Vector4.
  3994. */
  3995. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3996. result.x = this.x * otherVector.x;
  3997. result.y = this.y * otherVector.y;
  3998. result.z = this.z * otherVector.z;
  3999. result.w = this.w * otherVector.w;
  4000. return this;
  4001. };
  4002. /**
  4003. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  4004. */
  4005. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4006. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4007. };
  4008. /**
  4009. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  4010. */
  4011. Vector4.prototype.divide = function (otherVector) {
  4012. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4013. };
  4014. /**
  4015. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  4016. * Returns the current Vector4.
  4017. */
  4018. Vector4.prototype.divideToRef = function (otherVector, result) {
  4019. result.x = this.x / otherVector.x;
  4020. result.y = this.y / otherVector.y;
  4021. result.z = this.z / otherVector.z;
  4022. result.w = this.w / otherVector.w;
  4023. return this;
  4024. };
  4025. /**
  4026. * Divides the current Vector3 coordinates by the passed ones.
  4027. * @returns the updated Vector3.
  4028. */
  4029. Vector4.prototype.divideInPlace = function (otherVector) {
  4030. return this.divideToRef(otherVector, this);
  4031. };
  4032. /**
  4033. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  4034. * @param other defines the second operand
  4035. * @returns the current updated Vector4
  4036. */
  4037. Vector4.prototype.minimizeInPlace = function (other) {
  4038. if (other.x < this.x)
  4039. this.x = other.x;
  4040. if (other.y < this.y)
  4041. this.y = other.y;
  4042. if (other.z < this.z)
  4043. this.z = other.z;
  4044. if (other.w < this.w)
  4045. this.w = other.w;
  4046. return this;
  4047. };
  4048. /**
  4049. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  4050. * @param other defines the second operand
  4051. * @returns the current updated Vector4
  4052. */
  4053. Vector4.prototype.maximizeInPlace = function (other) {
  4054. if (other.x > this.x)
  4055. this.x = other.x;
  4056. if (other.y > this.y)
  4057. this.y = other.y;
  4058. if (other.z > this.z)
  4059. this.z = other.z;
  4060. if (other.w > this.w)
  4061. this.w = other.w;
  4062. return this;
  4063. };
  4064. // Properties
  4065. /**
  4066. * Returns the Vector4 length (float).
  4067. */
  4068. Vector4.prototype.length = function () {
  4069. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4070. };
  4071. /**
  4072. * Returns the Vector4 squared length (float).
  4073. */
  4074. Vector4.prototype.lengthSquared = function () {
  4075. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4076. };
  4077. // Methods
  4078. /**
  4079. * Normalizes in place the Vector4.
  4080. * Returns the updated Vector4.
  4081. */
  4082. Vector4.prototype.normalize = function () {
  4083. var len = this.length();
  4084. if (len === 0)
  4085. return this;
  4086. var num = 1.0 / len;
  4087. this.x *= num;
  4088. this.y *= num;
  4089. this.z *= num;
  4090. this.w *= num;
  4091. return this;
  4092. };
  4093. /**
  4094. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4095. */
  4096. Vector4.prototype.toVector3 = function () {
  4097. return new Vector3(this.x, this.y, this.z);
  4098. };
  4099. /**
  4100. * Returns a new Vector4 copied from the current one.
  4101. */
  4102. Vector4.prototype.clone = function () {
  4103. return new Vector4(this.x, this.y, this.z, this.w);
  4104. };
  4105. /**
  4106. * Updates the current Vector4 with the passed one coordinates.
  4107. * Returns the updated Vector4.
  4108. */
  4109. Vector4.prototype.copyFrom = function (source) {
  4110. this.x = source.x;
  4111. this.y = source.y;
  4112. this.z = source.z;
  4113. this.w = source.w;
  4114. return this;
  4115. };
  4116. /**
  4117. * Updates the current Vector4 coordinates with the passed floats.
  4118. * Returns the updated Vector4.
  4119. */
  4120. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4121. this.x = x;
  4122. this.y = y;
  4123. this.z = z;
  4124. this.w = w;
  4125. return this;
  4126. };
  4127. /**
  4128. * Updates the current Vector4 coordinates with the passed floats.
  4129. * Returns the updated Vector4.
  4130. */
  4131. Vector4.prototype.set = function (x, y, z, w) {
  4132. return this.copyFromFloats(x, y, z, w);
  4133. };
  4134. // Statics
  4135. /**
  4136. * Returns a new Vector4 set from the starting index of the passed array.
  4137. */
  4138. Vector4.FromArray = function (array, offset) {
  4139. if (!offset) {
  4140. offset = 0;
  4141. }
  4142. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4143. };
  4144. /**
  4145. * Updates the passed vector "result" from the starting index of the passed array.
  4146. */
  4147. Vector4.FromArrayToRef = function (array, offset, result) {
  4148. result.x = array[offset];
  4149. result.y = array[offset + 1];
  4150. result.z = array[offset + 2];
  4151. result.w = array[offset + 3];
  4152. };
  4153. /**
  4154. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4155. */
  4156. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4157. Vector4.FromArrayToRef(array, offset, result);
  4158. };
  4159. /**
  4160. * Updates the passed vector "result" coordinates from the passed floats.
  4161. */
  4162. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4163. result.x = x;
  4164. result.y = y;
  4165. result.z = z;
  4166. result.w = w;
  4167. };
  4168. /**
  4169. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4170. */
  4171. Vector4.Zero = function () {
  4172. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4173. };
  4174. /**
  4175. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4176. */
  4177. Vector4.One = function () {
  4178. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4179. };
  4180. /**
  4181. * Returns a new normalized Vector4 from the passed one.
  4182. */
  4183. Vector4.Normalize = function (vector) {
  4184. var result = Vector4.Zero();
  4185. Vector4.NormalizeToRef(vector, result);
  4186. return result;
  4187. };
  4188. /**
  4189. * Updates the passed vector "result" from the normalization of the passed one.
  4190. */
  4191. Vector4.NormalizeToRef = function (vector, result) {
  4192. result.copyFrom(vector);
  4193. result.normalize();
  4194. };
  4195. Vector4.Minimize = function (left, right) {
  4196. var min = left.clone();
  4197. min.minimizeInPlace(right);
  4198. return min;
  4199. };
  4200. Vector4.Maximize = function (left, right) {
  4201. var max = left.clone();
  4202. max.maximizeInPlace(right);
  4203. return max;
  4204. };
  4205. /**
  4206. * Returns the distance (float) between the vectors "value1" and "value2".
  4207. */
  4208. Vector4.Distance = function (value1, value2) {
  4209. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4210. };
  4211. /**
  4212. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4213. */
  4214. Vector4.DistanceSquared = function (value1, value2) {
  4215. var x = value1.x - value2.x;
  4216. var y = value1.y - value2.y;
  4217. var z = value1.z - value2.z;
  4218. var w = value1.w - value2.w;
  4219. return (x * x) + (y * y) + (z * z) + (w * w);
  4220. };
  4221. /**
  4222. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4223. */
  4224. Vector4.Center = function (value1, value2) {
  4225. var center = value1.add(value2);
  4226. center.scaleInPlace(0.5);
  4227. return center;
  4228. };
  4229. /**
  4230. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4231. * This methods computes transformed normalized direction vectors only.
  4232. */
  4233. Vector4.TransformNormal = function (vector, transformation) {
  4234. var result = Vector4.Zero();
  4235. Vector4.TransformNormalToRef(vector, transformation, result);
  4236. return result;
  4237. };
  4238. /**
  4239. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4240. * This methods computes transformed normalized direction vectors only.
  4241. */
  4242. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4243. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4244. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4245. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4246. result.x = x;
  4247. result.y = y;
  4248. result.z = z;
  4249. result.w = vector.w;
  4250. };
  4251. /**
  4252. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4253. * This methods computes transformed normalized direction vectors only.
  4254. */
  4255. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4256. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4257. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4258. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4259. result.w = w;
  4260. };
  4261. return Vector4;
  4262. }());
  4263. BABYLON.Vector4 = Vector4;
  4264. var Size = /** @class */ (function () {
  4265. /**
  4266. * Creates a Size object from the passed width and height (floats).
  4267. */
  4268. function Size(width, height) {
  4269. this.width = width;
  4270. this.height = height;
  4271. }
  4272. // Returns a string with the Size width and height.
  4273. Size.prototype.toString = function () {
  4274. return "{W: " + this.width + ", H: " + this.height + "}";
  4275. };
  4276. /**
  4277. * Returns the string "Size"
  4278. */
  4279. Size.prototype.getClassName = function () {
  4280. return "Size";
  4281. };
  4282. /**
  4283. * Returns the Size hash code.
  4284. */
  4285. Size.prototype.getHashCode = function () {
  4286. var hash = this.width || 0;
  4287. hash = (hash * 397) ^ (this.height || 0);
  4288. return hash;
  4289. };
  4290. /**
  4291. * Updates the current size from the passed one.
  4292. * Returns the updated Size.
  4293. */
  4294. Size.prototype.copyFrom = function (src) {
  4295. this.width = src.width;
  4296. this.height = src.height;
  4297. };
  4298. /**
  4299. * Updates in place the current Size from the passed floats.
  4300. * Returns the updated Size.
  4301. */
  4302. Size.prototype.copyFromFloats = function (width, height) {
  4303. this.width = width;
  4304. this.height = height;
  4305. return this;
  4306. };
  4307. /**
  4308. * Updates in place the current Size from the passed floats.
  4309. * Returns the updated Size.
  4310. */
  4311. Size.prototype.set = function (width, height) {
  4312. return this.copyFromFloats(width, height);
  4313. };
  4314. /**
  4315. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4316. */
  4317. Size.prototype.multiplyByFloats = function (w, h) {
  4318. return new Size(this.width * w, this.height * h);
  4319. };
  4320. /**
  4321. * Returns a new Size copied from the passed one.
  4322. */
  4323. Size.prototype.clone = function () {
  4324. return new Size(this.width, this.height);
  4325. };
  4326. /**
  4327. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4328. */
  4329. Size.prototype.equals = function (other) {
  4330. if (!other) {
  4331. return false;
  4332. }
  4333. return (this.width === other.width) && (this.height === other.height);
  4334. };
  4335. Object.defineProperty(Size.prototype, "surface", {
  4336. /**
  4337. * Returns the surface of the Size : width * height (float).
  4338. */
  4339. get: function () {
  4340. return this.width * this.height;
  4341. },
  4342. enumerable: true,
  4343. configurable: true
  4344. });
  4345. /**
  4346. * Returns a new Size set to (0.0, 0.0)
  4347. */
  4348. Size.Zero = function () {
  4349. return new Size(0.0, 0.0);
  4350. };
  4351. /**
  4352. * Returns a new Size set as the addition result of the current Size and the passed one.
  4353. */
  4354. Size.prototype.add = function (otherSize) {
  4355. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4356. return r;
  4357. };
  4358. /**
  4359. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4360. */
  4361. Size.prototype.subtract = function (otherSize) {
  4362. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4363. return r;
  4364. };
  4365. /**
  4366. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4367. */
  4368. Size.Lerp = function (start, end, amount) {
  4369. var w = start.width + ((end.width - start.width) * amount);
  4370. var h = start.height + ((end.height - start.height) * amount);
  4371. return new Size(w, h);
  4372. };
  4373. return Size;
  4374. }());
  4375. BABYLON.Size = Size;
  4376. var Quaternion = /** @class */ (function () {
  4377. /**
  4378. * Creates a new Quaternion from the passed floats.
  4379. */
  4380. function Quaternion(x, y, z, w) {
  4381. if (x === void 0) { x = 0.0; }
  4382. if (y === void 0) { y = 0.0; }
  4383. if (z === void 0) { z = 0.0; }
  4384. if (w === void 0) { w = 1.0; }
  4385. this.x = x;
  4386. this.y = y;
  4387. this.z = z;
  4388. this.w = w;
  4389. }
  4390. /**
  4391. * Returns a string with the Quaternion coordinates.
  4392. */
  4393. Quaternion.prototype.toString = function () {
  4394. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4395. };
  4396. /**
  4397. * Returns the string "Quaternion".
  4398. */
  4399. Quaternion.prototype.getClassName = function () {
  4400. return "Quaternion";
  4401. };
  4402. /**
  4403. * Returns the Quaternion hash code.
  4404. */
  4405. Quaternion.prototype.getHashCode = function () {
  4406. var hash = this.x || 0;
  4407. hash = (hash * 397) ^ (this.y || 0);
  4408. hash = (hash * 397) ^ (this.z || 0);
  4409. hash = (hash * 397) ^ (this.w || 0);
  4410. return hash;
  4411. };
  4412. /**
  4413. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4414. */
  4415. Quaternion.prototype.asArray = function () {
  4416. return [this.x, this.y, this.z, this.w];
  4417. };
  4418. /**
  4419. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4420. */
  4421. Quaternion.prototype.equals = function (otherQuaternion) {
  4422. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4423. };
  4424. /**
  4425. * Returns a new Quaternion copied from the current one.
  4426. */
  4427. Quaternion.prototype.clone = function () {
  4428. return new Quaternion(this.x, this.y, this.z, this.w);
  4429. };
  4430. /**
  4431. * Updates the current Quaternion from the passed one coordinates.
  4432. * Returns the updated Quaterion.
  4433. */
  4434. Quaternion.prototype.copyFrom = function (other) {
  4435. this.x = other.x;
  4436. this.y = other.y;
  4437. this.z = other.z;
  4438. this.w = other.w;
  4439. return this;
  4440. };
  4441. /**
  4442. * Updates the current Quaternion from the passed float coordinates.
  4443. * Returns the updated Quaterion.
  4444. */
  4445. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4446. this.x = x;
  4447. this.y = y;
  4448. this.z = z;
  4449. this.w = w;
  4450. return this;
  4451. };
  4452. /**
  4453. * Updates the current Quaternion from the passed float coordinates.
  4454. * Returns the updated Quaterion.
  4455. */
  4456. Quaternion.prototype.set = function (x, y, z, w) {
  4457. return this.copyFromFloats(x, y, z, w);
  4458. };
  4459. /**
  4460. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4461. */
  4462. Quaternion.prototype.add = function (other) {
  4463. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4464. };
  4465. /**
  4466. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4467. */
  4468. Quaternion.prototype.subtract = function (other) {
  4469. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4470. };
  4471. /**
  4472. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4473. */
  4474. Quaternion.prototype.scale = function (value) {
  4475. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4476. };
  4477. /**
  4478. * Scale the current Quaternion values by a factor to a given Quaternion
  4479. * @param scale defines the scale factor
  4480. * @param result defines the Quaternion object where to store the result
  4481. * @returns the unmodified current Quaternion
  4482. */
  4483. Quaternion.prototype.scaleToRef = function (scale, result) {
  4484. result.x = this.x * scale;
  4485. result.y = this.y * scale;
  4486. result.z = this.z * scale;
  4487. result.w = this.w * scale;
  4488. return this;
  4489. };
  4490. /**
  4491. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4492. * @param scale defines the scale factor
  4493. * @param result defines the Quaternion object where to store the result
  4494. * @returns the unmodified current Quaternion
  4495. */
  4496. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4497. result.x += this.x * scale;
  4498. result.y += this.y * scale;
  4499. result.z += this.z * scale;
  4500. result.w += this.w * scale;
  4501. return this;
  4502. };
  4503. /**
  4504. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4505. */
  4506. Quaternion.prototype.multiply = function (q1) {
  4507. var result = new Quaternion(0, 0, 0, 1.0);
  4508. this.multiplyToRef(q1, result);
  4509. return result;
  4510. };
  4511. /**
  4512. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4513. * Returns the current Quaternion.
  4514. */
  4515. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4516. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4517. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4518. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4519. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4520. result.copyFromFloats(x, y, z, w);
  4521. return this;
  4522. };
  4523. /**
  4524. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4525. * Returns the updated Quaternion.
  4526. */
  4527. Quaternion.prototype.multiplyInPlace = function (q1) {
  4528. this.multiplyToRef(q1, this);
  4529. return this;
  4530. };
  4531. /**
  4532. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4533. * Returns the current Quaternion.
  4534. */
  4535. Quaternion.prototype.conjugateToRef = function (ref) {
  4536. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4537. return this;
  4538. };
  4539. /**
  4540. * Conjugates in place the current Quaternion.
  4541. * Returns the updated Quaternion.
  4542. */
  4543. Quaternion.prototype.conjugateInPlace = function () {
  4544. this.x *= -1;
  4545. this.y *= -1;
  4546. this.z *= -1;
  4547. return this;
  4548. };
  4549. /**
  4550. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4551. */
  4552. Quaternion.prototype.conjugate = function () {
  4553. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4554. return result;
  4555. };
  4556. /**
  4557. * Returns the Quaternion length (float).
  4558. */
  4559. Quaternion.prototype.length = function () {
  4560. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4561. };
  4562. /**
  4563. * Normalize in place the current Quaternion.
  4564. * Returns the updated Quaternion.
  4565. */
  4566. Quaternion.prototype.normalize = function () {
  4567. var length = 1.0 / this.length();
  4568. this.x *= length;
  4569. this.y *= length;
  4570. this.z *= length;
  4571. this.w *= length;
  4572. return this;
  4573. };
  4574. /**
  4575. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4576. * @param order is a reserved parameter and is ignore for now
  4577. * @returns the new Vector3
  4578. */
  4579. Quaternion.prototype.toEulerAngles = function (order) {
  4580. if (order === void 0) { order = "YZX"; }
  4581. var result = Vector3.Zero();
  4582. this.toEulerAnglesToRef(result, order);
  4583. return result;
  4584. };
  4585. /**
  4586. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4587. * @param result defines the vector which will be filled with the Euler angles
  4588. * @param order is a reserved parameter and is ignore for now
  4589. * @returns the current Quaternion
  4590. */
  4591. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4592. if (order === void 0) { order = "YZX"; }
  4593. var qz = this.z;
  4594. var qx = this.x;
  4595. var qy = this.y;
  4596. var qw = this.w;
  4597. var sqw = qw * qw;
  4598. var sqz = qz * qz;
  4599. var sqx = qx * qx;
  4600. var sqy = qy * qy;
  4601. var zAxisY = qy * qz - qx * qw;
  4602. var limit = .4999999;
  4603. if (zAxisY < -limit) {
  4604. result.y = 2 * Math.atan2(qy, qw);
  4605. result.x = Math.PI / 2;
  4606. result.z = 0;
  4607. }
  4608. else if (zAxisY > limit) {
  4609. result.y = 2 * Math.atan2(qy, qw);
  4610. result.x = -Math.PI / 2;
  4611. result.z = 0;
  4612. }
  4613. else {
  4614. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4615. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4616. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4617. }
  4618. return this;
  4619. };
  4620. /**
  4621. * Updates the passed rotation matrix with the current Quaternion values.
  4622. * Returns the current Quaternion.
  4623. */
  4624. Quaternion.prototype.toRotationMatrix = function (result) {
  4625. var xx = this.x * this.x;
  4626. var yy = this.y * this.y;
  4627. var zz = this.z * this.z;
  4628. var xy = this.x * this.y;
  4629. var zw = this.z * this.w;
  4630. var zx = this.z * this.x;
  4631. var yw = this.y * this.w;
  4632. var yz = this.y * this.z;
  4633. var xw = this.x * this.w;
  4634. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4635. result.m[1] = 2.0 * (xy + zw);
  4636. result.m[2] = 2.0 * (zx - yw);
  4637. result.m[3] = 0;
  4638. result.m[4] = 2.0 * (xy - zw);
  4639. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4640. result.m[6] = 2.0 * (yz + xw);
  4641. result.m[7] = 0;
  4642. result.m[8] = 2.0 * (zx + yw);
  4643. result.m[9] = 2.0 * (yz - xw);
  4644. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4645. result.m[11] = 0;
  4646. result.m[12] = 0;
  4647. result.m[13] = 0;
  4648. result.m[14] = 0;
  4649. result.m[15] = 1.0;
  4650. result._markAsUpdated();
  4651. return this;
  4652. };
  4653. /**
  4654. * Updates the current Quaternion from the passed rotation matrix values.
  4655. * Returns the updated Quaternion.
  4656. */
  4657. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4658. Quaternion.FromRotationMatrixToRef(matrix, this);
  4659. return this;
  4660. };
  4661. // Statics
  4662. /**
  4663. * Returns a new Quaternion set from the passed rotation matrix values.
  4664. */
  4665. Quaternion.FromRotationMatrix = function (matrix) {
  4666. var result = new Quaternion();
  4667. Quaternion.FromRotationMatrixToRef(matrix, result);
  4668. return result;
  4669. };
  4670. /**
  4671. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4672. */
  4673. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4674. var data = matrix.m;
  4675. var m11 = data[0], m12 = data[4], m13 = data[8];
  4676. var m21 = data[1], m22 = data[5], m23 = data[9];
  4677. var m31 = data[2], m32 = data[6], m33 = data[10];
  4678. var trace = m11 + m22 + m33;
  4679. var s;
  4680. if (trace > 0) {
  4681. s = 0.5 / Math.sqrt(trace + 1.0);
  4682. result.w = 0.25 / s;
  4683. result.x = (m32 - m23) * s;
  4684. result.y = (m13 - m31) * s;
  4685. result.z = (m21 - m12) * s;
  4686. }
  4687. else if (m11 > m22 && m11 > m33) {
  4688. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4689. result.w = (m32 - m23) / s;
  4690. result.x = 0.25 * s;
  4691. result.y = (m12 + m21) / s;
  4692. result.z = (m13 + m31) / s;
  4693. }
  4694. else if (m22 > m33) {
  4695. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4696. result.w = (m13 - m31) / s;
  4697. result.x = (m12 + m21) / s;
  4698. result.y = 0.25 * s;
  4699. result.z = (m23 + m32) / s;
  4700. }
  4701. else {
  4702. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4703. result.w = (m21 - m12) / s;
  4704. result.x = (m13 + m31) / s;
  4705. result.y = (m23 + m32) / s;
  4706. result.z = 0.25 * s;
  4707. }
  4708. };
  4709. /**
  4710. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4711. */
  4712. Quaternion.Zero = function () {
  4713. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4714. };
  4715. /**
  4716. * Returns a new Quaternion as the inverted current Quaternion.
  4717. */
  4718. Quaternion.Inverse = function (q) {
  4719. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4720. };
  4721. /**
  4722. * Returns the identity Quaternion.
  4723. */
  4724. Quaternion.Identity = function () {
  4725. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4726. };
  4727. Quaternion.IsIdentity = function (quaternion) {
  4728. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4729. };
  4730. /**
  4731. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4732. */
  4733. Quaternion.RotationAxis = function (axis, angle) {
  4734. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4735. };
  4736. /**
  4737. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4738. */
  4739. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4740. var sin = Math.sin(angle / 2);
  4741. axis.normalize();
  4742. result.w = Math.cos(angle / 2);
  4743. result.x = axis.x * sin;
  4744. result.y = axis.y * sin;
  4745. result.z = axis.z * sin;
  4746. return result;
  4747. };
  4748. /**
  4749. * Retuns a new Quaternion set from the starting index of the passed array.
  4750. */
  4751. Quaternion.FromArray = function (array, offset) {
  4752. if (!offset) {
  4753. offset = 0;
  4754. }
  4755. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4756. };
  4757. /**
  4758. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4759. */
  4760. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4761. var q = new Quaternion();
  4762. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4763. return q;
  4764. };
  4765. /**
  4766. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4767. */
  4768. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4769. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4770. var halfRoll = roll * 0.5;
  4771. var halfPitch = pitch * 0.5;
  4772. var halfYaw = yaw * 0.5;
  4773. var sinRoll = Math.sin(halfRoll);
  4774. var cosRoll = Math.cos(halfRoll);
  4775. var sinPitch = Math.sin(halfPitch);
  4776. var cosPitch = Math.cos(halfPitch);
  4777. var sinYaw = Math.sin(halfYaw);
  4778. var cosYaw = Math.cos(halfYaw);
  4779. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4780. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4781. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4782. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4783. };
  4784. /**
  4785. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4786. */
  4787. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4788. var result = new Quaternion();
  4789. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4790. return result;
  4791. };
  4792. /**
  4793. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4794. */
  4795. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4796. // Produces a quaternion from Euler angles in the z-x-z orientation
  4797. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4798. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4799. var halfBeta = beta * 0.5;
  4800. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4801. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4802. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4803. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4804. };
  4805. /**
  4806. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4807. * cf to Vector3.RotationFromAxis() documentation.
  4808. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4809. */
  4810. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4811. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4812. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4813. return quat;
  4814. };
  4815. /**
  4816. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4817. * cf to Vector3.RotationFromAxis() documentation.
  4818. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4819. */
  4820. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4821. var rotMat = MathTmp.Matrix[0];
  4822. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4823. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4824. };
  4825. Quaternion.Slerp = function (left, right, amount) {
  4826. var result = Quaternion.Identity();
  4827. Quaternion.SlerpToRef(left, right, amount, result);
  4828. return result;
  4829. };
  4830. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4831. var num2;
  4832. var num3;
  4833. var num = amount;
  4834. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4835. var flag = false;
  4836. if (num4 < 0) {
  4837. flag = true;
  4838. num4 = -num4;
  4839. }
  4840. if (num4 > 0.999999) {
  4841. num3 = 1 - num;
  4842. num2 = flag ? -num : num;
  4843. }
  4844. else {
  4845. var num5 = Math.acos(num4);
  4846. var num6 = (1.0 / Math.sin(num5));
  4847. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4848. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4849. }
  4850. result.x = (num3 * left.x) + (num2 * right.x);
  4851. result.y = (num3 * left.y) + (num2 * right.y);
  4852. result.z = (num3 * left.z) + (num2 * right.z);
  4853. result.w = (num3 * left.w) + (num2 * right.w);
  4854. };
  4855. /**
  4856. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4857. */
  4858. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4859. var squared = amount * amount;
  4860. var cubed = amount * squared;
  4861. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4862. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4863. var part3 = (cubed - (2.0 * squared)) + amount;
  4864. var part4 = cubed - squared;
  4865. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4866. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4867. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4868. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4869. return new Quaternion(x, y, z, w);
  4870. };
  4871. return Quaternion;
  4872. }());
  4873. BABYLON.Quaternion = Quaternion;
  4874. var Matrix = /** @class */ (function () {
  4875. function Matrix() {
  4876. this._isIdentity = false;
  4877. this._isIdentityDirty = true;
  4878. this.m = new Float32Array(16);
  4879. this._markAsUpdated();
  4880. }
  4881. Matrix.prototype._markAsUpdated = function () {
  4882. this.updateFlag = Matrix._updateFlagSeed++;
  4883. this._isIdentityDirty = true;
  4884. };
  4885. // Properties
  4886. /**
  4887. * Boolean : True is the matrix is the identity matrix
  4888. */
  4889. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4890. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4891. if (this._isIdentityDirty) {
  4892. this._isIdentityDirty = false;
  4893. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4894. this._isIdentity = false;
  4895. }
  4896. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4897. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4898. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4899. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4900. this._isIdentity = false;
  4901. }
  4902. else {
  4903. this._isIdentity = true;
  4904. }
  4905. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4906. this._isIdentity = false;
  4907. }
  4908. }
  4909. return this._isIdentity;
  4910. };
  4911. /**
  4912. * Returns the matrix determinant (float).
  4913. */
  4914. Matrix.prototype.determinant = function () {
  4915. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4916. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4917. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4918. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4919. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4920. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4921. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4922. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4923. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4924. };
  4925. // Methods
  4926. /**
  4927. * Returns the matrix underlying array.
  4928. */
  4929. Matrix.prototype.toArray = function () {
  4930. return this.m;
  4931. };
  4932. /**
  4933. * Returns the matrix underlying array.
  4934. */
  4935. Matrix.prototype.asArray = function () {
  4936. return this.toArray();
  4937. };
  4938. /**
  4939. * Inverts in place the Matrix.
  4940. * Returns the Matrix inverted.
  4941. */
  4942. Matrix.prototype.invert = function () {
  4943. this.invertToRef(this);
  4944. return this;
  4945. };
  4946. /**
  4947. * Sets all the matrix elements to zero.
  4948. * Returns the Matrix.
  4949. */
  4950. Matrix.prototype.reset = function () {
  4951. for (var index = 0; index < 16; index++) {
  4952. this.m[index] = 0.0;
  4953. }
  4954. this._markAsUpdated();
  4955. return this;
  4956. };
  4957. /**
  4958. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4959. */
  4960. Matrix.prototype.add = function (other) {
  4961. var result = new Matrix();
  4962. this.addToRef(other, result);
  4963. return result;
  4964. };
  4965. /**
  4966. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4967. * Returns the Matrix.
  4968. */
  4969. Matrix.prototype.addToRef = function (other, result) {
  4970. for (var index = 0; index < 16; index++) {
  4971. result.m[index] = this.m[index] + other.m[index];
  4972. }
  4973. result._markAsUpdated();
  4974. return this;
  4975. };
  4976. /**
  4977. * Adds in place the passed matrix to the current Matrix.
  4978. * Returns the updated Matrix.
  4979. */
  4980. Matrix.prototype.addToSelf = function (other) {
  4981. for (var index = 0; index < 16; index++) {
  4982. this.m[index] += other.m[index];
  4983. }
  4984. this._markAsUpdated();
  4985. return this;
  4986. };
  4987. /**
  4988. * Sets the passed matrix with the current inverted Matrix.
  4989. * Returns the unmodified current Matrix.
  4990. */
  4991. Matrix.prototype.invertToRef = function (other) {
  4992. var l1 = this.m[0];
  4993. var l2 = this.m[1];
  4994. var l3 = this.m[2];
  4995. var l4 = this.m[3];
  4996. var l5 = this.m[4];
  4997. var l6 = this.m[5];
  4998. var l7 = this.m[6];
  4999. var l8 = this.m[7];
  5000. var l9 = this.m[8];
  5001. var l10 = this.m[9];
  5002. var l11 = this.m[10];
  5003. var l12 = this.m[11];
  5004. var l13 = this.m[12];
  5005. var l14 = this.m[13];
  5006. var l15 = this.m[14];
  5007. var l16 = this.m[15];
  5008. var l17 = (l11 * l16) - (l12 * l15);
  5009. var l18 = (l10 * l16) - (l12 * l14);
  5010. var l19 = (l10 * l15) - (l11 * l14);
  5011. var l20 = (l9 * l16) - (l12 * l13);
  5012. var l21 = (l9 * l15) - (l11 * l13);
  5013. var l22 = (l9 * l14) - (l10 * l13);
  5014. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5015. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5016. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5017. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5018. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5019. var l28 = (l7 * l16) - (l8 * l15);
  5020. var l29 = (l6 * l16) - (l8 * l14);
  5021. var l30 = (l6 * l15) - (l7 * l14);
  5022. var l31 = (l5 * l16) - (l8 * l13);
  5023. var l32 = (l5 * l15) - (l7 * l13);
  5024. var l33 = (l5 * l14) - (l6 * l13);
  5025. var l34 = (l7 * l12) - (l8 * l11);
  5026. var l35 = (l6 * l12) - (l8 * l10);
  5027. var l36 = (l6 * l11) - (l7 * l10);
  5028. var l37 = (l5 * l12) - (l8 * l9);
  5029. var l38 = (l5 * l11) - (l7 * l9);
  5030. var l39 = (l5 * l10) - (l6 * l9);
  5031. other.m[0] = l23 * l27;
  5032. other.m[4] = l24 * l27;
  5033. other.m[8] = l25 * l27;
  5034. other.m[12] = l26 * l27;
  5035. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5036. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5037. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5038. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5039. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5040. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5041. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5042. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5043. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5044. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5045. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5046. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5047. other._markAsUpdated();
  5048. return this;
  5049. };
  5050. /**
  5051. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  5052. * Returns the updated Matrix.
  5053. */
  5054. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5055. this.m[12] = x;
  5056. this.m[13] = y;
  5057. this.m[14] = z;
  5058. this._markAsUpdated();
  5059. return this;
  5060. };
  5061. /**
  5062. * Inserts the translation vector in the current Matrix.
  5063. * Returns the updated Matrix.
  5064. */
  5065. Matrix.prototype.setTranslation = function (vector3) {
  5066. this.m[12] = vector3.x;
  5067. this.m[13] = vector3.y;
  5068. this.m[14] = vector3.z;
  5069. this._markAsUpdated();
  5070. return this;
  5071. };
  5072. /**
  5073. * Returns a new Vector3 as the extracted translation from the Matrix.
  5074. */
  5075. Matrix.prototype.getTranslation = function () {
  5076. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5077. };
  5078. /**
  5079. * Fill a Vector3 with the extracted translation from the Matrix.
  5080. */
  5081. Matrix.prototype.getTranslationToRef = function (result) {
  5082. result.x = this.m[12];
  5083. result.y = this.m[13];
  5084. result.z = this.m[14];
  5085. return this;
  5086. };
  5087. /**
  5088. * Remove rotation and scaling part from the Matrix.
  5089. * Returns the updated Matrix.
  5090. */
  5091. Matrix.prototype.removeRotationAndScaling = function () {
  5092. this.setRowFromFloats(0, 1, 0, 0, 0);
  5093. this.setRowFromFloats(1, 0, 1, 0, 0);
  5094. this.setRowFromFloats(2, 0, 0, 1, 0);
  5095. return this;
  5096. };
  5097. /**
  5098. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  5099. */
  5100. Matrix.prototype.multiply = function (other) {
  5101. var result = new Matrix();
  5102. this.multiplyToRef(other, result);
  5103. return result;
  5104. };
  5105. /**
  5106. * Updates the current Matrix from the passed one values.
  5107. * Returns the updated Matrix.
  5108. */
  5109. Matrix.prototype.copyFrom = function (other) {
  5110. for (var index = 0; index < 16; index++) {
  5111. this.m[index] = other.m[index];
  5112. }
  5113. this._markAsUpdated();
  5114. return this;
  5115. };
  5116. /**
  5117. * Populates the passed array from the starting index with the Matrix values.
  5118. * Returns the Matrix.
  5119. */
  5120. Matrix.prototype.copyToArray = function (array, offset) {
  5121. if (offset === void 0) { offset = 0; }
  5122. for (var index = 0; index < 16; index++) {
  5123. array[offset + index] = this.m[index];
  5124. }
  5125. return this;
  5126. };
  5127. /**
  5128. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5129. */
  5130. Matrix.prototype.multiplyToRef = function (other, result) {
  5131. this.multiplyToArray(other, result.m, 0);
  5132. result._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5137. */
  5138. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5139. var tm0 = this.m[0];
  5140. var tm1 = this.m[1];
  5141. var tm2 = this.m[2];
  5142. var tm3 = this.m[3];
  5143. var tm4 = this.m[4];
  5144. var tm5 = this.m[5];
  5145. var tm6 = this.m[6];
  5146. var tm7 = this.m[7];
  5147. var tm8 = this.m[8];
  5148. var tm9 = this.m[9];
  5149. var tm10 = this.m[10];
  5150. var tm11 = this.m[11];
  5151. var tm12 = this.m[12];
  5152. var tm13 = this.m[13];
  5153. var tm14 = this.m[14];
  5154. var tm15 = this.m[15];
  5155. var om0 = other.m[0];
  5156. var om1 = other.m[1];
  5157. var om2 = other.m[2];
  5158. var om3 = other.m[3];
  5159. var om4 = other.m[4];
  5160. var om5 = other.m[5];
  5161. var om6 = other.m[6];
  5162. var om7 = other.m[7];
  5163. var om8 = other.m[8];
  5164. var om9 = other.m[9];
  5165. var om10 = other.m[10];
  5166. var om11 = other.m[11];
  5167. var om12 = other.m[12];
  5168. var om13 = other.m[13];
  5169. var om14 = other.m[14];
  5170. var om15 = other.m[15];
  5171. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5172. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5173. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5174. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5175. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5176. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5177. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5178. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5179. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5180. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5181. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5182. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5183. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5184. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5185. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5186. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5187. return this;
  5188. };
  5189. /**
  5190. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5191. */
  5192. Matrix.prototype.equals = function (value) {
  5193. return value &&
  5194. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5195. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5196. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5197. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5198. };
  5199. /**
  5200. * Returns a new Matrix from the current Matrix.
  5201. */
  5202. Matrix.prototype.clone = function () {
  5203. 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]);
  5204. };
  5205. /**
  5206. * Returns the string "Matrix"
  5207. */
  5208. Matrix.prototype.getClassName = function () {
  5209. return "Matrix";
  5210. };
  5211. /**
  5212. * Returns the Matrix hash code.
  5213. */
  5214. Matrix.prototype.getHashCode = function () {
  5215. var hash = this.m[0] || 0;
  5216. for (var i = 1; i < 16; i++) {
  5217. hash = (hash * 397) ^ (this.m[i] || 0);
  5218. }
  5219. return hash;
  5220. };
  5221. /**
  5222. * Decomposes the current Matrix into :
  5223. * - a scale vector3 passed as a reference to update,
  5224. * - a rotation quaternion passed as a reference to update,
  5225. * - a translation vector3 passed as a reference to update.
  5226. * Returns the true if operation was successful.
  5227. */
  5228. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5229. translation.x = this.m[12];
  5230. translation.y = this.m[13];
  5231. translation.z = this.m[14];
  5232. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5233. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5234. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5235. if (this.determinant() <= 0) {
  5236. scale.y *= -1;
  5237. }
  5238. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5239. rotation.x = 0;
  5240. rotation.y = 0;
  5241. rotation.z = 0;
  5242. rotation.w = 1;
  5243. return false;
  5244. }
  5245. 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]);
  5246. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5247. return true;
  5248. };
  5249. /**
  5250. * Returns the index-th row of the current matrix as a new Vector4.
  5251. */
  5252. Matrix.prototype.getRow = function (index) {
  5253. if (index < 0 || index > 3) {
  5254. return null;
  5255. }
  5256. var i = index * 4;
  5257. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5258. };
  5259. /**
  5260. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5261. * Returns the updated Matrix.
  5262. */
  5263. Matrix.prototype.setRow = function (index, row) {
  5264. if (index < 0 || index > 3) {
  5265. return this;
  5266. }
  5267. var i = index * 4;
  5268. this.m[i + 0] = row.x;
  5269. this.m[i + 1] = row.y;
  5270. this.m[i + 2] = row.z;
  5271. this.m[i + 3] = row.w;
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Compute the transpose of the matrix.
  5277. * Returns a new Matrix.
  5278. */
  5279. Matrix.prototype.transpose = function () {
  5280. return Matrix.Transpose(this);
  5281. };
  5282. /**
  5283. * Compute the transpose of the matrix.
  5284. * Returns the current matrix.
  5285. */
  5286. Matrix.prototype.transposeToRef = function (result) {
  5287. Matrix.TransposeToRef(this, result);
  5288. return this;
  5289. };
  5290. /**
  5291. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5292. * Returns the updated Matrix.
  5293. */
  5294. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5295. if (index < 0 || index > 3) {
  5296. return this;
  5297. }
  5298. var i = index * 4;
  5299. this.m[i + 0] = x;
  5300. this.m[i + 1] = y;
  5301. this.m[i + 2] = z;
  5302. this.m[i + 3] = w;
  5303. this._markAsUpdated();
  5304. return this;
  5305. };
  5306. /**
  5307. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5308. * @param scale defines the scale factor
  5309. * @returns a new Matrix
  5310. */
  5311. Matrix.prototype.scale = function (scale) {
  5312. var result = new Matrix();
  5313. this.scaleToRef(scale, result);
  5314. return result;
  5315. };
  5316. /**
  5317. * Scale the current Matrix values by a factor to a given result Matrix
  5318. * @param scale defines the scale factor
  5319. * @param result defines the Matrix to store the result
  5320. * @returns the current Matrix
  5321. */
  5322. Matrix.prototype.scaleToRef = function (scale, result) {
  5323. for (var index = 0; index < 16; index++) {
  5324. result.m[index] = this.m[index] * scale;
  5325. }
  5326. result._markAsUpdated();
  5327. return this;
  5328. };
  5329. /**
  5330. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5331. * @param scale defines the scale factor
  5332. * @param result defines the Matrix to store the result
  5333. * @returns the current Matrix
  5334. */
  5335. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5336. for (var index = 0; index < 16; index++) {
  5337. result.m[index] += this.m[index] * scale;
  5338. }
  5339. result._markAsUpdated();
  5340. return this;
  5341. };
  5342. /**
  5343. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5344. * @param ref matrix to store the result
  5345. */
  5346. Matrix.prototype.toNormalMatrix = function (ref) {
  5347. this.invertToRef(ref);
  5348. ref.transpose();
  5349. var m = ref.m;
  5350. 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);
  5351. };
  5352. /**
  5353. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5354. */
  5355. Matrix.prototype.getRotationMatrix = function () {
  5356. var result = Matrix.Identity();
  5357. this.getRotationMatrixToRef(result);
  5358. return result;
  5359. };
  5360. /**
  5361. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5362. * Returns the current Matrix.
  5363. */
  5364. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5365. var m = this.m;
  5366. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5367. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5368. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5369. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5370. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5371. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5372. 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);
  5373. return this;
  5374. };
  5375. // Statics
  5376. /**
  5377. * Returns a new Matrix set from the starting index of the passed array.
  5378. */
  5379. Matrix.FromArray = function (array, offset) {
  5380. var result = new Matrix();
  5381. if (!offset) {
  5382. offset = 0;
  5383. }
  5384. Matrix.FromArrayToRef(array, offset, result);
  5385. return result;
  5386. };
  5387. /**
  5388. * Sets the passed "result" matrix from the starting index of the passed array.
  5389. */
  5390. Matrix.FromArrayToRef = function (array, offset, result) {
  5391. for (var index = 0; index < 16; index++) {
  5392. result.m[index] = array[index + offset];
  5393. }
  5394. result._markAsUpdated();
  5395. };
  5396. /**
  5397. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5398. */
  5399. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5400. for (var index = 0; index < 16; index++) {
  5401. result.m[index] = array[index + offset] * scale;
  5402. }
  5403. result._markAsUpdated();
  5404. };
  5405. /**
  5406. * Sets the passed matrix "result" with the 16 passed floats.
  5407. */
  5408. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5409. result.m[0] = initialM11;
  5410. result.m[1] = initialM12;
  5411. result.m[2] = initialM13;
  5412. result.m[3] = initialM14;
  5413. result.m[4] = initialM21;
  5414. result.m[5] = initialM22;
  5415. result.m[6] = initialM23;
  5416. result.m[7] = initialM24;
  5417. result.m[8] = initialM31;
  5418. result.m[9] = initialM32;
  5419. result.m[10] = initialM33;
  5420. result.m[11] = initialM34;
  5421. result.m[12] = initialM41;
  5422. result.m[13] = initialM42;
  5423. result.m[14] = initialM43;
  5424. result.m[15] = initialM44;
  5425. result._markAsUpdated();
  5426. };
  5427. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5428. /**
  5429. * Static identity matrix to be used as readonly matrix
  5430. * Must not be updated.
  5431. */
  5432. get: function () {
  5433. return Matrix._identityReadOnly;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. /**
  5439. * Returns a new Matrix set from the 16 passed floats.
  5440. */
  5441. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5442. var result = new Matrix();
  5443. result.m[0] = initialM11;
  5444. result.m[1] = initialM12;
  5445. result.m[2] = initialM13;
  5446. result.m[3] = initialM14;
  5447. result.m[4] = initialM21;
  5448. result.m[5] = initialM22;
  5449. result.m[6] = initialM23;
  5450. result.m[7] = initialM24;
  5451. result.m[8] = initialM31;
  5452. result.m[9] = initialM32;
  5453. result.m[10] = initialM33;
  5454. result.m[11] = initialM34;
  5455. result.m[12] = initialM41;
  5456. result.m[13] = initialM42;
  5457. result.m[14] = initialM43;
  5458. result.m[15] = initialM44;
  5459. return result;
  5460. };
  5461. /**
  5462. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5463. */
  5464. Matrix.Compose = function (scale, rotation, translation) {
  5465. var result = Matrix.Identity();
  5466. Matrix.ComposeToRef(scale, rotation, translation, result);
  5467. return result;
  5468. };
  5469. /**
  5470. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5471. */
  5472. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5473. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5474. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5475. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5476. result.setTranslation(translation);
  5477. };
  5478. /**
  5479. * Returns a new indentity Matrix.
  5480. */
  5481. Matrix.Identity = function () {
  5482. 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);
  5483. };
  5484. /**
  5485. * Sets the passed "result" as an identity matrix.
  5486. */
  5487. Matrix.IdentityToRef = function (result) {
  5488. 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);
  5489. };
  5490. /**
  5491. * Returns a new zero Matrix.
  5492. */
  5493. Matrix.Zero = function () {
  5494. 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);
  5495. };
  5496. /**
  5497. * Returns a new rotation matrix for "angle" radians around the X axis.
  5498. */
  5499. Matrix.RotationX = function (angle) {
  5500. var result = new Matrix();
  5501. Matrix.RotationXToRef(angle, result);
  5502. return result;
  5503. };
  5504. /**
  5505. * Returns a new Matrix as the passed inverted one.
  5506. */
  5507. Matrix.Invert = function (source) {
  5508. var result = new Matrix();
  5509. source.invertToRef(result);
  5510. return result;
  5511. };
  5512. /**
  5513. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5514. */
  5515. Matrix.RotationXToRef = function (angle, result) {
  5516. var s = Math.sin(angle);
  5517. var c = Math.cos(angle);
  5518. result.m[0] = 1.0;
  5519. result.m[15] = 1.0;
  5520. result.m[5] = c;
  5521. result.m[10] = c;
  5522. result.m[9] = -s;
  5523. result.m[6] = s;
  5524. result.m[1] = 0.0;
  5525. result.m[2] = 0.0;
  5526. result.m[3] = 0.0;
  5527. result.m[4] = 0.0;
  5528. result.m[7] = 0.0;
  5529. result.m[8] = 0.0;
  5530. result.m[11] = 0.0;
  5531. result.m[12] = 0.0;
  5532. result.m[13] = 0.0;
  5533. result.m[14] = 0.0;
  5534. result._markAsUpdated();
  5535. };
  5536. /**
  5537. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5538. */
  5539. Matrix.RotationY = function (angle) {
  5540. var result = new Matrix();
  5541. Matrix.RotationYToRef(angle, result);
  5542. return result;
  5543. };
  5544. /**
  5545. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5546. */
  5547. Matrix.RotationYToRef = function (angle, result) {
  5548. var s = Math.sin(angle);
  5549. var c = Math.cos(angle);
  5550. result.m[5] = 1.0;
  5551. result.m[15] = 1.0;
  5552. result.m[0] = c;
  5553. result.m[2] = -s;
  5554. result.m[8] = s;
  5555. result.m[10] = c;
  5556. result.m[1] = 0.0;
  5557. result.m[3] = 0.0;
  5558. result.m[4] = 0.0;
  5559. result.m[6] = 0.0;
  5560. result.m[7] = 0.0;
  5561. result.m[9] = 0.0;
  5562. result.m[11] = 0.0;
  5563. result.m[12] = 0.0;
  5564. result.m[13] = 0.0;
  5565. result.m[14] = 0.0;
  5566. result._markAsUpdated();
  5567. };
  5568. /**
  5569. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5570. */
  5571. Matrix.RotationZ = function (angle) {
  5572. var result = new Matrix();
  5573. Matrix.RotationZToRef(angle, result);
  5574. return result;
  5575. };
  5576. /**
  5577. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5578. */
  5579. Matrix.RotationZToRef = function (angle, result) {
  5580. var s = Math.sin(angle);
  5581. var c = Math.cos(angle);
  5582. result.m[10] = 1.0;
  5583. result.m[15] = 1.0;
  5584. result.m[0] = c;
  5585. result.m[1] = s;
  5586. result.m[4] = -s;
  5587. result.m[5] = c;
  5588. result.m[2] = 0.0;
  5589. result.m[3] = 0.0;
  5590. result.m[6] = 0.0;
  5591. result.m[7] = 0.0;
  5592. result.m[8] = 0.0;
  5593. result.m[9] = 0.0;
  5594. result.m[11] = 0.0;
  5595. result.m[12] = 0.0;
  5596. result.m[13] = 0.0;
  5597. result.m[14] = 0.0;
  5598. result._markAsUpdated();
  5599. };
  5600. /**
  5601. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5602. */
  5603. Matrix.RotationAxis = function (axis, angle) {
  5604. var result = Matrix.Zero();
  5605. Matrix.RotationAxisToRef(axis, angle, result);
  5606. return result;
  5607. };
  5608. /**
  5609. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5610. */
  5611. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5612. var s = Math.sin(-angle);
  5613. var c = Math.cos(-angle);
  5614. var c1 = 1 - c;
  5615. axis.normalize();
  5616. result.m[0] = (axis.x * axis.x) * c1 + c;
  5617. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5618. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5619. result.m[3] = 0.0;
  5620. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5621. result.m[5] = (axis.y * axis.y) * c1 + c;
  5622. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5623. result.m[7] = 0.0;
  5624. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5625. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5626. result.m[10] = (axis.z * axis.z) * c1 + c;
  5627. result.m[11] = 0.0;
  5628. result.m[15] = 1.0;
  5629. result._markAsUpdated();
  5630. };
  5631. /**
  5632. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5633. */
  5634. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5635. var result = new Matrix();
  5636. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5637. return result;
  5638. };
  5639. /**
  5640. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5641. */
  5642. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5643. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5644. this._tempQuaternion.toRotationMatrix(result);
  5645. };
  5646. /**
  5647. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5648. */
  5649. Matrix.Scaling = function (x, y, z) {
  5650. var result = Matrix.Zero();
  5651. Matrix.ScalingToRef(x, y, z, result);
  5652. return result;
  5653. };
  5654. /**
  5655. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5656. */
  5657. Matrix.ScalingToRef = function (x, y, z, result) {
  5658. result.m[0] = x;
  5659. result.m[1] = 0.0;
  5660. result.m[2] = 0.0;
  5661. result.m[3] = 0.0;
  5662. result.m[4] = 0.0;
  5663. result.m[5] = y;
  5664. result.m[6] = 0.0;
  5665. result.m[7] = 0.0;
  5666. result.m[8] = 0.0;
  5667. result.m[9] = 0.0;
  5668. result.m[10] = z;
  5669. result.m[11] = 0.0;
  5670. result.m[12] = 0.0;
  5671. result.m[13] = 0.0;
  5672. result.m[14] = 0.0;
  5673. result.m[15] = 1.0;
  5674. result._markAsUpdated();
  5675. };
  5676. /**
  5677. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5678. */
  5679. Matrix.Translation = function (x, y, z) {
  5680. var result = Matrix.Identity();
  5681. Matrix.TranslationToRef(x, y, z, result);
  5682. return result;
  5683. };
  5684. /**
  5685. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5686. */
  5687. Matrix.TranslationToRef = function (x, y, z, result) {
  5688. 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);
  5689. };
  5690. /**
  5691. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5692. * @param startValue defines the start value
  5693. * @param endValue defines the end value
  5694. * @param gradient defines the gradient factor
  5695. * @returns the new matrix
  5696. */
  5697. Matrix.Lerp = function (startValue, endValue, gradient) {
  5698. var result = Matrix.Zero();
  5699. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5700. return result;
  5701. };
  5702. /**
  5703. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5704. * @param startValue defines the start value
  5705. * @param endValue defines the end value
  5706. * @param gradient defines the gradient factor
  5707. * @param result defines the Matrix object where to store data
  5708. */
  5709. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5710. for (var index = 0; index < 16; index++) {
  5711. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5712. }
  5713. result._markAsUpdated();
  5714. };
  5715. /**
  5716. * Returns a new Matrix whose values are computed by :
  5717. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5718. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5719. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5720. */
  5721. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5722. var startScale = new Vector3(0, 0, 0);
  5723. var startRotation = new Quaternion();
  5724. var startTranslation = new Vector3(0, 0, 0);
  5725. startValue.decompose(startScale, startRotation, startTranslation);
  5726. var endScale = new Vector3(0, 0, 0);
  5727. var endRotation = new Quaternion();
  5728. var endTranslation = new Vector3(0, 0, 0);
  5729. endValue.decompose(endScale, endRotation, endTranslation);
  5730. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5731. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5732. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5733. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5734. };
  5735. /**
  5736. * 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".
  5737. * This methods works for a Left-Handed system.
  5738. */
  5739. Matrix.LookAtLH = function (eye, target, up) {
  5740. var result = Matrix.Zero();
  5741. Matrix.LookAtLHToRef(eye, target, up, result);
  5742. return result;
  5743. };
  5744. /**
  5745. * 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".
  5746. * This methods works for a Left-Handed system.
  5747. */
  5748. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5749. // Z axis
  5750. target.subtractToRef(eye, this._zAxis);
  5751. this._zAxis.normalize();
  5752. // X axis
  5753. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5754. if (this._xAxis.lengthSquared() === 0) {
  5755. this._xAxis.x = 1.0;
  5756. }
  5757. else {
  5758. this._xAxis.normalize();
  5759. }
  5760. // Y axis
  5761. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5762. this._yAxis.normalize();
  5763. // Eye angles
  5764. var ex = -Vector3.Dot(this._xAxis, eye);
  5765. var ey = -Vector3.Dot(this._yAxis, eye);
  5766. var ez = -Vector3.Dot(this._zAxis, eye);
  5767. 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);
  5768. };
  5769. /**
  5770. * 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".
  5771. * This methods works for a Right-Handed system.
  5772. */
  5773. Matrix.LookAtRH = function (eye, target, up) {
  5774. var result = Matrix.Zero();
  5775. Matrix.LookAtRHToRef(eye, target, up, result);
  5776. return result;
  5777. };
  5778. /**
  5779. * 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".
  5780. * This methods works for a Left-Handed system.
  5781. */
  5782. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5783. // Z axis
  5784. eye.subtractToRef(target, this._zAxis);
  5785. this._zAxis.normalize();
  5786. // X axis
  5787. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5788. if (this._xAxis.lengthSquared() === 0) {
  5789. this._xAxis.x = 1.0;
  5790. }
  5791. else {
  5792. this._xAxis.normalize();
  5793. }
  5794. // Y axis
  5795. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5796. this._yAxis.normalize();
  5797. // Eye angles
  5798. var ex = -Vector3.Dot(this._xAxis, eye);
  5799. var ey = -Vector3.Dot(this._yAxis, eye);
  5800. var ez = -Vector3.Dot(this._zAxis, eye);
  5801. 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);
  5802. };
  5803. /**
  5804. * 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.
  5805. */
  5806. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5807. var matrix = Matrix.Zero();
  5808. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5809. return matrix;
  5810. };
  5811. /**
  5812. * 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.
  5813. */
  5814. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5815. var n = znear;
  5816. var f = zfar;
  5817. var a = 2.0 / width;
  5818. var b = 2.0 / height;
  5819. var c = 2.0 / (f - n);
  5820. var d = -(f + n) / (f - n);
  5821. 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);
  5822. };
  5823. /**
  5824. * 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.
  5825. */
  5826. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5827. var matrix = Matrix.Zero();
  5828. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5829. return matrix;
  5830. };
  5831. /**
  5832. * 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.
  5833. */
  5834. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5835. var n = znear;
  5836. var f = zfar;
  5837. var a = 2.0 / (right - left);
  5838. var b = 2.0 / (top - bottom);
  5839. var c = 2.0 / (f - n);
  5840. var d = -(f + n) / (f - n);
  5841. var i0 = (left + right) / (left - right);
  5842. var i1 = (top + bottom) / (bottom - top);
  5843. 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);
  5844. };
  5845. /**
  5846. * 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.
  5847. */
  5848. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5849. var matrix = Matrix.Zero();
  5850. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5851. return matrix;
  5852. };
  5853. /**
  5854. * 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.
  5855. */
  5856. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5857. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5858. result.m[10] *= -1.0;
  5859. };
  5860. /**
  5861. * 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.
  5862. */
  5863. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5864. var matrix = Matrix.Zero();
  5865. var n = znear;
  5866. var f = zfar;
  5867. var a = 2.0 * n / width;
  5868. var b = 2.0 * n / height;
  5869. var c = (f + n) / (f - n);
  5870. var d = -2.0 * f * n / (f - n);
  5871. 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);
  5872. return matrix;
  5873. };
  5874. /**
  5875. * 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.
  5876. */
  5877. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5878. var matrix = Matrix.Zero();
  5879. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5880. return matrix;
  5881. };
  5882. /**
  5883. * 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.
  5884. */
  5885. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5886. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5887. var n = znear;
  5888. var f = zfar;
  5889. var t = 1.0 / (Math.tan(fov * 0.5));
  5890. var a = isVerticalFovFixed ? (t / aspect) : t;
  5891. var b = isVerticalFovFixed ? t : (t * aspect);
  5892. var c = (f + n) / (f - n);
  5893. var d = -2.0 * f * n / (f - n);
  5894. 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);
  5895. };
  5896. /**
  5897. * 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.
  5898. */
  5899. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5900. var matrix = Matrix.Zero();
  5901. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5902. return matrix;
  5903. };
  5904. /**
  5905. * 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.
  5906. */
  5907. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5908. //alternatively this could be expressed as:
  5909. // m = PerspectiveFovLHToRef
  5910. // m[10] *= -1.0;
  5911. // m[11] *= -1.0;
  5912. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5913. var n = znear;
  5914. var f = zfar;
  5915. var t = 1.0 / (Math.tan(fov * 0.5));
  5916. var a = isVerticalFovFixed ? (t / aspect) : t;
  5917. var b = isVerticalFovFixed ? t : (t * aspect);
  5918. var c = -(f + n) / (f - n);
  5919. var d = -2 * f * n / (f - n);
  5920. 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);
  5921. };
  5922. /**
  5923. * 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.
  5924. */
  5925. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5926. if (rightHanded === void 0) { rightHanded = false; }
  5927. var rightHandedFactor = rightHanded ? -1 : 1;
  5928. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5929. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5930. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5931. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5932. var xScale = 2.0 / (leftTan + rightTan);
  5933. var yScale = 2.0 / (upTan + downTan);
  5934. result.m[0] = xScale;
  5935. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5936. result.m[5] = yScale;
  5937. result.m[6] = result.m[7] = 0.0;
  5938. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5939. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5940. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5941. result.m[10] = -zfar / (znear - zfar);
  5942. result.m[11] = 1.0 * rightHandedFactor;
  5943. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5944. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5945. // result.m[14] = (znear * zfar) / (znear - zfar);
  5946. result._markAsUpdated();
  5947. };
  5948. /**
  5949. * Returns the final transformation matrix : world * view * projection * viewport
  5950. */
  5951. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5952. var cw = viewport.width;
  5953. var ch = viewport.height;
  5954. var cx = viewport.x;
  5955. var cy = viewport.y;
  5956. 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);
  5957. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5958. };
  5959. /**
  5960. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5961. */
  5962. Matrix.GetAsMatrix2x2 = function (matrix) {
  5963. return new Float32Array([
  5964. matrix.m[0], matrix.m[1],
  5965. matrix.m[4], matrix.m[5]
  5966. ]);
  5967. };
  5968. /**
  5969. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5970. */
  5971. Matrix.GetAsMatrix3x3 = function (matrix) {
  5972. return new Float32Array([
  5973. matrix.m[0], matrix.m[1], matrix.m[2],
  5974. matrix.m[4], matrix.m[5], matrix.m[6],
  5975. matrix.m[8], matrix.m[9], matrix.m[10]
  5976. ]);
  5977. };
  5978. /**
  5979. * Compute the transpose of the passed Matrix.
  5980. * Returns a new Matrix.
  5981. */
  5982. Matrix.Transpose = function (matrix) {
  5983. var result = new Matrix();
  5984. Matrix.TransposeToRef(matrix, result);
  5985. return result;
  5986. };
  5987. /**
  5988. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5989. */
  5990. Matrix.TransposeToRef = function (matrix, result) {
  5991. result.m[0] = matrix.m[0];
  5992. result.m[1] = matrix.m[4];
  5993. result.m[2] = matrix.m[8];
  5994. result.m[3] = matrix.m[12];
  5995. result.m[4] = matrix.m[1];
  5996. result.m[5] = matrix.m[5];
  5997. result.m[6] = matrix.m[9];
  5998. result.m[7] = matrix.m[13];
  5999. result.m[8] = matrix.m[2];
  6000. result.m[9] = matrix.m[6];
  6001. result.m[10] = matrix.m[10];
  6002. result.m[11] = matrix.m[14];
  6003. result.m[12] = matrix.m[3];
  6004. result.m[13] = matrix.m[7];
  6005. result.m[14] = matrix.m[11];
  6006. result.m[15] = matrix.m[15];
  6007. };
  6008. /**
  6009. * Returns a new Matrix as the reflection matrix across the passed plane.
  6010. */
  6011. Matrix.Reflection = function (plane) {
  6012. var matrix = new Matrix();
  6013. Matrix.ReflectionToRef(plane, matrix);
  6014. return matrix;
  6015. };
  6016. /**
  6017. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  6018. */
  6019. Matrix.ReflectionToRef = function (plane, result) {
  6020. plane.normalize();
  6021. var x = plane.normal.x;
  6022. var y = plane.normal.y;
  6023. var z = plane.normal.z;
  6024. var temp = -2 * x;
  6025. var temp2 = -2 * y;
  6026. var temp3 = -2 * z;
  6027. result.m[0] = (temp * x) + 1;
  6028. result.m[1] = temp2 * x;
  6029. result.m[2] = temp3 * x;
  6030. result.m[3] = 0.0;
  6031. result.m[4] = temp * y;
  6032. result.m[5] = (temp2 * y) + 1;
  6033. result.m[6] = temp3 * y;
  6034. result.m[7] = 0.0;
  6035. result.m[8] = temp * z;
  6036. result.m[9] = temp2 * z;
  6037. result.m[10] = (temp3 * z) + 1;
  6038. result.m[11] = 0.0;
  6039. result.m[12] = temp * plane.d;
  6040. result.m[13] = temp2 * plane.d;
  6041. result.m[14] = temp3 * plane.d;
  6042. result.m[15] = 1.0;
  6043. result._markAsUpdated();
  6044. };
  6045. /**
  6046. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  6047. */
  6048. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6049. result.m[0] = xaxis.x;
  6050. result.m[1] = xaxis.y;
  6051. result.m[2] = xaxis.z;
  6052. result.m[3] = 0.0;
  6053. result.m[4] = yaxis.x;
  6054. result.m[5] = yaxis.y;
  6055. result.m[6] = yaxis.z;
  6056. result.m[7] = 0.0;
  6057. result.m[8] = zaxis.x;
  6058. result.m[9] = zaxis.y;
  6059. result.m[10] = zaxis.z;
  6060. result.m[11] = 0.0;
  6061. result.m[12] = 0.0;
  6062. result.m[13] = 0.0;
  6063. result.m[14] = 0.0;
  6064. result.m[15] = 1.0;
  6065. result._markAsUpdated();
  6066. };
  6067. /**
  6068. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  6069. */
  6070. Matrix.FromQuaternionToRef = function (quat, result) {
  6071. var xx = quat.x * quat.x;
  6072. var yy = quat.y * quat.y;
  6073. var zz = quat.z * quat.z;
  6074. var xy = quat.x * quat.y;
  6075. var zw = quat.z * quat.w;
  6076. var zx = quat.z * quat.x;
  6077. var yw = quat.y * quat.w;
  6078. var yz = quat.y * quat.z;
  6079. var xw = quat.x * quat.w;
  6080. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6081. result.m[1] = 2.0 * (xy + zw);
  6082. result.m[2] = 2.0 * (zx - yw);
  6083. result.m[3] = 0.0;
  6084. result.m[4] = 2.0 * (xy - zw);
  6085. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6086. result.m[6] = 2.0 * (yz + xw);
  6087. result.m[7] = 0.0;
  6088. result.m[8] = 2.0 * (zx + yw);
  6089. result.m[9] = 2.0 * (yz - xw);
  6090. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6091. result.m[11] = 0.0;
  6092. result.m[12] = 0.0;
  6093. result.m[13] = 0.0;
  6094. result.m[14] = 0.0;
  6095. result.m[15] = 1.0;
  6096. result._markAsUpdated();
  6097. };
  6098. Matrix._tempQuaternion = new Quaternion();
  6099. Matrix._xAxis = Vector3.Zero();
  6100. Matrix._yAxis = Vector3.Zero();
  6101. Matrix._zAxis = Vector3.Zero();
  6102. Matrix._updateFlagSeed = 0;
  6103. Matrix._identityReadOnly = Matrix.Identity();
  6104. return Matrix;
  6105. }());
  6106. BABYLON.Matrix = Matrix;
  6107. var Plane = /** @class */ (function () {
  6108. /**
  6109. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6110. */
  6111. function Plane(a, b, c, d) {
  6112. this.normal = new Vector3(a, b, c);
  6113. this.d = d;
  6114. }
  6115. /**
  6116. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6117. */
  6118. Plane.prototype.asArray = function () {
  6119. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6120. };
  6121. // Methods
  6122. /**
  6123. * Returns a new plane copied from the current Plane.
  6124. */
  6125. Plane.prototype.clone = function () {
  6126. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6127. };
  6128. /**
  6129. * Returns the string "Plane".
  6130. */
  6131. Plane.prototype.getClassName = function () {
  6132. return "Plane";
  6133. };
  6134. /**
  6135. * Returns the Plane hash code.
  6136. */
  6137. Plane.prototype.getHashCode = function () {
  6138. var hash = this.normal.getHashCode();
  6139. hash = (hash * 397) ^ (this.d || 0);
  6140. return hash;
  6141. };
  6142. /**
  6143. * Normalize the current Plane in place.
  6144. * Returns the updated Plane.
  6145. */
  6146. Plane.prototype.normalize = function () {
  6147. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6148. var magnitude = 0.0;
  6149. if (norm !== 0) {
  6150. magnitude = 1.0 / norm;
  6151. }
  6152. this.normal.x *= magnitude;
  6153. this.normal.y *= magnitude;
  6154. this.normal.z *= magnitude;
  6155. this.d *= magnitude;
  6156. return this;
  6157. };
  6158. /**
  6159. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6160. */
  6161. Plane.prototype.transform = function (transformation) {
  6162. var transposedMatrix = Matrix.Transpose(transformation);
  6163. var x = this.normal.x;
  6164. var y = this.normal.y;
  6165. var z = this.normal.z;
  6166. var d = this.d;
  6167. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6168. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6169. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6170. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6171. return new Plane(normalX, normalY, normalZ, finalD);
  6172. };
  6173. /**
  6174. * Returns the dot product (float) of the point coordinates and the plane normal.
  6175. */
  6176. Plane.prototype.dotCoordinate = function (point) {
  6177. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6178. };
  6179. /**
  6180. * Updates the current Plane from the plane defined by the three passed points.
  6181. * Returns the updated Plane.
  6182. */
  6183. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6184. var x1 = point2.x - point1.x;
  6185. var y1 = point2.y - point1.y;
  6186. var z1 = point2.z - point1.z;
  6187. var x2 = point3.x - point1.x;
  6188. var y2 = point3.y - point1.y;
  6189. var z2 = point3.z - point1.z;
  6190. var yz = (y1 * z2) - (z1 * y2);
  6191. var xz = (z1 * x2) - (x1 * z2);
  6192. var xy = (x1 * y2) - (y1 * x2);
  6193. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6194. var invPyth;
  6195. if (pyth !== 0) {
  6196. invPyth = 1.0 / pyth;
  6197. }
  6198. else {
  6199. invPyth = 0.0;
  6200. }
  6201. this.normal.x = yz * invPyth;
  6202. this.normal.y = xz * invPyth;
  6203. this.normal.z = xy * invPyth;
  6204. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6205. return this;
  6206. };
  6207. /**
  6208. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6209. */
  6210. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6211. var dot = Vector3.Dot(this.normal, direction);
  6212. return (dot <= epsilon);
  6213. };
  6214. /**
  6215. * Returns the signed distance (float) from the passed point to the Plane.
  6216. */
  6217. Plane.prototype.signedDistanceTo = function (point) {
  6218. return Vector3.Dot(point, this.normal) + this.d;
  6219. };
  6220. // Statics
  6221. /**
  6222. * Returns a new Plane from the passed array.
  6223. */
  6224. Plane.FromArray = function (array) {
  6225. return new Plane(array[0], array[1], array[2], array[3]);
  6226. };
  6227. /**
  6228. * Returns a new Plane defined by the three passed points.
  6229. */
  6230. Plane.FromPoints = function (point1, point2, point3) {
  6231. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6232. result.copyFromPoints(point1, point2, point3);
  6233. return result;
  6234. };
  6235. /**
  6236. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6237. * Note : the vector "normal" is updated because normalized.
  6238. */
  6239. Plane.FromPositionAndNormal = function (origin, normal) {
  6240. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6241. normal.normalize();
  6242. result.normal = normal;
  6243. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6244. return result;
  6245. };
  6246. /**
  6247. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6248. */
  6249. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6250. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6251. return Vector3.Dot(point, normal) + d;
  6252. };
  6253. return Plane;
  6254. }());
  6255. BABYLON.Plane = Plane;
  6256. var Viewport = /** @class */ (function () {
  6257. /**
  6258. * Creates a Viewport object located at (x, y) and sized (width, height).
  6259. */
  6260. function Viewport(x, y, width, height) {
  6261. this.x = x;
  6262. this.y = y;
  6263. this.width = width;
  6264. this.height = height;
  6265. }
  6266. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6267. if (renderWidthOrEngine.getRenderWidth) {
  6268. var engine = renderWidthOrEngine;
  6269. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6270. }
  6271. var renderWidth = renderWidthOrEngine;
  6272. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6273. };
  6274. /**
  6275. * Returns a new Viewport copied from the current one.
  6276. */
  6277. Viewport.prototype.clone = function () {
  6278. return new Viewport(this.x, this.y, this.width, this.height);
  6279. };
  6280. return Viewport;
  6281. }());
  6282. BABYLON.Viewport = Viewport;
  6283. var Frustum = /** @class */ (function () {
  6284. function Frustum() {
  6285. }
  6286. /**
  6287. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6288. */
  6289. Frustum.GetPlanes = function (transform) {
  6290. var frustumPlanes = [];
  6291. for (var index = 0; index < 6; index++) {
  6292. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6293. }
  6294. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6295. return frustumPlanes;
  6296. };
  6297. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6298. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6299. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6300. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6301. frustumPlane.d = transform.m[15] + transform.m[14];
  6302. frustumPlane.normalize();
  6303. };
  6304. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6305. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6306. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6307. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6308. frustumPlane.d = transform.m[15] - transform.m[14];
  6309. frustumPlane.normalize();
  6310. };
  6311. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6312. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6313. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6314. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6315. frustumPlane.d = transform.m[15] + transform.m[12];
  6316. frustumPlane.normalize();
  6317. };
  6318. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6319. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6320. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6321. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6322. frustumPlane.d = transform.m[15] - transform.m[12];
  6323. frustumPlane.normalize();
  6324. };
  6325. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6326. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6327. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6328. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6329. frustumPlane.d = transform.m[15] - transform.m[13];
  6330. frustumPlane.normalize();
  6331. };
  6332. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6333. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6334. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6335. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6336. frustumPlane.d = transform.m[15] + transform.m[13];
  6337. frustumPlane.normalize();
  6338. };
  6339. /**
  6340. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6341. */
  6342. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6343. // Near
  6344. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6345. // Far
  6346. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6347. // Left
  6348. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6349. // Right
  6350. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6351. // Top
  6352. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6353. // Bottom
  6354. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6355. };
  6356. return Frustum;
  6357. }());
  6358. BABYLON.Frustum = Frustum;
  6359. var Space;
  6360. (function (Space) {
  6361. Space[Space["LOCAL"] = 0] = "LOCAL";
  6362. Space[Space["WORLD"] = 1] = "WORLD";
  6363. Space[Space["BONE"] = 2] = "BONE";
  6364. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6365. var Axis = /** @class */ (function () {
  6366. function Axis() {
  6367. }
  6368. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6369. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6370. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6371. return Axis;
  6372. }());
  6373. BABYLON.Axis = Axis;
  6374. ;
  6375. var BezierCurve = /** @class */ (function () {
  6376. function BezierCurve() {
  6377. }
  6378. /**
  6379. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6380. */
  6381. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6382. // Extract X (which is equal to time here)
  6383. var f0 = 1 - 3 * x2 + 3 * x1;
  6384. var f1 = 3 * x2 - 6 * x1;
  6385. var f2 = 3 * x1;
  6386. var refinedT = t;
  6387. for (var i = 0; i < 5; i++) {
  6388. var refinedT2 = refinedT * refinedT;
  6389. var refinedT3 = refinedT2 * refinedT;
  6390. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6391. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6392. refinedT -= (x - t) * slope;
  6393. refinedT = Math.min(1, Math.max(0, refinedT));
  6394. }
  6395. // Resolve cubic bezier for the given x
  6396. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6397. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6398. Math.pow(refinedT, 3);
  6399. };
  6400. return BezierCurve;
  6401. }());
  6402. BABYLON.BezierCurve = BezierCurve;
  6403. var Orientation;
  6404. (function (Orientation) {
  6405. Orientation[Orientation["CW"] = 0] = "CW";
  6406. Orientation[Orientation["CCW"] = 1] = "CCW";
  6407. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6408. var Angle = /** @class */ (function () {
  6409. /**
  6410. * Creates an Angle object of "radians" radians (float).
  6411. */
  6412. function Angle(radians) {
  6413. var _this = this;
  6414. /**
  6415. * Returns the Angle value in degrees (float).
  6416. */
  6417. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6418. /**
  6419. * Returns the Angle value in radians (float).
  6420. */
  6421. this.radians = function () { return _this._radians; };
  6422. this._radians = radians;
  6423. if (this._radians < 0.0)
  6424. this._radians += (2.0 * Math.PI);
  6425. }
  6426. /**
  6427. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6428. */
  6429. Angle.BetweenTwoPoints = function (a, b) {
  6430. var delta = b.subtract(a);
  6431. var theta = Math.atan2(delta.y, delta.x);
  6432. return new Angle(theta);
  6433. };
  6434. /**
  6435. * Returns a new Angle object from the passed float in radians.
  6436. */
  6437. Angle.FromRadians = function (radians) {
  6438. return new Angle(radians);
  6439. };
  6440. /**
  6441. * Returns a new Angle object from the passed float in degrees.
  6442. */
  6443. Angle.FromDegrees = function (degrees) {
  6444. return new Angle(degrees * Math.PI / 180.0);
  6445. };
  6446. return Angle;
  6447. }());
  6448. BABYLON.Angle = Angle;
  6449. var Arc2 = /** @class */ (function () {
  6450. /**
  6451. * Creates an Arc object from the three passed points : start, middle and end.
  6452. */
  6453. function Arc2(startPoint, midPoint, endPoint) {
  6454. this.startPoint = startPoint;
  6455. this.midPoint = midPoint;
  6456. this.endPoint = endPoint;
  6457. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6458. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6459. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6460. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6461. 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);
  6462. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6463. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6464. var a1 = this.startAngle.degrees();
  6465. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6466. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6467. // angles correction
  6468. if (a2 - a1 > +180.0)
  6469. a2 -= 360.0;
  6470. if (a2 - a1 < -180.0)
  6471. a2 += 360.0;
  6472. if (a3 - a2 > +180.0)
  6473. a3 -= 360.0;
  6474. if (a3 - a2 < -180.0)
  6475. a3 += 360.0;
  6476. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6477. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6478. }
  6479. return Arc2;
  6480. }());
  6481. BABYLON.Arc2 = Arc2;
  6482. var Path2 = /** @class */ (function () {
  6483. /**
  6484. * Creates a Path2 object from the starting 2D coordinates x and y.
  6485. */
  6486. function Path2(x, y) {
  6487. this._points = new Array();
  6488. this._length = 0.0;
  6489. this.closed = false;
  6490. this._points.push(new Vector2(x, y));
  6491. }
  6492. /**
  6493. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6494. * Returns the updated Path2.
  6495. */
  6496. Path2.prototype.addLineTo = function (x, y) {
  6497. if (this.closed) {
  6498. return this;
  6499. }
  6500. var newPoint = new Vector2(x, y);
  6501. var previousPoint = this._points[this._points.length - 1];
  6502. this._points.push(newPoint);
  6503. this._length += newPoint.subtract(previousPoint).length();
  6504. return this;
  6505. };
  6506. /**
  6507. * 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.
  6508. * Returns the updated Path2.
  6509. */
  6510. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6511. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6512. if (this.closed) {
  6513. return this;
  6514. }
  6515. var startPoint = this._points[this._points.length - 1];
  6516. var midPoint = new Vector2(midX, midY);
  6517. var endPoint = new Vector2(endX, endY);
  6518. var arc = new Arc2(startPoint, midPoint, endPoint);
  6519. var increment = arc.angle.radians() / numberOfSegments;
  6520. if (arc.orientation === Orientation.CW)
  6521. increment *= -1;
  6522. var currentAngle = arc.startAngle.radians() + increment;
  6523. for (var i = 0; i < numberOfSegments; i++) {
  6524. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6525. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6526. this.addLineTo(x, y);
  6527. currentAngle += increment;
  6528. }
  6529. return this;
  6530. };
  6531. /**
  6532. * Closes the Path2.
  6533. * Returns the Path2.
  6534. */
  6535. Path2.prototype.close = function () {
  6536. this.closed = true;
  6537. return this;
  6538. };
  6539. /**
  6540. * Returns the Path2 total length (float).
  6541. */
  6542. Path2.prototype.length = function () {
  6543. var result = this._length;
  6544. if (!this.closed) {
  6545. var lastPoint = this._points[this._points.length - 1];
  6546. var firstPoint = this._points[0];
  6547. result += (firstPoint.subtract(lastPoint).length());
  6548. }
  6549. return result;
  6550. };
  6551. /**
  6552. * Returns the Path2 internal array of points.
  6553. */
  6554. Path2.prototype.getPoints = function () {
  6555. return this._points;
  6556. };
  6557. /**
  6558. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6559. */
  6560. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6561. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6562. return Vector2.Zero();
  6563. }
  6564. var lengthPosition = normalizedLengthPosition * this.length();
  6565. var previousOffset = 0;
  6566. for (var i = 0; i < this._points.length; i++) {
  6567. var j = (i + 1) % this._points.length;
  6568. var a = this._points[i];
  6569. var b = this._points[j];
  6570. var bToA = b.subtract(a);
  6571. var nextOffset = (bToA.length() + previousOffset);
  6572. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6573. var dir = bToA.normalize();
  6574. var localOffset = lengthPosition - previousOffset;
  6575. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6576. }
  6577. previousOffset = nextOffset;
  6578. }
  6579. return Vector2.Zero();
  6580. };
  6581. /**
  6582. * Returns a new Path2 starting at the coordinates (x, y).
  6583. */
  6584. Path2.StartingAt = function (x, y) {
  6585. return new Path2(x, y);
  6586. };
  6587. return Path2;
  6588. }());
  6589. BABYLON.Path2 = Path2;
  6590. var Path3D = /** @class */ (function () {
  6591. /**
  6592. * new Path3D(path, normal, raw)
  6593. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6594. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6595. * path : an array of Vector3, the curve axis of the Path3D
  6596. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6597. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6598. */
  6599. function Path3D(path, firstNormal, raw) {
  6600. if (firstNormal === void 0) { firstNormal = null; }
  6601. this.path = path;
  6602. this._curve = new Array();
  6603. this._distances = new Array();
  6604. this._tangents = new Array();
  6605. this._normals = new Array();
  6606. this._binormals = new Array();
  6607. for (var p = 0; p < path.length; p++) {
  6608. this._curve[p] = path[p].clone(); // hard copy
  6609. }
  6610. this._raw = raw || false;
  6611. this._compute(firstNormal);
  6612. }
  6613. /**
  6614. * Returns the Path3D array of successive Vector3 designing its curve.
  6615. */
  6616. Path3D.prototype.getCurve = function () {
  6617. return this._curve;
  6618. };
  6619. /**
  6620. * Returns an array populated with tangent vectors on each Path3D curve point.
  6621. */
  6622. Path3D.prototype.getTangents = function () {
  6623. return this._tangents;
  6624. };
  6625. /**
  6626. * Returns an array populated with normal vectors on each Path3D curve point.
  6627. */
  6628. Path3D.prototype.getNormals = function () {
  6629. return this._normals;
  6630. };
  6631. /**
  6632. * Returns an array populated with binormal vectors on each Path3D curve point.
  6633. */
  6634. Path3D.prototype.getBinormals = function () {
  6635. return this._binormals;
  6636. };
  6637. /**
  6638. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6639. */
  6640. Path3D.prototype.getDistances = function () {
  6641. return this._distances;
  6642. };
  6643. /**
  6644. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6645. * Returns the same object updated.
  6646. */
  6647. Path3D.prototype.update = function (path, firstNormal) {
  6648. if (firstNormal === void 0) { firstNormal = null; }
  6649. for (var p = 0; p < path.length; p++) {
  6650. this._curve[p].x = path[p].x;
  6651. this._curve[p].y = path[p].y;
  6652. this._curve[p].z = path[p].z;
  6653. }
  6654. this._compute(firstNormal);
  6655. return this;
  6656. };
  6657. // private function compute() : computes tangents, normals and binormals
  6658. Path3D.prototype._compute = function (firstNormal) {
  6659. var l = this._curve.length;
  6660. // first and last tangents
  6661. this._tangents[0] = this._getFirstNonNullVector(0);
  6662. if (!this._raw) {
  6663. this._tangents[0].normalize();
  6664. }
  6665. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6666. if (!this._raw) {
  6667. this._tangents[l - 1].normalize();
  6668. }
  6669. // normals and binormals at first point : arbitrary vector with _normalVector()
  6670. var tg0 = this._tangents[0];
  6671. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6672. this._normals[0] = pp0;
  6673. if (!this._raw) {
  6674. this._normals[0].normalize();
  6675. }
  6676. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6677. if (!this._raw) {
  6678. this._binormals[0].normalize();
  6679. }
  6680. this._distances[0] = 0.0;
  6681. // normals and binormals : next points
  6682. var prev; // previous vector (segment)
  6683. var cur; // current vector (segment)
  6684. var curTang; // current tangent
  6685. // previous normal
  6686. var prevBinor; // previous binormal
  6687. for (var i = 1; i < l; i++) {
  6688. // tangents
  6689. prev = this._getLastNonNullVector(i);
  6690. if (i < l - 1) {
  6691. cur = this._getFirstNonNullVector(i);
  6692. this._tangents[i] = prev.add(cur);
  6693. this._tangents[i].normalize();
  6694. }
  6695. this._distances[i] = this._distances[i - 1] + prev.length();
  6696. // normals and binormals
  6697. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6698. curTang = this._tangents[i];
  6699. prevBinor = this._binormals[i - 1];
  6700. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6701. if (!this._raw) {
  6702. this._normals[i].normalize();
  6703. }
  6704. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6705. if (!this._raw) {
  6706. this._binormals[i].normalize();
  6707. }
  6708. }
  6709. };
  6710. // private function getFirstNonNullVector(index)
  6711. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6712. Path3D.prototype._getFirstNonNullVector = function (index) {
  6713. var i = 1;
  6714. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6715. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6716. i++;
  6717. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6718. }
  6719. return nNVector;
  6720. };
  6721. // private function getLastNonNullVector(index)
  6722. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6723. Path3D.prototype._getLastNonNullVector = function (index) {
  6724. var i = 1;
  6725. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6726. while (nLVector.length() === 0 && index > i + 1) {
  6727. i++;
  6728. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6729. }
  6730. return nLVector;
  6731. };
  6732. // private function normalVector(v0, vt, va) :
  6733. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6734. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6735. Path3D.prototype._normalVector = function (v0, vt, va) {
  6736. var normal0;
  6737. var tgl = vt.length();
  6738. if (tgl === 0.0) {
  6739. tgl = 1.0;
  6740. }
  6741. if (va === undefined || va === null) {
  6742. var point;
  6743. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6744. point = new Vector3(0.0, -1.0, 0.0);
  6745. }
  6746. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6747. point = new Vector3(1.0, 0.0, 0.0);
  6748. }
  6749. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6750. point = new Vector3(0.0, 0.0, 1.0);
  6751. }
  6752. else {
  6753. point = Vector3.Zero();
  6754. }
  6755. normal0 = Vector3.Cross(vt, point);
  6756. }
  6757. else {
  6758. normal0 = Vector3.Cross(vt, va);
  6759. Vector3.CrossToRef(normal0, vt, normal0);
  6760. }
  6761. normal0.normalize();
  6762. return normal0;
  6763. };
  6764. return Path3D;
  6765. }());
  6766. BABYLON.Path3D = Path3D;
  6767. var Curve3 = /** @class */ (function () {
  6768. /**
  6769. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6770. * A Curve3 is designed from a series of successive Vector3.
  6771. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6772. */
  6773. function Curve3(points) {
  6774. this._length = 0.0;
  6775. this._points = points;
  6776. this._length = this._computeLength(points);
  6777. }
  6778. /**
  6779. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6780. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6781. * @param v1 (Vector3) the control point
  6782. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6783. * @param nbPoints (integer) the wanted number of points in the curve
  6784. */
  6785. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6786. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6787. var bez = new Array();
  6788. var equation = function (t, val0, val1, val2) {
  6789. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6790. return res;
  6791. };
  6792. for (var i = 0; i <= nbPoints; i++) {
  6793. 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)));
  6794. }
  6795. return new Curve3(bez);
  6796. };
  6797. /**
  6798. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6799. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6800. * @param v1 (Vector3) the first control point
  6801. * @param v2 (Vector3) the second control point
  6802. * @param v3 (Vector3) the end point of the Cubic Bezier
  6803. * @param nbPoints (integer) the wanted number of points in the curve
  6804. */
  6805. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6806. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6807. var bez = new Array();
  6808. var equation = function (t, val0, val1, val2, val3) {
  6809. 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;
  6810. return res;
  6811. };
  6812. for (var i = 0; i <= nbPoints; i++) {
  6813. 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)));
  6814. }
  6815. return new Curve3(bez);
  6816. };
  6817. /**
  6818. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6819. * @param p1 (Vector3) the origin point of the Hermite Spline
  6820. * @param t1 (Vector3) the tangent vector at the origin point
  6821. * @param p2 (Vector3) the end point of the Hermite Spline
  6822. * @param t2 (Vector3) the tangent vector at the end point
  6823. * @param nbPoints (integer) the wanted number of points in the curve
  6824. */
  6825. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6826. var hermite = new Array();
  6827. var step = 1.0 / nbPoints;
  6828. for (var i = 0; i <= nbPoints; i++) {
  6829. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6830. }
  6831. return new Curve3(hermite);
  6832. };
  6833. /**
  6834. * Returns a Curve3 object along a CatmullRom Spline curve :
  6835. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6836. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6837. */
  6838. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6839. var totalPoints = new Array();
  6840. totalPoints.push(points[0].clone());
  6841. Array.prototype.push.apply(totalPoints, points);
  6842. totalPoints.push(points[points.length - 1].clone());
  6843. var catmullRom = new Array();
  6844. var step = 1.0 / nbPoints;
  6845. var amount = 0.0;
  6846. for (var i = 0; i < totalPoints.length - 3; i++) {
  6847. amount = 0;
  6848. for (var c = 0; c < nbPoints; c++) {
  6849. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6850. amount += step;
  6851. }
  6852. }
  6853. i--;
  6854. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6855. return new Curve3(catmullRom);
  6856. };
  6857. /**
  6858. * Returns the Curve3 stored array of successive Vector3
  6859. */
  6860. Curve3.prototype.getPoints = function () {
  6861. return this._points;
  6862. };
  6863. /**
  6864. * Returns the computed length (float) of the curve.
  6865. */
  6866. Curve3.prototype.length = function () {
  6867. return this._length;
  6868. };
  6869. /**
  6870. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6871. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6872. * curveA and curveB keep unchanged.
  6873. */
  6874. Curve3.prototype.continue = function (curve) {
  6875. var lastPoint = this._points[this._points.length - 1];
  6876. var continuedPoints = this._points.slice();
  6877. var curvePoints = curve.getPoints();
  6878. for (var i = 1; i < curvePoints.length; i++) {
  6879. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6880. }
  6881. var continuedCurve = new Curve3(continuedPoints);
  6882. return continuedCurve;
  6883. };
  6884. Curve3.prototype._computeLength = function (path) {
  6885. var l = 0;
  6886. for (var i = 1; i < path.length; i++) {
  6887. l += (path[i].subtract(path[i - 1])).length();
  6888. }
  6889. return l;
  6890. };
  6891. return Curve3;
  6892. }());
  6893. BABYLON.Curve3 = Curve3;
  6894. // Vertex formats
  6895. var PositionNormalVertex = /** @class */ (function () {
  6896. function PositionNormalVertex(position, normal) {
  6897. if (position === void 0) { position = Vector3.Zero(); }
  6898. if (normal === void 0) { normal = Vector3.Up(); }
  6899. this.position = position;
  6900. this.normal = normal;
  6901. }
  6902. PositionNormalVertex.prototype.clone = function () {
  6903. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6904. };
  6905. return PositionNormalVertex;
  6906. }());
  6907. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6908. var PositionNormalTextureVertex = /** @class */ (function () {
  6909. function PositionNormalTextureVertex(position, normal, uv) {
  6910. if (position === void 0) { position = Vector3.Zero(); }
  6911. if (normal === void 0) { normal = Vector3.Up(); }
  6912. if (uv === void 0) { uv = Vector2.Zero(); }
  6913. this.position = position;
  6914. this.normal = normal;
  6915. this.uv = uv;
  6916. }
  6917. PositionNormalTextureVertex.prototype.clone = function () {
  6918. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6919. };
  6920. return PositionNormalTextureVertex;
  6921. }());
  6922. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6923. // Temporary pre-allocated objects for engine internal use
  6924. // usage in any internal function :
  6925. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6926. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6927. var Tmp = /** @class */ (function () {
  6928. function Tmp() {
  6929. }
  6930. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6931. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6932. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6933. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6934. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6935. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6936. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6937. Matrix.Zero(), Matrix.Zero(),
  6938. Matrix.Zero(), Matrix.Zero(),
  6939. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6940. return Tmp;
  6941. }());
  6942. BABYLON.Tmp = Tmp;
  6943. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6944. var MathTmp = /** @class */ (function () {
  6945. function MathTmp() {
  6946. }
  6947. MathTmp.Vector3 = [Vector3.Zero()];
  6948. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6949. MathTmp.Quaternion = [Quaternion.Zero()];
  6950. return MathTmp;
  6951. }());
  6952. })(BABYLON || (BABYLON = {}));
  6953. //# sourceMappingURL=babylon.math.js.map
  6954. "use strict";
  6955. var BABYLON;
  6956. (function (BABYLON) {
  6957. var Scalar = /** @class */ (function () {
  6958. function Scalar() {
  6959. }
  6960. /**
  6961. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6962. */
  6963. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6964. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6965. var num = a - b;
  6966. return -epsilon <= num && num <= epsilon;
  6967. };
  6968. /**
  6969. * Returns a string : the upper case translation of the number i to hexadecimal.
  6970. */
  6971. Scalar.ToHex = function (i) {
  6972. var str = i.toString(16);
  6973. if (i <= 15) {
  6974. return ("0" + str).toUpperCase();
  6975. }
  6976. return str.toUpperCase();
  6977. };
  6978. /**
  6979. * Returns -1 if value is negative and +1 is value is positive.
  6980. * Returns the value itself if it's equal to zero.
  6981. */
  6982. Scalar.Sign = function (value) {
  6983. value = +value; // convert to a number
  6984. if (value === 0 || isNaN(value))
  6985. return value;
  6986. return value > 0 ? 1 : -1;
  6987. };
  6988. /**
  6989. * Returns the value itself if it's between min and max.
  6990. * Returns min if the value is lower than min.
  6991. * Returns max if the value is greater than max.
  6992. */
  6993. Scalar.Clamp = function (value, min, max) {
  6994. if (min === void 0) { min = 0; }
  6995. if (max === void 0) { max = 1; }
  6996. return Math.min(max, Math.max(min, value));
  6997. };
  6998. /**
  6999. * Returns the log2 of value.
  7000. */
  7001. Scalar.Log2 = function (value) {
  7002. return Math.log(value) * Math.LOG2E;
  7003. };
  7004. /**
  7005. * Loops the value, so that it is never larger than length and never smaller than 0.
  7006. *
  7007. * This is similar to the modulo operator but it works with floating point numbers.
  7008. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7009. * With t = 5 and length = 2.5, the result would be 0.0.
  7010. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7011. */
  7012. Scalar.Repeat = function (value, length) {
  7013. return value - Math.floor(value / length) * length;
  7014. };
  7015. /**
  7016. * Normalize the value between 0.0 and 1.0 using min and max values
  7017. */
  7018. Scalar.Normalize = function (value, min, max) {
  7019. return (value - min) / (max - min);
  7020. };
  7021. /**
  7022. * Denormalize the value from 0.0 and 1.0 using min and max values
  7023. */
  7024. Scalar.Denormalize = function (normalized, min, max) {
  7025. return (normalized * (max - min) + min);
  7026. };
  7027. /**
  7028. * Calculates the shortest difference between two given angles given in degrees.
  7029. */
  7030. Scalar.DeltaAngle = function (current, target) {
  7031. var num = Scalar.Repeat(target - current, 360.0);
  7032. if (num > 180.0) {
  7033. num -= 360.0;
  7034. }
  7035. return num;
  7036. };
  7037. /**
  7038. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7039. *
  7040. * The returned value will move back and forth between 0 and length
  7041. */
  7042. Scalar.PingPong = function (tx, length) {
  7043. var t = Scalar.Repeat(tx, length * 2.0);
  7044. return length - Math.abs(t - length);
  7045. };
  7046. /**
  7047. * Interpolates between min and max with smoothing at the limits.
  7048. *
  7049. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7050. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7051. */
  7052. Scalar.SmoothStep = function (from, to, tx) {
  7053. var t = Scalar.Clamp(tx);
  7054. t = -2.0 * t * t * t + 3.0 * t * t;
  7055. return to * t + from * (1.0 - t);
  7056. };
  7057. /**
  7058. * Moves a value current towards target.
  7059. *
  7060. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7061. * Negative values of maxDelta pushes the value away from target.
  7062. */
  7063. Scalar.MoveTowards = function (current, target, maxDelta) {
  7064. var result = 0;
  7065. if (Math.abs(target - current) <= maxDelta) {
  7066. result = target;
  7067. }
  7068. else {
  7069. result = current + Scalar.Sign(target - current) * maxDelta;
  7070. }
  7071. return result;
  7072. };
  7073. /**
  7074. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7075. *
  7076. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7077. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7078. */
  7079. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7080. var num = Scalar.DeltaAngle(current, target);
  7081. var result = 0;
  7082. if (-maxDelta < num && num < maxDelta) {
  7083. result = target;
  7084. }
  7085. else {
  7086. target = current + num;
  7087. result = Scalar.MoveTowards(current, target, maxDelta);
  7088. }
  7089. return result;
  7090. };
  7091. /**
  7092. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7093. */
  7094. Scalar.Lerp = function (start, end, amount) {
  7095. return start + ((end - start) * amount);
  7096. };
  7097. /**
  7098. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7099. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7100. */
  7101. Scalar.LerpAngle = function (start, end, amount) {
  7102. var num = Scalar.Repeat(end - start, 360.0);
  7103. if (num > 180.0) {
  7104. num -= 360.0;
  7105. }
  7106. return start + num * Scalar.Clamp(amount);
  7107. };
  7108. /**
  7109. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7110. */
  7111. Scalar.InverseLerp = function (a, b, value) {
  7112. var result = 0;
  7113. if (a != b) {
  7114. result = Scalar.Clamp((value - a) / (b - a));
  7115. }
  7116. else {
  7117. result = 0.0;
  7118. }
  7119. return result;
  7120. };
  7121. /**
  7122. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7123. */
  7124. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7125. var squared = amount * amount;
  7126. var cubed = amount * squared;
  7127. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7128. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7129. var part3 = (cubed - (2.0 * squared)) + amount;
  7130. var part4 = cubed - squared;
  7131. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7132. };
  7133. /**
  7134. * Returns a random float number between and min and max values
  7135. */
  7136. Scalar.RandomRange = function (min, max) {
  7137. if (min === max)
  7138. return min;
  7139. return ((Math.random() * (max - min)) + min);
  7140. };
  7141. /**
  7142. * This function returns percentage of a number in a given range.
  7143. *
  7144. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7145. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7146. */
  7147. Scalar.RangeToPercent = function (number, min, max) {
  7148. return ((number - min) / (max - min));
  7149. };
  7150. /**
  7151. * This function returns number that corresponds to the percentage in a given range.
  7152. *
  7153. * PercentToRange(0.34,0,100) will return 34.
  7154. */
  7155. Scalar.PercentToRange = function (percent, min, max) {
  7156. return ((max - min) * percent + min);
  7157. };
  7158. /**
  7159. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7160. * @param angle The angle to normalize in radian.
  7161. * @return The converted angle.
  7162. */
  7163. Scalar.NormalizeRadians = function (angle) {
  7164. // More precise but slower version kept for reference.
  7165. // angle = angle % Tools.TwoPi;
  7166. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7167. //if (angle > Math.PI) {
  7168. // angle -= Tools.TwoPi;
  7169. //}
  7170. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7171. return angle;
  7172. };
  7173. /**
  7174. * Two pi constants convenient for computation.
  7175. */
  7176. Scalar.TwoPi = Math.PI * 2;
  7177. return Scalar;
  7178. }());
  7179. BABYLON.Scalar = Scalar;
  7180. })(BABYLON || (BABYLON = {}));
  7181. //# sourceMappingURL=babylon.math.scalar.js.map
  7182. "use strict";
  7183. //# sourceMappingURL=babylon.mixins.js.map
  7184. "use strict";
  7185. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7186. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7187. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7188. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7189. //# sourceMappingURL=babylon.webgl2.js.map
  7190. "use strict";
  7191. var BABYLON;
  7192. (function (BABYLON) {
  7193. var __decoratorInitialStore = {};
  7194. var __mergedStore = {};
  7195. var _copySource = function (creationFunction, source, instanciate) {
  7196. var destination = creationFunction();
  7197. // Tags
  7198. if (BABYLON.Tags) {
  7199. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7200. }
  7201. var classStore = getMergedStore(destination);
  7202. // Properties
  7203. for (var property in classStore) {
  7204. var propertyDescriptor = classStore[property];
  7205. var sourceProperty = source[property];
  7206. var propertyType = propertyDescriptor.type;
  7207. if (sourceProperty !== undefined && sourceProperty !== null) {
  7208. switch (propertyType) {
  7209. case 0: // Value
  7210. case 6:// Mesh reference
  7211. destination[property] = sourceProperty;
  7212. break;
  7213. case 1:// Texture
  7214. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7215. break;
  7216. case 2: // Color3
  7217. case 3: // FresnelParameters
  7218. case 4: // Vector2
  7219. case 5: // Vector3
  7220. case 7: // Color Curves
  7221. case 10:// Quaternion
  7222. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7223. break;
  7224. }
  7225. }
  7226. }
  7227. return destination;
  7228. };
  7229. function getDirectStore(target) {
  7230. var classKey = target.getClassName();
  7231. if (!__decoratorInitialStore[classKey]) {
  7232. __decoratorInitialStore[classKey] = {};
  7233. }
  7234. return __decoratorInitialStore[classKey];
  7235. }
  7236. /**
  7237. * Return the list of properties flagged as serializable
  7238. * @param target: host object
  7239. */
  7240. function getMergedStore(target) {
  7241. var classKey = target.getClassName();
  7242. if (__mergedStore[classKey]) {
  7243. return __mergedStore[classKey];
  7244. }
  7245. __mergedStore[classKey] = {};
  7246. var store = __mergedStore[classKey];
  7247. var currentTarget = target;
  7248. var currentKey = classKey;
  7249. while (currentKey) {
  7250. var initialStore = __decoratorInitialStore[currentKey];
  7251. for (var property in initialStore) {
  7252. store[property] = initialStore[property];
  7253. }
  7254. var parent_1 = void 0;
  7255. var done = false;
  7256. do {
  7257. parent_1 = Object.getPrototypeOf(currentTarget);
  7258. if (!parent_1.getClassName) {
  7259. done = true;
  7260. break;
  7261. }
  7262. if (parent_1.getClassName() !== currentKey) {
  7263. break;
  7264. }
  7265. currentTarget = parent_1;
  7266. } while (parent_1);
  7267. if (done) {
  7268. break;
  7269. }
  7270. currentKey = parent_1.getClassName();
  7271. currentTarget = parent_1;
  7272. }
  7273. return store;
  7274. }
  7275. function generateSerializableMember(type, sourceName) {
  7276. return function (target, propertyKey) {
  7277. var classStore = getDirectStore(target);
  7278. if (!classStore[propertyKey]) {
  7279. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7280. }
  7281. };
  7282. }
  7283. function generateExpandMember(setCallback, targetKey) {
  7284. if (targetKey === void 0) { targetKey = null; }
  7285. return function (target, propertyKey) {
  7286. var key = targetKey || ("_" + propertyKey);
  7287. Object.defineProperty(target, propertyKey, {
  7288. get: function () {
  7289. return this[key];
  7290. },
  7291. set: function (value) {
  7292. if (this[key] === value) {
  7293. return;
  7294. }
  7295. this[key] = value;
  7296. target[setCallback].apply(this);
  7297. },
  7298. enumerable: true,
  7299. configurable: true
  7300. });
  7301. };
  7302. }
  7303. function expandToProperty(callback, targetKey) {
  7304. if (targetKey === void 0) { targetKey = null; }
  7305. return generateExpandMember(callback, targetKey);
  7306. }
  7307. BABYLON.expandToProperty = expandToProperty;
  7308. function serialize(sourceName) {
  7309. return generateSerializableMember(0, sourceName); // value member
  7310. }
  7311. BABYLON.serialize = serialize;
  7312. function serializeAsTexture(sourceName) {
  7313. return generateSerializableMember(1, sourceName); // texture member
  7314. }
  7315. BABYLON.serializeAsTexture = serializeAsTexture;
  7316. function serializeAsColor3(sourceName) {
  7317. return generateSerializableMember(2, sourceName); // color3 member
  7318. }
  7319. BABYLON.serializeAsColor3 = serializeAsColor3;
  7320. function serializeAsFresnelParameters(sourceName) {
  7321. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7322. }
  7323. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7324. function serializeAsVector2(sourceName) {
  7325. return generateSerializableMember(4, sourceName); // vector2 member
  7326. }
  7327. BABYLON.serializeAsVector2 = serializeAsVector2;
  7328. function serializeAsVector3(sourceName) {
  7329. return generateSerializableMember(5, sourceName); // vector3 member
  7330. }
  7331. BABYLON.serializeAsVector3 = serializeAsVector3;
  7332. function serializeAsMeshReference(sourceName) {
  7333. return generateSerializableMember(6, sourceName); // mesh reference member
  7334. }
  7335. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7336. function serializeAsColorCurves(sourceName) {
  7337. return generateSerializableMember(7, sourceName); // color curves
  7338. }
  7339. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7340. function serializeAsColor4(sourceName) {
  7341. return generateSerializableMember(8, sourceName); // color 4
  7342. }
  7343. BABYLON.serializeAsColor4 = serializeAsColor4;
  7344. function serializeAsImageProcessingConfiguration(sourceName) {
  7345. return generateSerializableMember(9, sourceName); // image processing
  7346. }
  7347. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7348. function serializeAsQuaternion(sourceName) {
  7349. return generateSerializableMember(10, sourceName); // quaternion member
  7350. }
  7351. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7352. var SerializationHelper = /** @class */ (function () {
  7353. function SerializationHelper() {
  7354. }
  7355. SerializationHelper.Serialize = function (entity, serializationObject) {
  7356. if (!serializationObject) {
  7357. serializationObject = {};
  7358. }
  7359. // Tags
  7360. if (BABYLON.Tags) {
  7361. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7362. }
  7363. var serializedProperties = getMergedStore(entity);
  7364. // Properties
  7365. for (var property in serializedProperties) {
  7366. var propertyDescriptor = serializedProperties[property];
  7367. var targetPropertyName = propertyDescriptor.sourceName || property;
  7368. var propertyType = propertyDescriptor.type;
  7369. var sourceProperty = entity[property];
  7370. if (sourceProperty !== undefined && sourceProperty !== null) {
  7371. switch (propertyType) {
  7372. case 0:// Value
  7373. serializationObject[targetPropertyName] = sourceProperty;
  7374. break;
  7375. case 1:// Texture
  7376. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7377. break;
  7378. case 2:// Color3
  7379. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7380. break;
  7381. case 3:// FresnelParameters
  7382. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7383. break;
  7384. case 4:// Vector2
  7385. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7386. break;
  7387. case 5:// Vector3
  7388. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7389. break;
  7390. case 6:// Mesh reference
  7391. serializationObject[targetPropertyName] = sourceProperty.id;
  7392. break;
  7393. case 7:// Color Curves
  7394. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7395. break;
  7396. case 8:// Color 4
  7397. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7398. break;
  7399. case 9:// Image Processing
  7400. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7401. break;
  7402. }
  7403. }
  7404. }
  7405. return serializationObject;
  7406. };
  7407. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7408. if (rootUrl === void 0) { rootUrl = null; }
  7409. var destination = creationFunction();
  7410. if (!rootUrl) {
  7411. rootUrl = "";
  7412. }
  7413. // Tags
  7414. if (BABYLON.Tags) {
  7415. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7416. }
  7417. var classStore = getMergedStore(destination);
  7418. // Properties
  7419. for (var property in classStore) {
  7420. var propertyDescriptor = classStore[property];
  7421. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7422. var propertyType = propertyDescriptor.type;
  7423. if (sourceProperty !== undefined && sourceProperty !== null) {
  7424. var dest = destination;
  7425. switch (propertyType) {
  7426. case 0:// Value
  7427. dest[property] = sourceProperty;
  7428. break;
  7429. case 1:// Texture
  7430. if (scene) {
  7431. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7432. }
  7433. break;
  7434. case 2:// Color3
  7435. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7436. break;
  7437. case 3:// FresnelParameters
  7438. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7439. break;
  7440. case 4:// Vector2
  7441. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7442. break;
  7443. case 5:// Vector3
  7444. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7445. break;
  7446. case 6:// Mesh reference
  7447. if (scene) {
  7448. dest[property] = scene.getLastMeshByID(sourceProperty);
  7449. }
  7450. break;
  7451. case 7:// Color Curves
  7452. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7453. break;
  7454. case 8:// Color 4
  7455. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7456. break;
  7457. case 9:// Image Processing
  7458. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7459. break;
  7460. }
  7461. }
  7462. }
  7463. return destination;
  7464. };
  7465. SerializationHelper.Clone = function (creationFunction, source) {
  7466. return _copySource(creationFunction, source, false);
  7467. };
  7468. SerializationHelper.Instanciate = function (creationFunction, source) {
  7469. return _copySource(creationFunction, source, true);
  7470. };
  7471. return SerializationHelper;
  7472. }());
  7473. BABYLON.SerializationHelper = SerializationHelper;
  7474. })(BABYLON || (BABYLON = {}));
  7475. //# sourceMappingURL=babylon.decorators.js.map
  7476. "use strict";
  7477. var BABYLON;
  7478. (function (BABYLON) {
  7479. /**
  7480. * Wrapper class for promise with external resolve and reject.
  7481. */
  7482. var Deferred = /** @class */ (function () {
  7483. /**
  7484. * Constructor for this deferred object.
  7485. */
  7486. function Deferred() {
  7487. var _this = this;
  7488. this.promise = new Promise(function (resolve, reject) {
  7489. _this._resolve = resolve;
  7490. _this._reject = reject;
  7491. });
  7492. }
  7493. Object.defineProperty(Deferred.prototype, "resolve", {
  7494. /**
  7495. * The resolve method of the promise associated with this deferred object.
  7496. */
  7497. get: function () {
  7498. return this._resolve;
  7499. },
  7500. enumerable: true,
  7501. configurable: true
  7502. });
  7503. Object.defineProperty(Deferred.prototype, "reject", {
  7504. /**
  7505. * The reject method of the promise associated with this deferred object.
  7506. */
  7507. get: function () {
  7508. return this._reject;
  7509. },
  7510. enumerable: true,
  7511. configurable: true
  7512. });
  7513. return Deferred;
  7514. }());
  7515. BABYLON.Deferred = Deferred;
  7516. })(BABYLON || (BABYLON = {}));
  7517. //# sourceMappingURL=babylon.deferred.js.map
  7518. "use strict";
  7519. var BABYLON;
  7520. (function (BABYLON) {
  7521. /**
  7522. * A class serves as a medium between the observable and its observers
  7523. */
  7524. var EventState = /** @class */ (function () {
  7525. /**
  7526. * Create a new EventState
  7527. * @param mask defines the mask associated with this state
  7528. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7529. * @param target defines the original target of the state
  7530. * @param currentTarget defines the current target of the state
  7531. */
  7532. function EventState(mask, skipNextObservers, target, currentTarget) {
  7533. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7534. this.initalize(mask, skipNextObservers, target, currentTarget);
  7535. }
  7536. /**
  7537. * Initialize the current event state
  7538. * @param mask defines the mask associated with this state
  7539. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7540. * @param target defines the original target of the state
  7541. * @param currentTarget defines the current target of the state
  7542. * @returns the current event state
  7543. */
  7544. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7545. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7546. this.mask = mask;
  7547. this.skipNextObservers = skipNextObservers;
  7548. this.target = target;
  7549. this.currentTarget = currentTarget;
  7550. return this;
  7551. };
  7552. return EventState;
  7553. }());
  7554. BABYLON.EventState = EventState;
  7555. /**
  7556. * Represent an Observer registered to a given Observable object.
  7557. */
  7558. var Observer = /** @class */ (function () {
  7559. /**
  7560. * Creates a new observer
  7561. * @param callback defines the callback to call when the observer is notified
  7562. * @param mask defines the mask of the observer (used to filter notifications)
  7563. * @param scope defines the current scope used to restore the JS context
  7564. */
  7565. function Observer(
  7566. /**
  7567. * Defines the callback to call when the observer is notified
  7568. */
  7569. callback,
  7570. /**
  7571. * Defines the mask of the observer (used to filter notifications)
  7572. */
  7573. mask,
  7574. /**
  7575. * Defines the current scope used to restore the JS context
  7576. */
  7577. scope) {
  7578. if (scope === void 0) { scope = null; }
  7579. this.callback = callback;
  7580. this.mask = mask;
  7581. this.scope = scope;
  7582. /** @ignore */
  7583. this._willBeUnregistered = false;
  7584. /**
  7585. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7586. */
  7587. this.unregisterOnNextCall = false;
  7588. }
  7589. return Observer;
  7590. }());
  7591. BABYLON.Observer = Observer;
  7592. /**
  7593. * Represent a list of observers registered to multiple Observables object.
  7594. */
  7595. var MultiObserver = /** @class */ (function () {
  7596. function MultiObserver() {
  7597. }
  7598. /**
  7599. * Release associated resources
  7600. */
  7601. MultiObserver.prototype.dispose = function () {
  7602. if (this._observers && this._observables) {
  7603. for (var index = 0; index < this._observers.length; index++) {
  7604. this._observables[index].remove(this._observers[index]);
  7605. }
  7606. }
  7607. this._observers = null;
  7608. this._observables = null;
  7609. };
  7610. /**
  7611. * Raise a callback when one of the observable will notify
  7612. * @param observables defines a list of observables to watch
  7613. * @param callback defines the callback to call on notification
  7614. * @param mask defines the mask used to filter notifications
  7615. * @param scope defines the current scope used to restore the JS context
  7616. * @returns the new MultiObserver
  7617. */
  7618. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7619. if (mask === void 0) { mask = -1; }
  7620. if (scope === void 0) { scope = null; }
  7621. var result = new MultiObserver();
  7622. result._observers = new Array();
  7623. result._observables = observables;
  7624. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7625. var observable = observables_1[_i];
  7626. var observer = observable.add(callback, mask, false, scope);
  7627. if (observer) {
  7628. result._observers.push(observer);
  7629. }
  7630. }
  7631. return result;
  7632. };
  7633. return MultiObserver;
  7634. }());
  7635. BABYLON.MultiObserver = MultiObserver;
  7636. /**
  7637. * The Observable class is a simple implementation of the Observable pattern.
  7638. * 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.
  7639. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7640. * 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).
  7641. * 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.
  7642. */
  7643. var Observable = /** @class */ (function () {
  7644. /**
  7645. * Creates a new observable
  7646. * @param onObserverAdded defines a callback to call when a new observer is added
  7647. */
  7648. function Observable(onObserverAdded) {
  7649. this._observers = new Array();
  7650. this._eventState = new EventState(0);
  7651. if (onObserverAdded) {
  7652. this._onObserverAdded = onObserverAdded;
  7653. }
  7654. }
  7655. /**
  7656. * Create a new Observer with the specified callback
  7657. * @param callback the callback that will be executed for that Observer
  7658. * @param mask the mask used to filter observers
  7659. * @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.
  7660. * @param scope optional scope for the callback to be called from
  7661. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7662. * @returns the new observer created for the callback
  7663. */
  7664. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7665. if (mask === void 0) { mask = -1; }
  7666. if (insertFirst === void 0) { insertFirst = false; }
  7667. if (scope === void 0) { scope = null; }
  7668. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7669. if (!callback) {
  7670. return null;
  7671. }
  7672. var observer = new Observer(callback, mask, scope);
  7673. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7674. if (insertFirst) {
  7675. this._observers.unshift(observer);
  7676. }
  7677. else {
  7678. this._observers.push(observer);
  7679. }
  7680. if (this._onObserverAdded) {
  7681. this._onObserverAdded(observer);
  7682. }
  7683. return observer;
  7684. };
  7685. /**
  7686. * Remove an Observer from the Observable object
  7687. * @param observer the instance of the Observer to remove
  7688. * @returns false if it doesn't belong to this Observable
  7689. */
  7690. Observable.prototype.remove = function (observer) {
  7691. if (!observer) {
  7692. return false;
  7693. }
  7694. var index = this._observers.indexOf(observer);
  7695. if (index !== -1) {
  7696. this._observers.splice(index, 1);
  7697. return true;
  7698. }
  7699. return false;
  7700. };
  7701. /**
  7702. * Remove a callback from the Observable object
  7703. * @param callback the callback to remove
  7704. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7705. * @returns false if it doesn't belong to this Observable
  7706. */
  7707. Observable.prototype.removeCallback = function (callback, scope) {
  7708. for (var index = 0; index < this._observers.length; index++) {
  7709. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7710. this._observers.splice(index, 1);
  7711. return true;
  7712. }
  7713. }
  7714. return false;
  7715. };
  7716. Observable.prototype._deferUnregister = function (observer) {
  7717. var _this = this;
  7718. observer.unregisterOnNextCall = false;
  7719. observer._willBeUnregistered = true;
  7720. BABYLON.Tools.SetImmediate(function () {
  7721. _this.remove(observer);
  7722. });
  7723. };
  7724. /**
  7725. * Notify all Observers by calling their respective callback with the given data
  7726. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7727. * @param eventData defines the data to send to all observers
  7728. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7729. * @param target defines the original target of the state
  7730. * @param currentTarget defines the current target of the state
  7731. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7732. */
  7733. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7734. if (mask === void 0) { mask = -1; }
  7735. if (!this._observers.length) {
  7736. return true;
  7737. }
  7738. var state = this._eventState;
  7739. state.mask = mask;
  7740. state.target = target;
  7741. state.currentTarget = currentTarget;
  7742. state.skipNextObservers = false;
  7743. state.lastReturnValue = eventData;
  7744. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7745. var obs = _a[_i];
  7746. if (obs._willBeUnregistered) {
  7747. continue;
  7748. }
  7749. if (obs.mask & mask) {
  7750. if (obs.scope) {
  7751. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7752. }
  7753. else {
  7754. state.lastReturnValue = obs.callback(eventData, state);
  7755. }
  7756. if (obs.unregisterOnNextCall) {
  7757. this._deferUnregister(obs);
  7758. }
  7759. }
  7760. if (state.skipNextObservers) {
  7761. return false;
  7762. }
  7763. }
  7764. return true;
  7765. };
  7766. /**
  7767. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7768. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7769. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7770. * and it is crucial that all callbacks will be executed.
  7771. * The order of the callbacks is kept, callbacks are not executed parallel.
  7772. *
  7773. * @param eventData The data to be sent to each callback
  7774. * @param mask is used to filter observers defaults to -1
  7775. * @param target defines the callback target (see EventState)
  7776. * @param currentTarget defines he current object in the bubbling phase
  7777. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7778. */
  7779. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7780. var _this = this;
  7781. if (mask === void 0) { mask = -1; }
  7782. // create an empty promise
  7783. var p = Promise.resolve(eventData);
  7784. // no observers? return this promise.
  7785. if (!this._observers.length) {
  7786. return p;
  7787. }
  7788. var state = this._eventState;
  7789. state.mask = mask;
  7790. state.target = target;
  7791. state.currentTarget = currentTarget;
  7792. state.skipNextObservers = false;
  7793. // execute one callback after another (not using Promise.all, the order is important)
  7794. this._observers.forEach(function (obs) {
  7795. if (state.skipNextObservers) {
  7796. return;
  7797. }
  7798. if (obs._willBeUnregistered) {
  7799. return;
  7800. }
  7801. if (obs.mask & mask) {
  7802. if (obs.scope) {
  7803. p = p.then(function (lastReturnedValue) {
  7804. state.lastReturnValue = lastReturnedValue;
  7805. return obs.callback.apply(obs.scope, [eventData, state]);
  7806. });
  7807. }
  7808. else {
  7809. p = p.then(function (lastReturnedValue) {
  7810. state.lastReturnValue = lastReturnedValue;
  7811. return obs.callback(eventData, state);
  7812. });
  7813. }
  7814. if (obs.unregisterOnNextCall) {
  7815. _this._deferUnregister(obs);
  7816. }
  7817. }
  7818. });
  7819. // return the eventData
  7820. return p.then(function () { return eventData; });
  7821. };
  7822. /**
  7823. * Notify a specific observer
  7824. * @param observer defines the observer to notify
  7825. * @param eventData defines the data to be sent to each callback
  7826. * @param mask is used to filter observers defaults to -1
  7827. */
  7828. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7829. if (mask === void 0) { mask = -1; }
  7830. var state = this._eventState;
  7831. state.mask = mask;
  7832. state.skipNextObservers = false;
  7833. observer.callback(eventData, state);
  7834. };
  7835. /**
  7836. * Gets a boolean indicating if the observable has at least one observer
  7837. * @returns true is the Observable has at least one Observer registered
  7838. */
  7839. Observable.prototype.hasObservers = function () {
  7840. return this._observers.length > 0;
  7841. };
  7842. /**
  7843. * Clear the list of observers
  7844. */
  7845. Observable.prototype.clear = function () {
  7846. this._observers = new Array();
  7847. this._onObserverAdded = null;
  7848. };
  7849. /**
  7850. * Clone the current observable
  7851. * @returns a new observable
  7852. */
  7853. Observable.prototype.clone = function () {
  7854. var result = new Observable();
  7855. result._observers = this._observers.slice(0);
  7856. return result;
  7857. };
  7858. /**
  7859. * Does this observable handles observer registered with a given mask
  7860. * @param mask defines the mask to be tested
  7861. * @return whether or not one observer registered with the given mask is handeled
  7862. **/
  7863. Observable.prototype.hasSpecificMask = function (mask) {
  7864. if (mask === void 0) { mask = -1; }
  7865. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7866. var obs = _a[_i];
  7867. if (obs.mask & mask || obs.mask === mask) {
  7868. return true;
  7869. }
  7870. }
  7871. return false;
  7872. };
  7873. return Observable;
  7874. }());
  7875. BABYLON.Observable = Observable;
  7876. })(BABYLON || (BABYLON = {}));
  7877. //# sourceMappingURL=babylon.observable.js.map
  7878. "use strict";
  7879. var BABYLON;
  7880. (function (BABYLON) {
  7881. var SmartArray = /** @class */ (function () {
  7882. function SmartArray(capacity) {
  7883. this.length = 0;
  7884. this.data = new Array(capacity);
  7885. this._id = SmartArray._GlobalId++;
  7886. }
  7887. SmartArray.prototype.push = function (value) {
  7888. this.data[this.length++] = value;
  7889. if (this.length > this.data.length) {
  7890. this.data.length *= 2;
  7891. }
  7892. };
  7893. SmartArray.prototype.forEach = function (func) {
  7894. for (var index = 0; index < this.length; index++) {
  7895. func(this.data[index]);
  7896. }
  7897. };
  7898. SmartArray.prototype.sort = function (compareFn) {
  7899. this.data.sort(compareFn);
  7900. };
  7901. SmartArray.prototype.reset = function () {
  7902. this.length = 0;
  7903. };
  7904. SmartArray.prototype.dispose = function () {
  7905. this.reset();
  7906. if (this.data) {
  7907. this.data.length = 0;
  7908. this.data = [];
  7909. }
  7910. };
  7911. SmartArray.prototype.concat = function (array) {
  7912. if (array.length === 0) {
  7913. return;
  7914. }
  7915. if (this.length + array.length > this.data.length) {
  7916. this.data.length = (this.length + array.length) * 2;
  7917. }
  7918. for (var index = 0; index < array.length; index++) {
  7919. this.data[this.length++] = (array.data || array)[index];
  7920. }
  7921. };
  7922. SmartArray.prototype.indexOf = function (value) {
  7923. var position = this.data.indexOf(value);
  7924. if (position >= this.length) {
  7925. return -1;
  7926. }
  7927. return position;
  7928. };
  7929. SmartArray.prototype.contains = function (value) {
  7930. return this.data.indexOf(value) !== -1;
  7931. };
  7932. // Statics
  7933. SmartArray._GlobalId = 0;
  7934. return SmartArray;
  7935. }());
  7936. BABYLON.SmartArray = SmartArray;
  7937. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7938. __extends(SmartArrayNoDuplicate, _super);
  7939. function SmartArrayNoDuplicate() {
  7940. var _this = _super !== null && _super.apply(this, arguments) || this;
  7941. _this._duplicateId = 0;
  7942. return _this;
  7943. }
  7944. SmartArrayNoDuplicate.prototype.push = function (value) {
  7945. _super.prototype.push.call(this, value);
  7946. if (!value.__smartArrayFlags) {
  7947. value.__smartArrayFlags = {};
  7948. }
  7949. value.__smartArrayFlags[this._id] = this._duplicateId;
  7950. };
  7951. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7952. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7953. return false;
  7954. }
  7955. this.push(value);
  7956. return true;
  7957. };
  7958. SmartArrayNoDuplicate.prototype.reset = function () {
  7959. _super.prototype.reset.call(this);
  7960. this._duplicateId++;
  7961. };
  7962. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7963. if (array.length === 0) {
  7964. return;
  7965. }
  7966. if (this.length + array.length > this.data.length) {
  7967. this.data.length = (this.length + array.length) * 2;
  7968. }
  7969. for (var index = 0; index < array.length; index++) {
  7970. var item = (array.data || array)[index];
  7971. this.pushNoDuplicate(item);
  7972. }
  7973. };
  7974. return SmartArrayNoDuplicate;
  7975. }(SmartArray));
  7976. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7977. })(BABYLON || (BABYLON = {}));
  7978. //# sourceMappingURL=babylon.smartArray.js.map
  7979. "use strict";
  7980. var BABYLON;
  7981. (function (BABYLON) {
  7982. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7983. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7984. var LoadFileError = /** @class */ (function (_super) {
  7985. __extends(LoadFileError, _super);
  7986. function LoadFileError(message, request) {
  7987. var _this = _super.call(this, message) || this;
  7988. _this.request = request;
  7989. _this.name = "LoadFileError";
  7990. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7991. return _this;
  7992. }
  7993. // Polyfill for Object.setPrototypeOf if necessary.
  7994. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7995. return LoadFileError;
  7996. }(Error));
  7997. BABYLON.LoadFileError = LoadFileError;
  7998. var RetryStrategy = /** @class */ (function () {
  7999. function RetryStrategy() {
  8000. }
  8001. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8002. if (maxRetries === void 0) { maxRetries = 3; }
  8003. if (baseInterval === void 0) { baseInterval = 500; }
  8004. return function (url, request, retryIndex) {
  8005. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8006. return -1;
  8007. }
  8008. return Math.pow(2, retryIndex) * baseInterval;
  8009. };
  8010. };
  8011. return RetryStrategy;
  8012. }());
  8013. BABYLON.RetryStrategy = RetryStrategy;
  8014. // Screenshots
  8015. var screenshotCanvas;
  8016. var cloneValue = function (source, destinationObject) {
  8017. if (!source)
  8018. return null;
  8019. if (source instanceof BABYLON.Mesh) {
  8020. return null;
  8021. }
  8022. if (source instanceof BABYLON.SubMesh) {
  8023. return source.clone(destinationObject);
  8024. }
  8025. else if (source.clone) {
  8026. return source.clone();
  8027. }
  8028. return null;
  8029. };
  8030. var Tools = /** @class */ (function () {
  8031. function Tools() {
  8032. }
  8033. /**
  8034. * Interpolates between a and b via alpha
  8035. * @param a The lower value (returned when alpha = 0)
  8036. * @param b The upper value (returned when alpha = 1)
  8037. * @param alpha The interpolation-factor
  8038. * @return The mixed value
  8039. */
  8040. Tools.Mix = function (a, b, alpha) {
  8041. return a * (1 - alpha) + b * alpha;
  8042. };
  8043. Tools.Instantiate = function (className) {
  8044. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8045. return Tools.RegisteredExternalClasses[className];
  8046. }
  8047. var arr = className.split(".");
  8048. var fn = (window || this);
  8049. for (var i = 0, len = arr.length; i < len; i++) {
  8050. fn = fn[arr[i]];
  8051. }
  8052. if (typeof fn !== "function") {
  8053. return null;
  8054. }
  8055. return fn;
  8056. };
  8057. /**
  8058. * Provides a slice function that will work even on IE
  8059. * @param data defines the array to slice
  8060. * @returns the new sliced array
  8061. */
  8062. Tools.Slice = function (data) {
  8063. if (data.slice) {
  8064. return data.slice();
  8065. }
  8066. return Array.prototype.slice.call(data);
  8067. };
  8068. Tools.SetImmediate = function (action) {
  8069. if (window.setImmediate) {
  8070. window.setImmediate(action);
  8071. }
  8072. else {
  8073. setTimeout(action, 1);
  8074. }
  8075. };
  8076. Tools.IsExponentOfTwo = function (value) {
  8077. var count = 1;
  8078. do {
  8079. count *= 2;
  8080. } while (count < value);
  8081. return count === value;
  8082. };
  8083. /**
  8084. * Find the next highest power of two.
  8085. * @param x Number to start search from.
  8086. * @return Next highest power of two.
  8087. */
  8088. Tools.CeilingPOT = function (x) {
  8089. x--;
  8090. x |= x >> 1;
  8091. x |= x >> 2;
  8092. x |= x >> 4;
  8093. x |= x >> 8;
  8094. x |= x >> 16;
  8095. x++;
  8096. return x;
  8097. };
  8098. /**
  8099. * Find the next lowest power of two.
  8100. * @param x Number to start search from.
  8101. * @return Next lowest power of two.
  8102. */
  8103. Tools.FloorPOT = function (x) {
  8104. x = x | (x >> 1);
  8105. x = x | (x >> 2);
  8106. x = x | (x >> 4);
  8107. x = x | (x >> 8);
  8108. x = x | (x >> 16);
  8109. return x - (x >> 1);
  8110. };
  8111. /**
  8112. * Find the nearest power of two.
  8113. * @param x Number to start search from.
  8114. * @return Next nearest power of two.
  8115. */
  8116. Tools.NearestPOT = function (x) {
  8117. var c = Tools.CeilingPOT(x);
  8118. var f = Tools.FloorPOT(x);
  8119. return (c - x) > (x - f) ? f : c;
  8120. };
  8121. Tools.GetExponentOfTwo = function (value, max, mode) {
  8122. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8123. var pot;
  8124. switch (mode) {
  8125. case BABYLON.Engine.SCALEMODE_FLOOR:
  8126. pot = Tools.FloorPOT(value);
  8127. break;
  8128. case BABYLON.Engine.SCALEMODE_NEAREST:
  8129. pot = Tools.NearestPOT(value);
  8130. break;
  8131. case BABYLON.Engine.SCALEMODE_CEILING:
  8132. default:
  8133. pot = Tools.CeilingPOT(value);
  8134. break;
  8135. }
  8136. return Math.min(pot, max);
  8137. };
  8138. Tools.GetFilename = function (path) {
  8139. var index = path.lastIndexOf("/");
  8140. if (index < 0)
  8141. return path;
  8142. return path.substring(index + 1);
  8143. };
  8144. /**
  8145. * Extracts the "folder" part of a path (everything before the filename).
  8146. * @param uri The URI to extract the info from
  8147. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8148. * @returns The "folder" part of the path
  8149. */
  8150. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8151. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8152. var index = uri.lastIndexOf("/");
  8153. if (index < 0) {
  8154. if (returnUnchangedIfNoSlash) {
  8155. return uri;
  8156. }
  8157. return "";
  8158. }
  8159. return uri.substring(0, index + 1);
  8160. };
  8161. Tools.GetDOMTextContent = function (element) {
  8162. var result = "";
  8163. var child = element.firstChild;
  8164. while (child) {
  8165. if (child.nodeType === 3) {
  8166. result += child.textContent;
  8167. }
  8168. child = child.nextSibling;
  8169. }
  8170. return result;
  8171. };
  8172. Tools.ToDegrees = function (angle) {
  8173. return angle * 180 / Math.PI;
  8174. };
  8175. Tools.ToRadians = function (angle) {
  8176. return angle * Math.PI / 180;
  8177. };
  8178. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8179. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8180. var output = "";
  8181. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8182. var i = 0;
  8183. var bytes = new Uint8Array(buffer);
  8184. while (i < bytes.length) {
  8185. chr1 = bytes[i++];
  8186. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8187. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8188. enc1 = chr1 >> 2;
  8189. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8190. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8191. enc4 = chr3 & 63;
  8192. if (isNaN(chr2)) {
  8193. enc3 = enc4 = 64;
  8194. }
  8195. else if (isNaN(chr3)) {
  8196. enc4 = 64;
  8197. }
  8198. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8199. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8200. }
  8201. return "data:image/png;base64," + output;
  8202. };
  8203. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8204. if (bias === void 0) { bias = null; }
  8205. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8206. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8207. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8208. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8209. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8210. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8211. }
  8212. if (bias) {
  8213. minimum.x -= minimum.x * bias.x + bias.y;
  8214. minimum.y -= minimum.y * bias.x + bias.y;
  8215. minimum.z -= minimum.z * bias.x + bias.y;
  8216. maximum.x += maximum.x * bias.x + bias.y;
  8217. maximum.y += maximum.y * bias.x + bias.y;
  8218. maximum.z += maximum.z * bias.x + bias.y;
  8219. }
  8220. return {
  8221. minimum: minimum,
  8222. maximum: maximum
  8223. };
  8224. };
  8225. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8226. if (bias === void 0) { bias = null; }
  8227. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8228. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8229. if (!stride) {
  8230. stride = 3;
  8231. }
  8232. for (var index = start; index < start + count; index++) {
  8233. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8234. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8235. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8236. }
  8237. if (bias) {
  8238. minimum.x -= minimum.x * bias.x + bias.y;
  8239. minimum.y -= minimum.y * bias.x + bias.y;
  8240. minimum.z -= minimum.z * bias.x + bias.y;
  8241. maximum.x += maximum.x * bias.x + bias.y;
  8242. maximum.y += maximum.y * bias.x + bias.y;
  8243. maximum.z += maximum.z * bias.x + bias.y;
  8244. }
  8245. return {
  8246. minimum: minimum,
  8247. maximum: maximum
  8248. };
  8249. };
  8250. Tools.Vector2ArrayFeeder = function (array) {
  8251. return function (index) {
  8252. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8253. var length = isFloatArray ? array.length / 2 : array.length;
  8254. if (index >= length) {
  8255. return null;
  8256. }
  8257. if (isFloatArray) {
  8258. var fa = array;
  8259. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8260. }
  8261. var a = array;
  8262. return a[index];
  8263. };
  8264. };
  8265. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8266. if (bias === void 0) { bias = null; }
  8267. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8268. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8269. var i = 0;
  8270. var cur = feeder(i++);
  8271. while (cur) {
  8272. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8273. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8274. cur = feeder(i++);
  8275. }
  8276. if (bias) {
  8277. minimum.x -= minimum.x * bias.x + bias.y;
  8278. minimum.y -= minimum.y * bias.x + bias.y;
  8279. maximum.x += maximum.x * bias.x + bias.y;
  8280. maximum.y += maximum.y * bias.x + bias.y;
  8281. }
  8282. return {
  8283. minimum: minimum,
  8284. maximum: maximum
  8285. };
  8286. };
  8287. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8288. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8289. return null;
  8290. return Array.isArray(obj) ? obj : [obj];
  8291. };
  8292. // Misc.
  8293. Tools.GetPointerPrefix = function () {
  8294. var eventPrefix = "pointer";
  8295. // Check if pointer events are supported
  8296. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8297. eventPrefix = "mouse";
  8298. }
  8299. return eventPrefix;
  8300. };
  8301. /**
  8302. * @param func - the function to be called
  8303. * @param requester - the object that will request the next frame. Falls back to window.
  8304. */
  8305. Tools.QueueNewFrame = function (func, requester) {
  8306. if (!Tools.IsWindowObjectExist()) {
  8307. return setTimeout(func, 16);
  8308. }
  8309. if (!requester) {
  8310. requester = window;
  8311. }
  8312. if (requester.requestAnimationFrame) {
  8313. return requester.requestAnimationFrame(func);
  8314. }
  8315. else if (requester.msRequestAnimationFrame) {
  8316. return requester.msRequestAnimationFrame(func);
  8317. }
  8318. else if (requester.webkitRequestAnimationFrame) {
  8319. return requester.webkitRequestAnimationFrame(func);
  8320. }
  8321. else if (requester.mozRequestAnimationFrame) {
  8322. return requester.mozRequestAnimationFrame(func);
  8323. }
  8324. else if (requester.oRequestAnimationFrame) {
  8325. return requester.oRequestAnimationFrame(func);
  8326. }
  8327. else {
  8328. return window.setTimeout(func, 16);
  8329. }
  8330. };
  8331. Tools.RequestFullscreen = function (element) {
  8332. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8333. if (!requestFunction)
  8334. return;
  8335. requestFunction.call(element);
  8336. };
  8337. Tools.ExitFullscreen = function () {
  8338. if (document.exitFullscreen) {
  8339. document.exitFullscreen();
  8340. }
  8341. else if (document.mozCancelFullScreen) {
  8342. document.mozCancelFullScreen();
  8343. }
  8344. else if (document.webkitCancelFullScreen) {
  8345. document.webkitCancelFullScreen();
  8346. }
  8347. else if (document.msCancelFullScreen) {
  8348. document.msCancelFullScreen();
  8349. }
  8350. };
  8351. Tools.SetCorsBehavior = function (url, element) {
  8352. if (url && url.indexOf("data:") === 0) {
  8353. return;
  8354. }
  8355. if (Tools.CorsBehavior) {
  8356. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8357. element.crossOrigin = Tools.CorsBehavior;
  8358. }
  8359. else {
  8360. var result = Tools.CorsBehavior(url);
  8361. if (result) {
  8362. element.crossOrigin = result;
  8363. }
  8364. }
  8365. }
  8366. };
  8367. // External files
  8368. Tools.CleanUrl = function (url) {
  8369. url = url.replace(/#/mg, "%23");
  8370. return url;
  8371. };
  8372. Tools.LoadImage = function (url, onLoad, onError, database) {
  8373. if (url instanceof ArrayBuffer) {
  8374. url = Tools.EncodeArrayBufferTobase64(url);
  8375. }
  8376. url = Tools.CleanUrl(url);
  8377. url = Tools.PreprocessUrl(url);
  8378. var img = new Image();
  8379. Tools.SetCorsBehavior(url, img);
  8380. var loadHandler = function () {
  8381. img.removeEventListener("load", loadHandler);
  8382. img.removeEventListener("error", errorHandler);
  8383. onLoad(img);
  8384. };
  8385. var errorHandler = function (err) {
  8386. img.removeEventListener("load", loadHandler);
  8387. img.removeEventListener("error", errorHandler);
  8388. Tools.Error("Error while trying to load image: " + url);
  8389. if (onError) {
  8390. onError("Error while trying to load image: " + url, err);
  8391. }
  8392. };
  8393. img.addEventListener("load", loadHandler);
  8394. img.addEventListener("error", errorHandler);
  8395. var noIndexedDB = function () {
  8396. img.src = url;
  8397. };
  8398. var loadFromIndexedDB = function () {
  8399. if (database) {
  8400. database.loadImageFromDB(url, img);
  8401. }
  8402. };
  8403. //ANY database to do!
  8404. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8405. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8406. }
  8407. else {
  8408. if (url.indexOf("file:") !== -1) {
  8409. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8410. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8411. try {
  8412. var blobURL;
  8413. try {
  8414. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8415. }
  8416. catch (ex) {
  8417. // Chrome doesn't support oneTimeOnly parameter
  8418. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8419. }
  8420. img.src = blobURL;
  8421. }
  8422. catch (e) {
  8423. img.src = "";
  8424. }
  8425. return img;
  8426. }
  8427. }
  8428. noIndexedDB();
  8429. }
  8430. return img;
  8431. };
  8432. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8433. url = Tools.CleanUrl(url);
  8434. url = Tools.PreprocessUrl(url);
  8435. // If file and file input are set
  8436. if (url.indexOf("file:") !== -1) {
  8437. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8438. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8439. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8440. }
  8441. }
  8442. var loadUrl = Tools.BaseUrl + url;
  8443. var aborted = false;
  8444. var fileRequest = {
  8445. onCompleteObservable: new BABYLON.Observable(),
  8446. abort: function () { return aborted = true; },
  8447. };
  8448. var requestFile = function () {
  8449. var request = new XMLHttpRequest();
  8450. var retryHandle = null;
  8451. fileRequest.abort = function () {
  8452. aborted = true;
  8453. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8454. request.abort();
  8455. }
  8456. if (retryHandle !== null) {
  8457. clearTimeout(retryHandle);
  8458. retryHandle = null;
  8459. }
  8460. };
  8461. var retryLoop = function (retryIndex) {
  8462. request.open('GET', loadUrl, true);
  8463. if (useArrayBuffer) {
  8464. request.responseType = "arraybuffer";
  8465. }
  8466. if (onProgress) {
  8467. request.addEventListener("progress", onProgress);
  8468. }
  8469. var onLoadEnd = function () {
  8470. request.removeEventListener("loadend", onLoadEnd);
  8471. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8472. fileRequest.onCompleteObservable.clear();
  8473. };
  8474. request.addEventListener("loadend", onLoadEnd);
  8475. var onReadyStateChange = function () {
  8476. if (aborted) {
  8477. return;
  8478. }
  8479. // In case of undefined state in some browsers.
  8480. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8481. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8482. request.removeEventListener("readystatechange", onReadyStateChange);
  8483. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8484. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8485. return;
  8486. }
  8487. var retryStrategy = Tools.DefaultRetryStrategy;
  8488. if (retryStrategy) {
  8489. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8490. if (waitTime !== -1) {
  8491. // Prevent the request from completing for retry.
  8492. request.removeEventListener("loadend", onLoadEnd);
  8493. request = new XMLHttpRequest();
  8494. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8495. return;
  8496. }
  8497. }
  8498. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8499. if (onError) {
  8500. onError(request, e);
  8501. }
  8502. else {
  8503. throw e;
  8504. }
  8505. }
  8506. };
  8507. request.addEventListener("readystatechange", onReadyStateChange);
  8508. request.send();
  8509. };
  8510. retryLoop(0);
  8511. };
  8512. // Caching all files
  8513. if (database && database.enableSceneOffline) {
  8514. var noIndexedDB_1 = function () {
  8515. if (!aborted) {
  8516. requestFile();
  8517. }
  8518. };
  8519. var loadFromIndexedDB = function () {
  8520. // TODO: database needs to support aborting and should return a IFileRequest
  8521. if (aborted) {
  8522. return;
  8523. }
  8524. if (database) {
  8525. database.loadFileFromDB(url, function (data) {
  8526. if (!aborted) {
  8527. onSuccess(data);
  8528. }
  8529. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8530. }, onProgress ? function (event) {
  8531. if (!aborted) {
  8532. onProgress(event);
  8533. }
  8534. } : undefined, noIndexedDB_1, useArrayBuffer);
  8535. }
  8536. };
  8537. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8538. }
  8539. else {
  8540. requestFile();
  8541. }
  8542. return fileRequest;
  8543. };
  8544. /**
  8545. * Load a script (identified by an url). When the url returns, the
  8546. * content of this file is added into a new script element, attached to the DOM (body element)
  8547. */
  8548. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8549. var head = document.getElementsByTagName('head')[0];
  8550. var script = document.createElement('script');
  8551. script.type = 'text/javascript';
  8552. script.src = scriptUrl;
  8553. script.onload = function () {
  8554. if (onSuccess) {
  8555. onSuccess();
  8556. }
  8557. };
  8558. script.onerror = function (e) {
  8559. if (onError) {
  8560. onError("Unable to load script", e);
  8561. }
  8562. };
  8563. head.appendChild(script);
  8564. };
  8565. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8566. var reader = new FileReader();
  8567. var request = {
  8568. onCompleteObservable: new BABYLON.Observable(),
  8569. abort: function () { return reader.abort(); },
  8570. };
  8571. reader.onloadend = function (e) {
  8572. request.onCompleteObservable.notifyObservers(request);
  8573. };
  8574. reader.onload = function (e) {
  8575. //target doesn't have result from ts 1.3
  8576. callback(e.target['result']);
  8577. };
  8578. reader.onprogress = progressCallback;
  8579. reader.readAsDataURL(fileToLoad);
  8580. return request;
  8581. };
  8582. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8583. var reader = new FileReader();
  8584. var request = {
  8585. onCompleteObservable: new BABYLON.Observable(),
  8586. abort: function () { return reader.abort(); },
  8587. };
  8588. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8589. reader.onerror = function (e) {
  8590. Tools.Log("Error while reading file: " + fileToLoad.name);
  8591. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8592. };
  8593. reader.onload = function (e) {
  8594. //target doesn't have result from ts 1.3
  8595. callback(e.target['result']);
  8596. };
  8597. if (progressCallBack) {
  8598. reader.onprogress = progressCallBack;
  8599. }
  8600. if (!useArrayBuffer) {
  8601. // Asynchronous read
  8602. reader.readAsText(fileToLoad);
  8603. }
  8604. else {
  8605. reader.readAsArrayBuffer(fileToLoad);
  8606. }
  8607. return request;
  8608. };
  8609. //returns a downloadable url to a file content.
  8610. Tools.FileAsURL = function (content) {
  8611. var fileBlob = new Blob([content]);
  8612. var url = window.URL || window.webkitURL;
  8613. var link = url.createObjectURL(fileBlob);
  8614. return link;
  8615. };
  8616. // Misc.
  8617. Tools.Format = function (value, decimals) {
  8618. if (decimals === void 0) { decimals = 2; }
  8619. return value.toFixed(decimals);
  8620. };
  8621. Tools.CheckExtends = function (v, min, max) {
  8622. if (v.x < min.x)
  8623. min.x = v.x;
  8624. if (v.y < min.y)
  8625. min.y = v.y;
  8626. if (v.z < min.z)
  8627. min.z = v.z;
  8628. if (v.x > max.x)
  8629. max.x = v.x;
  8630. if (v.y > max.y)
  8631. max.y = v.y;
  8632. if (v.z > max.z)
  8633. max.z = v.z;
  8634. };
  8635. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8636. for (var prop in source) {
  8637. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8638. continue;
  8639. }
  8640. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8641. continue;
  8642. }
  8643. var sourceValue = source[prop];
  8644. var typeOfSourceValue = typeof sourceValue;
  8645. if (typeOfSourceValue === "function") {
  8646. continue;
  8647. }
  8648. try {
  8649. if (typeOfSourceValue === "object") {
  8650. if (sourceValue instanceof Array) {
  8651. destination[prop] = [];
  8652. if (sourceValue.length > 0) {
  8653. if (typeof sourceValue[0] == "object") {
  8654. for (var index = 0; index < sourceValue.length; index++) {
  8655. var clonedValue = cloneValue(sourceValue[index], destination);
  8656. if (destination[prop].indexOf(clonedValue) === -1) {
  8657. destination[prop].push(clonedValue);
  8658. }
  8659. }
  8660. }
  8661. else {
  8662. destination[prop] = sourceValue.slice(0);
  8663. }
  8664. }
  8665. }
  8666. else {
  8667. destination[prop] = cloneValue(sourceValue, destination);
  8668. }
  8669. }
  8670. else {
  8671. destination[prop] = sourceValue;
  8672. }
  8673. }
  8674. catch (e) {
  8675. // Just ignore error (it could be because of a read-only property)
  8676. }
  8677. }
  8678. };
  8679. Tools.IsEmpty = function (obj) {
  8680. for (var i in obj) {
  8681. if (obj.hasOwnProperty(i)) {
  8682. return false;
  8683. }
  8684. }
  8685. return true;
  8686. };
  8687. Tools.RegisterTopRootEvents = function (events) {
  8688. for (var index = 0; index < events.length; index++) {
  8689. var event = events[index];
  8690. window.addEventListener(event.name, event.handler, false);
  8691. try {
  8692. if (window.parent) {
  8693. window.parent.addEventListener(event.name, event.handler, false);
  8694. }
  8695. }
  8696. catch (e) {
  8697. // Silently fails...
  8698. }
  8699. }
  8700. };
  8701. Tools.UnregisterTopRootEvents = function (events) {
  8702. for (var index = 0; index < events.length; index++) {
  8703. var event = events[index];
  8704. window.removeEventListener(event.name, event.handler);
  8705. try {
  8706. if (window.parent) {
  8707. window.parent.removeEventListener(event.name, event.handler);
  8708. }
  8709. }
  8710. catch (e) {
  8711. // Silently fails...
  8712. }
  8713. }
  8714. };
  8715. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8716. if (mimeType === void 0) { mimeType = "image/png"; }
  8717. // Read the contents of the framebuffer
  8718. var numberOfChannelsByLine = width * 4;
  8719. var halfHeight = height / 2;
  8720. //Reading datas from WebGL
  8721. var data = engine.readPixels(0, 0, width, height);
  8722. //To flip image on Y axis.
  8723. for (var i = 0; i < halfHeight; i++) {
  8724. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8725. var currentCell = j + i * numberOfChannelsByLine;
  8726. var targetLine = height - i - 1;
  8727. var targetCell = j + targetLine * numberOfChannelsByLine;
  8728. var temp = data[currentCell];
  8729. data[currentCell] = data[targetCell];
  8730. data[targetCell] = temp;
  8731. }
  8732. }
  8733. // Create a 2D canvas to store the result
  8734. if (!screenshotCanvas) {
  8735. screenshotCanvas = document.createElement('canvas');
  8736. }
  8737. screenshotCanvas.width = width;
  8738. screenshotCanvas.height = height;
  8739. var context = screenshotCanvas.getContext('2d');
  8740. if (context) {
  8741. // Copy the pixels to a 2D canvas
  8742. var imageData = context.createImageData(width, height);
  8743. var castData = (imageData.data);
  8744. castData.set(data);
  8745. context.putImageData(imageData, 0, 0);
  8746. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8747. }
  8748. };
  8749. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8750. if (mimeType === void 0) { mimeType = "image/png"; }
  8751. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8752. if (successCallback) {
  8753. successCallback(base64Image);
  8754. }
  8755. else {
  8756. // We need HTMLCanvasElement.toBlob for HD screenshots
  8757. if (!screenshotCanvas.toBlob) {
  8758. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8759. screenshotCanvas.toBlob = function (callback, type, quality) {
  8760. var _this = this;
  8761. setTimeout(function () {
  8762. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8763. for (var i = 0; i < len; i++) {
  8764. arr[i] = binStr.charCodeAt(i);
  8765. }
  8766. callback(new Blob([arr], { type: type || 'image/png' }));
  8767. });
  8768. };
  8769. }
  8770. screenshotCanvas.toBlob(function (blob) {
  8771. var url = URL.createObjectURL(blob);
  8772. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8773. if (("download" in document.createElement("a"))) {
  8774. var a = window.document.createElement("a");
  8775. a.href = url;
  8776. if (fileName) {
  8777. a.setAttribute("download", fileName);
  8778. }
  8779. else {
  8780. var date = new Date();
  8781. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8782. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8783. }
  8784. window.document.body.appendChild(a);
  8785. a.addEventListener("click", function () {
  8786. if (a.parentElement) {
  8787. a.parentElement.removeChild(a);
  8788. }
  8789. });
  8790. a.click();
  8791. }
  8792. else {
  8793. var newWindow = window.open("");
  8794. if (!newWindow)
  8795. return;
  8796. var img = newWindow.document.createElement("img");
  8797. img.onload = function () {
  8798. // no longer need to read the blob so it's revoked
  8799. URL.revokeObjectURL(url);
  8800. };
  8801. img.src = url;
  8802. newWindow.document.body.appendChild(img);
  8803. }
  8804. });
  8805. }
  8806. };
  8807. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8808. if (mimeType === void 0) { mimeType = "image/png"; }
  8809. var width;
  8810. var height;
  8811. // If a precision value is specified
  8812. if (size.precision) {
  8813. width = Math.round(engine.getRenderWidth() * size.precision);
  8814. height = Math.round(width / engine.getAspectRatio(camera));
  8815. }
  8816. else if (size.width && size.height) {
  8817. width = size.width;
  8818. height = size.height;
  8819. }
  8820. else if (size.width && !size.height) {
  8821. width = size.width;
  8822. height = Math.round(width / engine.getAspectRatio(camera));
  8823. }
  8824. else if (size.height && !size.width) {
  8825. height = size.height;
  8826. width = Math.round(height * engine.getAspectRatio(camera));
  8827. }
  8828. else if (!isNaN(size)) {
  8829. height = size;
  8830. width = size;
  8831. }
  8832. else {
  8833. Tools.Error("Invalid 'size' parameter !");
  8834. return;
  8835. }
  8836. if (!screenshotCanvas) {
  8837. screenshotCanvas = document.createElement('canvas');
  8838. }
  8839. screenshotCanvas.width = width;
  8840. screenshotCanvas.height = height;
  8841. var renderContext = screenshotCanvas.getContext("2d");
  8842. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8843. var newWidth = width;
  8844. var newHeight = newWidth / ratio;
  8845. if (newHeight > height) {
  8846. newHeight = height;
  8847. newWidth = newHeight * ratio;
  8848. }
  8849. var offsetX = Math.max(0, width - newWidth) / 2;
  8850. var offsetY = Math.max(0, height - newHeight) / 2;
  8851. var renderingCanvas = engine.getRenderingCanvas();
  8852. if (renderContext && renderingCanvas) {
  8853. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8854. }
  8855. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8856. };
  8857. /**
  8858. * Generates an image screenshot from the specified camera.
  8859. *
  8860. * @param engine The engine to use for rendering
  8861. * @param camera The camera to use for rendering
  8862. * @param size This parameter can be set to a single number or to an object with the
  8863. * following (optional) properties: precision, width, height. If a single number is passed,
  8864. * it will be used for both width and height. If an object is passed, the screenshot size
  8865. * will be derived from the parameters. The precision property is a multiplier allowing
  8866. * rendering at a higher or lower resolution.
  8867. * @param successCallback The callback receives a single parameter which contains the
  8868. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8869. * src parameter of an <img> to display it.
  8870. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8871. * Check your browser for supported MIME types.
  8872. * @param samples Texture samples (default: 1)
  8873. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8874. * @param fileName A name for for the downloaded file.
  8875. * @constructor
  8876. */
  8877. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8878. if (mimeType === void 0) { mimeType = "image/png"; }
  8879. if (samples === void 0) { samples = 1; }
  8880. if (antialiasing === void 0) { antialiasing = false; }
  8881. var width;
  8882. var height;
  8883. //If a precision value is specified
  8884. if (size.precision) {
  8885. width = Math.round(engine.getRenderWidth() * size.precision);
  8886. height = Math.round(width / engine.getAspectRatio(camera));
  8887. size = { width: width, height: height };
  8888. }
  8889. else if (size.width && size.height) {
  8890. width = size.width;
  8891. height = size.height;
  8892. }
  8893. else if (size.width && !size.height) {
  8894. width = size.width;
  8895. height = Math.round(width / engine.getAspectRatio(camera));
  8896. size = { width: width, height: height };
  8897. }
  8898. else if (size.height && !size.width) {
  8899. height = size.height;
  8900. width = Math.round(height * engine.getAspectRatio(camera));
  8901. size = { width: width, height: height };
  8902. }
  8903. else if (!isNaN(size)) {
  8904. height = size;
  8905. width = size;
  8906. }
  8907. else {
  8908. Tools.Error("Invalid 'size' parameter !");
  8909. return;
  8910. }
  8911. var scene = camera.getScene();
  8912. var previousCamera = null;
  8913. if (scene.activeCamera !== camera) {
  8914. previousCamera = scene.activeCamera;
  8915. scene.activeCamera = camera;
  8916. }
  8917. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8918. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8919. texture.renderList = null;
  8920. texture.samples = samples;
  8921. if (antialiasing) {
  8922. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8923. }
  8924. texture.onAfterRenderObservable.add(function () {
  8925. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8926. });
  8927. scene.incrementRenderId();
  8928. scene.resetCachedMaterial();
  8929. texture.render(true);
  8930. texture.dispose();
  8931. if (previousCamera) {
  8932. scene.activeCamera = previousCamera;
  8933. }
  8934. camera.getProjectionMatrix(true); // Force cache refresh;
  8935. };
  8936. // XHR response validator for local file scenario
  8937. Tools.ValidateXHRData = function (xhr, dataType) {
  8938. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8939. if (dataType === void 0) { dataType = 7; }
  8940. try {
  8941. if (dataType & 1) {
  8942. if (xhr.responseText && xhr.responseText.length > 0) {
  8943. return true;
  8944. }
  8945. else if (dataType === 1) {
  8946. return false;
  8947. }
  8948. }
  8949. if (dataType & 2) {
  8950. // Check header width and height since there is no "TGA" magic number
  8951. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8952. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8953. return true;
  8954. }
  8955. else if (dataType === 2) {
  8956. return false;
  8957. }
  8958. }
  8959. if (dataType & 4) {
  8960. // Check for the "DDS" magic number
  8961. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8962. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8963. return true;
  8964. }
  8965. else {
  8966. return false;
  8967. }
  8968. }
  8969. }
  8970. catch (e) {
  8971. // Global protection
  8972. }
  8973. return false;
  8974. };
  8975. /**
  8976. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8977. * Be aware Math.random() could cause collisions, but:
  8978. * "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"
  8979. */
  8980. Tools.RandomId = function () {
  8981. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8982. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8983. return v.toString(16);
  8984. });
  8985. };
  8986. /**
  8987. * Test if the given uri is a base64 string.
  8988. * @param uri The uri to test
  8989. * @return True if the uri is a base64 string or false otherwise.
  8990. */
  8991. Tools.IsBase64 = function (uri) {
  8992. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8993. };
  8994. /**
  8995. * Decode the given base64 uri.
  8996. * @param uri The uri to decode
  8997. * @return The decoded base64 data.
  8998. */
  8999. Tools.DecodeBase64 = function (uri) {
  9000. var decodedString = atob(uri.split(",")[1]);
  9001. var bufferLength = decodedString.length;
  9002. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9003. for (var i = 0; i < bufferLength; i++) {
  9004. bufferView[i] = decodedString.charCodeAt(i);
  9005. }
  9006. return bufferView.buffer;
  9007. };
  9008. Object.defineProperty(Tools, "NoneLogLevel", {
  9009. get: function () {
  9010. return Tools._NoneLogLevel;
  9011. },
  9012. enumerable: true,
  9013. configurable: true
  9014. });
  9015. Object.defineProperty(Tools, "MessageLogLevel", {
  9016. get: function () {
  9017. return Tools._MessageLogLevel;
  9018. },
  9019. enumerable: true,
  9020. configurable: true
  9021. });
  9022. Object.defineProperty(Tools, "WarningLogLevel", {
  9023. get: function () {
  9024. return Tools._WarningLogLevel;
  9025. },
  9026. enumerable: true,
  9027. configurable: true
  9028. });
  9029. Object.defineProperty(Tools, "ErrorLogLevel", {
  9030. get: function () {
  9031. return Tools._ErrorLogLevel;
  9032. },
  9033. enumerable: true,
  9034. configurable: true
  9035. });
  9036. Object.defineProperty(Tools, "AllLogLevel", {
  9037. get: function () {
  9038. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9039. },
  9040. enumerable: true,
  9041. configurable: true
  9042. });
  9043. Tools._AddLogEntry = function (entry) {
  9044. Tools._LogCache = entry + Tools._LogCache;
  9045. if (Tools.OnNewCacheEntry) {
  9046. Tools.OnNewCacheEntry(entry);
  9047. }
  9048. };
  9049. Tools._FormatMessage = function (message) {
  9050. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9051. var date = new Date();
  9052. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9053. };
  9054. Tools._LogDisabled = function (message) {
  9055. // nothing to do
  9056. };
  9057. Tools._LogEnabled = function (message) {
  9058. var formattedMessage = Tools._FormatMessage(message);
  9059. console.log("BJS - " + formattedMessage);
  9060. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9061. Tools._AddLogEntry(entry);
  9062. };
  9063. Tools._WarnDisabled = function (message) {
  9064. // nothing to do
  9065. };
  9066. Tools._WarnEnabled = function (message) {
  9067. var formattedMessage = Tools._FormatMessage(message);
  9068. console.warn("BJS - " + formattedMessage);
  9069. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9070. Tools._AddLogEntry(entry);
  9071. };
  9072. Tools._ErrorDisabled = function (message) {
  9073. // nothing to do
  9074. };
  9075. Tools._ErrorEnabled = function (message) {
  9076. Tools.errorsCount++;
  9077. var formattedMessage = Tools._FormatMessage(message);
  9078. console.error("BJS - " + formattedMessage);
  9079. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9080. Tools._AddLogEntry(entry);
  9081. };
  9082. Object.defineProperty(Tools, "LogCache", {
  9083. get: function () {
  9084. return Tools._LogCache;
  9085. },
  9086. enumerable: true,
  9087. configurable: true
  9088. });
  9089. Tools.ClearLogCache = function () {
  9090. Tools._LogCache = "";
  9091. Tools.errorsCount = 0;
  9092. };
  9093. Object.defineProperty(Tools, "LogLevels", {
  9094. set: function (level) {
  9095. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9096. Tools.Log = Tools._LogEnabled;
  9097. }
  9098. else {
  9099. Tools.Log = Tools._LogDisabled;
  9100. }
  9101. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9102. Tools.Warn = Tools._WarnEnabled;
  9103. }
  9104. else {
  9105. Tools.Warn = Tools._WarnDisabled;
  9106. }
  9107. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9108. Tools.Error = Tools._ErrorEnabled;
  9109. }
  9110. else {
  9111. Tools.Error = Tools._ErrorDisabled;
  9112. }
  9113. },
  9114. enumerable: true,
  9115. configurable: true
  9116. });
  9117. Tools.IsWindowObjectExist = function () {
  9118. return (typeof window) !== "undefined";
  9119. };
  9120. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9121. get: function () {
  9122. return Tools._PerformanceNoneLogLevel;
  9123. },
  9124. enumerable: true,
  9125. configurable: true
  9126. });
  9127. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9128. get: function () {
  9129. return Tools._PerformanceUserMarkLogLevel;
  9130. },
  9131. enumerable: true,
  9132. configurable: true
  9133. });
  9134. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9135. get: function () {
  9136. return Tools._PerformanceConsoleLogLevel;
  9137. },
  9138. enumerable: true,
  9139. configurable: true
  9140. });
  9141. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9142. set: function (level) {
  9143. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9144. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9145. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9146. return;
  9147. }
  9148. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9149. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9150. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9151. return;
  9152. }
  9153. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9154. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9155. },
  9156. enumerable: true,
  9157. configurable: true
  9158. });
  9159. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9160. };
  9161. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9162. };
  9163. Tools._StartUserMark = function (counterName, condition) {
  9164. if (condition === void 0) { condition = true; }
  9165. if (!Tools._performance) {
  9166. if (!Tools.IsWindowObjectExist()) {
  9167. return;
  9168. }
  9169. Tools._performance = window.performance;
  9170. }
  9171. if (!condition || !Tools._performance.mark) {
  9172. return;
  9173. }
  9174. Tools._performance.mark(counterName + "-Begin");
  9175. };
  9176. Tools._EndUserMark = function (counterName, condition) {
  9177. if (condition === void 0) { condition = true; }
  9178. if (!condition || !Tools._performance.mark) {
  9179. return;
  9180. }
  9181. Tools._performance.mark(counterName + "-End");
  9182. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9183. };
  9184. Tools._StartPerformanceConsole = function (counterName, condition) {
  9185. if (condition === void 0) { condition = true; }
  9186. if (!condition) {
  9187. return;
  9188. }
  9189. Tools._StartUserMark(counterName, condition);
  9190. if (console.time) {
  9191. console.time(counterName);
  9192. }
  9193. };
  9194. Tools._EndPerformanceConsole = function (counterName, condition) {
  9195. if (condition === void 0) { condition = true; }
  9196. if (!condition) {
  9197. return;
  9198. }
  9199. Tools._EndUserMark(counterName, condition);
  9200. if (console.time) {
  9201. console.timeEnd(counterName);
  9202. }
  9203. };
  9204. Object.defineProperty(Tools, "Now", {
  9205. get: function () {
  9206. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9207. return window.performance.now();
  9208. }
  9209. return new Date().getTime();
  9210. },
  9211. enumerable: true,
  9212. configurable: true
  9213. });
  9214. /**
  9215. * This method will return the name of the class used to create the instance of the given object.
  9216. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9217. * @param object the object to get the class name from
  9218. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9219. */
  9220. Tools.GetClassName = function (object, isType) {
  9221. if (isType === void 0) { isType = false; }
  9222. var name = null;
  9223. if (!isType && object.getClassName) {
  9224. name = object.getClassName();
  9225. }
  9226. else {
  9227. if (object instanceof Object) {
  9228. var classObj = isType ? object : Object.getPrototypeOf(object);
  9229. name = classObj.constructor["__bjsclassName__"];
  9230. }
  9231. if (!name) {
  9232. name = typeof object;
  9233. }
  9234. }
  9235. return name;
  9236. };
  9237. Tools.First = function (array, predicate) {
  9238. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9239. var el = array_1[_i];
  9240. if (predicate(el)) {
  9241. return el;
  9242. }
  9243. }
  9244. return null;
  9245. };
  9246. /**
  9247. * This method will return the name of the full name of the class, including its owning module (if any).
  9248. * 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).
  9249. * @param object the object to get the class name from
  9250. * @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.
  9251. */
  9252. Tools.getFullClassName = function (object, isType) {
  9253. if (isType === void 0) { isType = false; }
  9254. var className = null;
  9255. var moduleName = null;
  9256. if (!isType && object.getClassName) {
  9257. className = object.getClassName();
  9258. }
  9259. else {
  9260. if (object instanceof Object) {
  9261. var classObj = isType ? object : Object.getPrototypeOf(object);
  9262. className = classObj.constructor["__bjsclassName__"];
  9263. moduleName = classObj.constructor["__bjsmoduleName__"];
  9264. }
  9265. if (!className) {
  9266. className = typeof object;
  9267. }
  9268. }
  9269. if (!className) {
  9270. return null;
  9271. }
  9272. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9273. };
  9274. /**
  9275. * 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.
  9276. * @param array
  9277. */
  9278. Tools.arrayOrStringFeeder = function (array) {
  9279. return function (index) {
  9280. if (index >= array.length) {
  9281. return null;
  9282. }
  9283. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9284. if (val && val.getHashCode) {
  9285. val = val.getHashCode();
  9286. }
  9287. if (typeof val === "string") {
  9288. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9289. }
  9290. return val;
  9291. };
  9292. };
  9293. /**
  9294. * Compute the hashCode of a stream of number
  9295. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9296. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9297. * @return the hash code computed
  9298. */
  9299. Tools.hashCodeFromStream = function (feeder) {
  9300. // Based from here: http://stackoverflow.com/a/7616484/802124
  9301. var hash = 0;
  9302. var index = 0;
  9303. var chr = feeder(index++);
  9304. while (chr != null) {
  9305. hash = ((hash << 5) - hash) + chr;
  9306. hash |= 0; // Convert to 32bit integer
  9307. chr = feeder(index++);
  9308. }
  9309. return hash;
  9310. };
  9311. /**
  9312. * Returns a promise that resolves after the given amount of time.
  9313. * @param delay Number of milliseconds to delay
  9314. * @returns Promise that resolves after the given amount of time
  9315. */
  9316. Tools.DelayAsync = function (delay) {
  9317. return new Promise(function (resolve) {
  9318. setTimeout(function () {
  9319. resolve();
  9320. }, delay);
  9321. });
  9322. };
  9323. Tools.BaseUrl = "";
  9324. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9325. /**
  9326. * Default behaviour for cors in the application.
  9327. * It can be a string if the expected behavior is identical in the entire app.
  9328. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9329. */
  9330. Tools.CorsBehavior = "anonymous";
  9331. Tools.UseFallbackTexture = true;
  9332. /**
  9333. * Use this object to register external classes like custom textures or material
  9334. * to allow the laoders to instantiate them
  9335. */
  9336. Tools.RegisteredExternalClasses = {};
  9337. // Used in case of a texture loading problem
  9338. 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";
  9339. Tools.PreprocessUrl = function (url) {
  9340. return url;
  9341. };
  9342. // Logs
  9343. Tools._NoneLogLevel = 0;
  9344. Tools._MessageLogLevel = 1;
  9345. Tools._WarningLogLevel = 2;
  9346. Tools._ErrorLogLevel = 4;
  9347. Tools._LogCache = "";
  9348. Tools.errorsCount = 0;
  9349. Tools.Log = Tools._LogEnabled;
  9350. Tools.Warn = Tools._WarnEnabled;
  9351. Tools.Error = Tools._ErrorEnabled;
  9352. // Performances
  9353. Tools._PerformanceNoneLogLevel = 0;
  9354. Tools._PerformanceUserMarkLogLevel = 1;
  9355. Tools._PerformanceConsoleLogLevel = 2;
  9356. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9357. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9358. return Tools;
  9359. }());
  9360. BABYLON.Tools = Tools;
  9361. /**
  9362. * This class is used to track a performance counter which is number based.
  9363. * The user has access to many properties which give statistics of different nature
  9364. *
  9365. * The implementer can track two kinds of Performance Counter: time and count
  9366. * 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.
  9367. * 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.
  9368. */
  9369. var PerfCounter = /** @class */ (function () {
  9370. function PerfCounter() {
  9371. this._startMonitoringTime = 0;
  9372. this._min = 0;
  9373. this._max = 0;
  9374. this._average = 0;
  9375. this._lastSecAverage = 0;
  9376. this._current = 0;
  9377. this._totalValueCount = 0;
  9378. this._totalAccumulated = 0;
  9379. this._lastSecAccumulated = 0;
  9380. this._lastSecTime = 0;
  9381. this._lastSecValueCount = 0;
  9382. }
  9383. Object.defineProperty(PerfCounter.prototype, "min", {
  9384. /**
  9385. * Returns the smallest value ever
  9386. */
  9387. get: function () {
  9388. return this._min;
  9389. },
  9390. enumerable: true,
  9391. configurable: true
  9392. });
  9393. Object.defineProperty(PerfCounter.prototype, "max", {
  9394. /**
  9395. * Returns the biggest value ever
  9396. */
  9397. get: function () {
  9398. return this._max;
  9399. },
  9400. enumerable: true,
  9401. configurable: true
  9402. });
  9403. Object.defineProperty(PerfCounter.prototype, "average", {
  9404. /**
  9405. * Returns the average value since the performance counter is running
  9406. */
  9407. get: function () {
  9408. return this._average;
  9409. },
  9410. enumerable: true,
  9411. configurable: true
  9412. });
  9413. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9414. /**
  9415. * Returns the average value of the last second the counter was monitored
  9416. */
  9417. get: function () {
  9418. return this._lastSecAverage;
  9419. },
  9420. enumerable: true,
  9421. configurable: true
  9422. });
  9423. Object.defineProperty(PerfCounter.prototype, "current", {
  9424. /**
  9425. * Returns the current value
  9426. */
  9427. get: function () {
  9428. return this._current;
  9429. },
  9430. enumerable: true,
  9431. configurable: true
  9432. });
  9433. Object.defineProperty(PerfCounter.prototype, "total", {
  9434. get: function () {
  9435. return this._totalAccumulated;
  9436. },
  9437. enumerable: true,
  9438. configurable: true
  9439. });
  9440. Object.defineProperty(PerfCounter.prototype, "count", {
  9441. get: function () {
  9442. return this._totalValueCount;
  9443. },
  9444. enumerable: true,
  9445. configurable: true
  9446. });
  9447. /**
  9448. * Call this method to start monitoring a new frame.
  9449. * 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.
  9450. */
  9451. PerfCounter.prototype.fetchNewFrame = function () {
  9452. this._totalValueCount++;
  9453. this._current = 0;
  9454. this._lastSecValueCount++;
  9455. };
  9456. /**
  9457. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9458. * @param newCount the count value to add to the monitored count
  9459. * @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.
  9460. */
  9461. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9462. if (!PerfCounter.Enabled) {
  9463. return;
  9464. }
  9465. this._current += newCount;
  9466. if (fetchResult) {
  9467. this._fetchResult();
  9468. }
  9469. };
  9470. /**
  9471. * Start monitoring this performance counter
  9472. */
  9473. PerfCounter.prototype.beginMonitoring = function () {
  9474. if (!PerfCounter.Enabled) {
  9475. return;
  9476. }
  9477. this._startMonitoringTime = Tools.Now;
  9478. };
  9479. /**
  9480. * Compute the time lapsed since the previous beginMonitoring() call.
  9481. * @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
  9482. */
  9483. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9484. if (newFrame === void 0) { newFrame = true; }
  9485. if (!PerfCounter.Enabled) {
  9486. return;
  9487. }
  9488. if (newFrame) {
  9489. this.fetchNewFrame();
  9490. }
  9491. var currentTime = Tools.Now;
  9492. this._current = currentTime - this._startMonitoringTime;
  9493. if (newFrame) {
  9494. this._fetchResult();
  9495. }
  9496. };
  9497. PerfCounter.prototype._fetchResult = function () {
  9498. this._totalAccumulated += this._current;
  9499. this._lastSecAccumulated += this._current;
  9500. // Min/Max update
  9501. this._min = Math.min(this._min, this._current);
  9502. this._max = Math.max(this._max, this._current);
  9503. this._average = this._totalAccumulated / this._totalValueCount;
  9504. // Reset last sec?
  9505. var now = Tools.Now;
  9506. if ((now - this._lastSecTime) > 1000) {
  9507. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9508. this._lastSecTime = now;
  9509. this._lastSecAccumulated = 0;
  9510. this._lastSecValueCount = 0;
  9511. }
  9512. };
  9513. PerfCounter.Enabled = true;
  9514. return PerfCounter;
  9515. }());
  9516. BABYLON.PerfCounter = PerfCounter;
  9517. /**
  9518. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9519. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9520. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9521. * @param name The name of the class, case should be preserved
  9522. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9523. */
  9524. function className(name, module) {
  9525. return function (target) {
  9526. target["__bjsclassName__"] = name;
  9527. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9528. };
  9529. }
  9530. BABYLON.className = className;
  9531. /**
  9532. * An implementation of a loop for asynchronous functions.
  9533. */
  9534. var AsyncLoop = /** @class */ (function () {
  9535. /**
  9536. * Constroctor.
  9537. * @param iterations the number of iterations.
  9538. * @param _fn the function to run each iteration
  9539. * @param _successCallback the callback that will be called upon succesful execution
  9540. * @param offset starting offset.
  9541. */
  9542. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9543. if (offset === void 0) { offset = 0; }
  9544. this.iterations = iterations;
  9545. this._fn = _fn;
  9546. this._successCallback = _successCallback;
  9547. this.index = offset - 1;
  9548. this._done = false;
  9549. }
  9550. /**
  9551. * Execute the next iteration. Must be called after the last iteration was finished.
  9552. */
  9553. AsyncLoop.prototype.executeNext = function () {
  9554. if (!this._done) {
  9555. if (this.index + 1 < this.iterations) {
  9556. ++this.index;
  9557. this._fn(this);
  9558. }
  9559. else {
  9560. this.breakLoop();
  9561. }
  9562. }
  9563. };
  9564. /**
  9565. * Break the loop and run the success callback.
  9566. */
  9567. AsyncLoop.prototype.breakLoop = function () {
  9568. this._done = true;
  9569. this._successCallback();
  9570. };
  9571. /**
  9572. * Helper function
  9573. */
  9574. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9575. if (offset === void 0) { offset = 0; }
  9576. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9577. loop.executeNext();
  9578. return loop;
  9579. };
  9580. /**
  9581. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9582. * @param iterations total number of iterations
  9583. * @param syncedIterations number of synchronous iterations in each async iteration.
  9584. * @param fn the function to call each iteration.
  9585. * @param callback a success call back that will be called when iterating stops.
  9586. * @param breakFunction a break condition (optional)
  9587. * @param timeout timeout settings for the setTimeout function. default - 0.
  9588. * @constructor
  9589. */
  9590. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9591. if (timeout === void 0) { timeout = 0; }
  9592. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9593. if (breakFunction && breakFunction())
  9594. loop.breakLoop();
  9595. else {
  9596. setTimeout(function () {
  9597. for (var i = 0; i < syncedIterations; ++i) {
  9598. var iteration = (loop.index * syncedIterations) + i;
  9599. if (iteration >= iterations)
  9600. break;
  9601. fn(iteration);
  9602. if (breakFunction && breakFunction()) {
  9603. loop.breakLoop();
  9604. break;
  9605. }
  9606. }
  9607. loop.executeNext();
  9608. }, timeout);
  9609. }
  9610. }, callback);
  9611. };
  9612. return AsyncLoop;
  9613. }());
  9614. BABYLON.AsyncLoop = AsyncLoop;
  9615. })(BABYLON || (BABYLON = {}));
  9616. //# sourceMappingURL=babylon.tools.js.map
  9617. "use strict";
  9618. var BABYLON;
  9619. (function (BABYLON) {
  9620. var PromiseStates;
  9621. (function (PromiseStates) {
  9622. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9623. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9624. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9625. })(PromiseStates || (PromiseStates = {}));
  9626. var FulFillmentAgregator = /** @class */ (function () {
  9627. function FulFillmentAgregator() {
  9628. this.count = 0;
  9629. this.target = 0;
  9630. this.results = [];
  9631. }
  9632. return FulFillmentAgregator;
  9633. }());
  9634. var InternalPromise = /** @class */ (function () {
  9635. function InternalPromise(resolver) {
  9636. var _this = this;
  9637. this._state = PromiseStates.Pending;
  9638. this._children = new Array();
  9639. this._rejectWasConsumed = false;
  9640. if (!resolver) {
  9641. return;
  9642. }
  9643. try {
  9644. resolver(function (value) {
  9645. _this._resolve(value);
  9646. }, function (reason) {
  9647. _this._reject(reason);
  9648. });
  9649. }
  9650. catch (e) {
  9651. this._reject(e);
  9652. }
  9653. }
  9654. InternalPromise.prototype.catch = function (onRejected) {
  9655. return this.then(undefined, onRejected);
  9656. };
  9657. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9658. var _this = this;
  9659. var newPromise = new InternalPromise();
  9660. newPromise._onFulfilled = onFulfilled;
  9661. newPromise._onRejected = onRejected;
  9662. // Composition
  9663. this._children.push(newPromise);
  9664. if (this._state !== PromiseStates.Pending) {
  9665. BABYLON.Tools.SetImmediate(function () {
  9666. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9667. var returnedValue = newPromise._resolve(_this._result);
  9668. if (returnedValue !== undefined && returnedValue !== null) {
  9669. if (returnedValue._state !== undefined) {
  9670. var returnedPromise = returnedValue;
  9671. newPromise._children.push(returnedPromise);
  9672. newPromise = returnedPromise;
  9673. }
  9674. else {
  9675. newPromise._result = returnedValue;
  9676. }
  9677. }
  9678. }
  9679. else {
  9680. newPromise._reject(_this._reason);
  9681. }
  9682. });
  9683. }
  9684. return newPromise;
  9685. };
  9686. InternalPromise.prototype._moveChildren = function (children) {
  9687. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9688. if (this._state === PromiseStates.Fulfilled) {
  9689. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9690. var child = _b[_i];
  9691. child._resolve(this._result);
  9692. }
  9693. }
  9694. else if (this._state === PromiseStates.Rejected) {
  9695. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9696. var child = _d[_c];
  9697. child._reject(this._reason);
  9698. }
  9699. }
  9700. var _a;
  9701. };
  9702. InternalPromise.prototype._resolve = function (value) {
  9703. try {
  9704. this._state = PromiseStates.Fulfilled;
  9705. this._result = value;
  9706. var returnedValue = null;
  9707. if (this._onFulfilled) {
  9708. returnedValue = this._onFulfilled(value);
  9709. }
  9710. if (returnedValue !== undefined && returnedValue !== null) {
  9711. if (returnedValue._state !== undefined) {
  9712. // Transmit children
  9713. var returnedPromise = returnedValue;
  9714. returnedPromise._moveChildren(this._children);
  9715. }
  9716. else {
  9717. value = returnedValue;
  9718. }
  9719. }
  9720. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9721. var child = _a[_i];
  9722. child._resolve(value);
  9723. }
  9724. this._children.length = 0;
  9725. delete this._onFulfilled;
  9726. delete this._onRejected;
  9727. return returnedValue;
  9728. }
  9729. catch (e) {
  9730. this._reject(e, true);
  9731. }
  9732. return null;
  9733. };
  9734. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9735. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9736. this._state = PromiseStates.Rejected;
  9737. this._reason = reason;
  9738. if (this._onRejected && !onLocalThrow) {
  9739. try {
  9740. this._onRejected(reason);
  9741. this._rejectWasConsumed = true;
  9742. }
  9743. catch (e) {
  9744. reason = e;
  9745. }
  9746. }
  9747. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9748. var child = _a[_i];
  9749. if (this._rejectWasConsumed) {
  9750. child._resolve(null);
  9751. }
  9752. else {
  9753. child._reject(reason);
  9754. }
  9755. }
  9756. this._children.length = 0;
  9757. delete this._onFulfilled;
  9758. delete this._onRejected;
  9759. };
  9760. InternalPromise.resolve = function (value) {
  9761. var newPromise = new InternalPromise();
  9762. newPromise._resolve(value);
  9763. return newPromise;
  9764. };
  9765. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9766. promise.then(function (value) {
  9767. agregator.results[index] = value;
  9768. agregator.count++;
  9769. if (agregator.count === agregator.target) {
  9770. agregator.rootPromise._resolve(agregator.results);
  9771. }
  9772. return null;
  9773. }, function (reason) {
  9774. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9775. agregator.rootPromise._reject(reason);
  9776. }
  9777. });
  9778. };
  9779. InternalPromise.all = function (promises) {
  9780. var newPromise = new InternalPromise();
  9781. var agregator = new FulFillmentAgregator();
  9782. agregator.target = promises.length;
  9783. agregator.rootPromise = newPromise;
  9784. if (promises.length) {
  9785. for (var index = 0; index < promises.length; index++) {
  9786. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9787. }
  9788. }
  9789. else {
  9790. newPromise._resolve([]);
  9791. }
  9792. return newPromise;
  9793. };
  9794. InternalPromise.race = function (promises) {
  9795. var newPromise = new InternalPromise();
  9796. if (promises.length) {
  9797. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9798. var promise = promises_1[_i];
  9799. promise.then(function (value) {
  9800. if (newPromise) {
  9801. newPromise._resolve(value);
  9802. newPromise = null;
  9803. }
  9804. return null;
  9805. }, function (reason) {
  9806. if (newPromise) {
  9807. newPromise._reject(reason);
  9808. newPromise = null;
  9809. }
  9810. });
  9811. }
  9812. }
  9813. return newPromise;
  9814. };
  9815. return InternalPromise;
  9816. }());
  9817. /**
  9818. * Helper class that provides a small promise polyfill
  9819. */
  9820. var PromisePolyfill = /** @class */ (function () {
  9821. function PromisePolyfill() {
  9822. }
  9823. /**
  9824. * Static function used to check if the polyfill is required
  9825. * If this is the case then the function will inject the polyfill to window.Promise
  9826. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9827. */
  9828. PromisePolyfill.Apply = function (force) {
  9829. if (force === void 0) { force = false; }
  9830. if (force || typeof Promise === 'undefined') {
  9831. var root = window;
  9832. root.Promise = InternalPromise;
  9833. }
  9834. };
  9835. return PromisePolyfill;
  9836. }());
  9837. BABYLON.PromisePolyfill = PromisePolyfill;
  9838. })(BABYLON || (BABYLON = {}));
  9839. //# sourceMappingURL=babylon.promise.js.map
  9840. "use strict";
  9841. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9842. var BABYLON;
  9843. (function (BABYLON) {
  9844. /**
  9845. * Helper class to push actions to a pool of workers.
  9846. */
  9847. var WorkerPool = /** @class */ (function () {
  9848. /**
  9849. * Constructor
  9850. * @param workers Array of workers to use for actions
  9851. */
  9852. function WorkerPool(workers) {
  9853. this._pendingActions = new Array();
  9854. this._workerInfos = workers.map(function (worker) { return ({
  9855. worker: worker,
  9856. active: false
  9857. }); });
  9858. }
  9859. /**
  9860. * Terminates all workers and clears any pending actions.
  9861. */
  9862. WorkerPool.prototype.dispose = function () {
  9863. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9864. var workerInfo = _a[_i];
  9865. workerInfo.worker.terminate();
  9866. }
  9867. delete this._workerInfos;
  9868. delete this._pendingActions;
  9869. };
  9870. /**
  9871. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9872. * pended until a worker has completed its action.
  9873. * @param action The action to perform. Call onComplete when the action is complete.
  9874. */
  9875. WorkerPool.prototype.push = function (action) {
  9876. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9877. var workerInfo = _a[_i];
  9878. if (!workerInfo.active) {
  9879. this._execute(workerInfo, action);
  9880. return;
  9881. }
  9882. }
  9883. this._pendingActions.push(action);
  9884. };
  9885. WorkerPool.prototype._execute = function (workerInfo, action) {
  9886. var _this = this;
  9887. workerInfo.active = true;
  9888. action(workerInfo.worker, function () {
  9889. workerInfo.active = false;
  9890. var nextAction = _this._pendingActions.shift();
  9891. if (nextAction) {
  9892. _this._execute(workerInfo, nextAction);
  9893. }
  9894. });
  9895. };
  9896. return WorkerPool;
  9897. }());
  9898. BABYLON.WorkerPool = WorkerPool;
  9899. })(BABYLON || (BABYLON = {}));
  9900. //# sourceMappingURL=babylon.workerPool.js.map
  9901. "use strict";
  9902. var BABYLON;
  9903. (function (BABYLON) {
  9904. var _AlphaState = /** @class */ (function () {
  9905. /**
  9906. * Initializes the state.
  9907. */
  9908. function _AlphaState() {
  9909. this._isAlphaBlendDirty = false;
  9910. this._isBlendFunctionParametersDirty = false;
  9911. this._isBlendEquationParametersDirty = false;
  9912. this._isBlendConstantsDirty = false;
  9913. this._alphaBlend = false;
  9914. this._blendFunctionParameters = new Array(4);
  9915. this._blendEquationParameters = new Array(2);
  9916. this._blendConstants = new Array(4);
  9917. this.reset();
  9918. }
  9919. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9920. get: function () {
  9921. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9927. get: function () {
  9928. return this._alphaBlend;
  9929. },
  9930. set: function (value) {
  9931. if (this._alphaBlend === value) {
  9932. return;
  9933. }
  9934. this._alphaBlend = value;
  9935. this._isAlphaBlendDirty = true;
  9936. },
  9937. enumerable: true,
  9938. configurable: true
  9939. });
  9940. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9941. if (this._blendConstants[0] === r &&
  9942. this._blendConstants[1] === g &&
  9943. this._blendConstants[2] === b &&
  9944. this._blendConstants[3] === a) {
  9945. return;
  9946. }
  9947. this._blendConstants[0] = r;
  9948. this._blendConstants[1] = g;
  9949. this._blendConstants[2] = b;
  9950. this._blendConstants[3] = a;
  9951. this._isBlendConstantsDirty = true;
  9952. };
  9953. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9954. if (this._blendFunctionParameters[0] === value0 &&
  9955. this._blendFunctionParameters[1] === value1 &&
  9956. this._blendFunctionParameters[2] === value2 &&
  9957. this._blendFunctionParameters[3] === value3) {
  9958. return;
  9959. }
  9960. this._blendFunctionParameters[0] = value0;
  9961. this._blendFunctionParameters[1] = value1;
  9962. this._blendFunctionParameters[2] = value2;
  9963. this._blendFunctionParameters[3] = value3;
  9964. this._isBlendFunctionParametersDirty = true;
  9965. };
  9966. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9967. if (this._blendEquationParameters[0] === rgb &&
  9968. this._blendEquationParameters[1] === alpha) {
  9969. return;
  9970. }
  9971. this._blendEquationParameters[0] = rgb;
  9972. this._blendEquationParameters[1] = alpha;
  9973. this._isBlendEquationParametersDirty = true;
  9974. };
  9975. _AlphaState.prototype.reset = function () {
  9976. this._alphaBlend = false;
  9977. this._blendFunctionParameters[0] = null;
  9978. this._blendFunctionParameters[1] = null;
  9979. this._blendFunctionParameters[2] = null;
  9980. this._blendFunctionParameters[3] = null;
  9981. this._blendEquationParameters[0] = null;
  9982. this._blendEquationParameters[1] = null;
  9983. this._blendConstants[0] = null;
  9984. this._blendConstants[1] = null;
  9985. this._blendConstants[2] = null;
  9986. this._blendConstants[3] = null;
  9987. this._isAlphaBlendDirty = true;
  9988. this._isBlendFunctionParametersDirty = false;
  9989. this._isBlendEquationParametersDirty = false;
  9990. this._isBlendConstantsDirty = false;
  9991. };
  9992. _AlphaState.prototype.apply = function (gl) {
  9993. if (!this.isDirty) {
  9994. return;
  9995. }
  9996. // Alpha blend
  9997. if (this._isAlphaBlendDirty) {
  9998. if (this._alphaBlend) {
  9999. gl.enable(gl.BLEND);
  10000. }
  10001. else {
  10002. gl.disable(gl.BLEND);
  10003. }
  10004. this._isAlphaBlendDirty = false;
  10005. }
  10006. // Alpha function
  10007. if (this._isBlendFunctionParametersDirty) {
  10008. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10009. this._isBlendFunctionParametersDirty = false;
  10010. }
  10011. // Alpha equation
  10012. if (this._isBlendEquationParametersDirty) {
  10013. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10014. this._isBlendEquationParametersDirty = false;
  10015. }
  10016. // Constants
  10017. if (this._isBlendConstantsDirty) {
  10018. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10019. this._isBlendConstantsDirty = false;
  10020. }
  10021. };
  10022. return _AlphaState;
  10023. }());
  10024. BABYLON._AlphaState = _AlphaState;
  10025. })(BABYLON || (BABYLON = {}));
  10026. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10027. "use strict";
  10028. var BABYLON;
  10029. (function (BABYLON) {
  10030. var _DepthCullingState = /** @class */ (function () {
  10031. /**
  10032. * Initializes the state.
  10033. */
  10034. function _DepthCullingState() {
  10035. this._isDepthTestDirty = false;
  10036. this._isDepthMaskDirty = false;
  10037. this._isDepthFuncDirty = false;
  10038. this._isCullFaceDirty = false;
  10039. this._isCullDirty = false;
  10040. this._isZOffsetDirty = false;
  10041. this._isFrontFaceDirty = false;
  10042. this.reset();
  10043. }
  10044. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10045. get: function () {
  10046. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10047. },
  10048. enumerable: true,
  10049. configurable: true
  10050. });
  10051. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10052. get: function () {
  10053. return this._zOffset;
  10054. },
  10055. set: function (value) {
  10056. if (this._zOffset === value) {
  10057. return;
  10058. }
  10059. this._zOffset = value;
  10060. this._isZOffsetDirty = true;
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10066. get: function () {
  10067. return this._cullFace;
  10068. },
  10069. set: function (value) {
  10070. if (this._cullFace === value) {
  10071. return;
  10072. }
  10073. this._cullFace = value;
  10074. this._isCullFaceDirty = true;
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10080. get: function () {
  10081. return this._cull;
  10082. },
  10083. set: function (value) {
  10084. if (this._cull === value) {
  10085. return;
  10086. }
  10087. this._cull = value;
  10088. this._isCullDirty = true;
  10089. },
  10090. enumerable: true,
  10091. configurable: true
  10092. });
  10093. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10094. get: function () {
  10095. return this._depthFunc;
  10096. },
  10097. set: function (value) {
  10098. if (this._depthFunc === value) {
  10099. return;
  10100. }
  10101. this._depthFunc = value;
  10102. this._isDepthFuncDirty = true;
  10103. },
  10104. enumerable: true,
  10105. configurable: true
  10106. });
  10107. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10108. get: function () {
  10109. return this._depthMask;
  10110. },
  10111. set: function (value) {
  10112. if (this._depthMask === value) {
  10113. return;
  10114. }
  10115. this._depthMask = value;
  10116. this._isDepthMaskDirty = true;
  10117. },
  10118. enumerable: true,
  10119. configurable: true
  10120. });
  10121. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10122. get: function () {
  10123. return this._depthTest;
  10124. },
  10125. set: function (value) {
  10126. if (this._depthTest === value) {
  10127. return;
  10128. }
  10129. this._depthTest = value;
  10130. this._isDepthTestDirty = true;
  10131. },
  10132. enumerable: true,
  10133. configurable: true
  10134. });
  10135. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10136. get: function () {
  10137. return this._frontFace;
  10138. },
  10139. set: function (value) {
  10140. if (this._frontFace === value) {
  10141. return;
  10142. }
  10143. this._frontFace = value;
  10144. this._isFrontFaceDirty = true;
  10145. },
  10146. enumerable: true,
  10147. configurable: true
  10148. });
  10149. _DepthCullingState.prototype.reset = function () {
  10150. this._depthMask = true;
  10151. this._depthTest = true;
  10152. this._depthFunc = null;
  10153. this._cullFace = null;
  10154. this._cull = null;
  10155. this._zOffset = 0;
  10156. this._frontFace = null;
  10157. this._isDepthTestDirty = true;
  10158. this._isDepthMaskDirty = true;
  10159. this._isDepthFuncDirty = false;
  10160. this._isCullFaceDirty = false;
  10161. this._isCullDirty = false;
  10162. this._isZOffsetDirty = false;
  10163. this._isFrontFaceDirty = false;
  10164. };
  10165. _DepthCullingState.prototype.apply = function (gl) {
  10166. if (!this.isDirty) {
  10167. return;
  10168. }
  10169. // Cull
  10170. if (this._isCullDirty) {
  10171. if (this.cull) {
  10172. gl.enable(gl.CULL_FACE);
  10173. }
  10174. else {
  10175. gl.disable(gl.CULL_FACE);
  10176. }
  10177. this._isCullDirty = false;
  10178. }
  10179. // Cull face
  10180. if (this._isCullFaceDirty) {
  10181. gl.cullFace(this.cullFace);
  10182. this._isCullFaceDirty = false;
  10183. }
  10184. // Depth mask
  10185. if (this._isDepthMaskDirty) {
  10186. gl.depthMask(this.depthMask);
  10187. this._isDepthMaskDirty = false;
  10188. }
  10189. // Depth test
  10190. if (this._isDepthTestDirty) {
  10191. if (this.depthTest) {
  10192. gl.enable(gl.DEPTH_TEST);
  10193. }
  10194. else {
  10195. gl.disable(gl.DEPTH_TEST);
  10196. }
  10197. this._isDepthTestDirty = false;
  10198. }
  10199. // Depth func
  10200. if (this._isDepthFuncDirty) {
  10201. gl.depthFunc(this.depthFunc);
  10202. this._isDepthFuncDirty = false;
  10203. }
  10204. // zOffset
  10205. if (this._isZOffsetDirty) {
  10206. if (this.zOffset) {
  10207. gl.enable(gl.POLYGON_OFFSET_FILL);
  10208. gl.polygonOffset(this.zOffset, 0);
  10209. }
  10210. else {
  10211. gl.disable(gl.POLYGON_OFFSET_FILL);
  10212. }
  10213. this._isZOffsetDirty = false;
  10214. }
  10215. // Front face
  10216. if (this._isFrontFaceDirty) {
  10217. gl.frontFace(this.frontFace);
  10218. this._isFrontFaceDirty = false;
  10219. }
  10220. };
  10221. return _DepthCullingState;
  10222. }());
  10223. BABYLON._DepthCullingState = _DepthCullingState;
  10224. })(BABYLON || (BABYLON = {}));
  10225. //# sourceMappingURL=babylon.depthCullingState.js.map
  10226. "use strict";
  10227. var BABYLON;
  10228. (function (BABYLON) {
  10229. var _StencilState = /** @class */ (function () {
  10230. function _StencilState() {
  10231. this._isStencilTestDirty = false;
  10232. this._isStencilMaskDirty = false;
  10233. this._isStencilFuncDirty = false;
  10234. this._isStencilOpDirty = false;
  10235. this.reset();
  10236. }
  10237. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10238. get: function () {
  10239. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10240. },
  10241. enumerable: true,
  10242. configurable: true
  10243. });
  10244. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10245. get: function () {
  10246. return this._stencilFunc;
  10247. },
  10248. set: function (value) {
  10249. if (this._stencilFunc === value) {
  10250. return;
  10251. }
  10252. this._stencilFunc = value;
  10253. this._isStencilFuncDirty = true;
  10254. },
  10255. enumerable: true,
  10256. configurable: true
  10257. });
  10258. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10259. get: function () {
  10260. return this._stencilFuncRef;
  10261. },
  10262. set: function (value) {
  10263. if (this._stencilFuncRef === value) {
  10264. return;
  10265. }
  10266. this._stencilFuncRef = value;
  10267. this._isStencilFuncDirty = true;
  10268. },
  10269. enumerable: true,
  10270. configurable: true
  10271. });
  10272. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10273. get: function () {
  10274. return this._stencilFuncMask;
  10275. },
  10276. set: function (value) {
  10277. if (this._stencilFuncMask === value) {
  10278. return;
  10279. }
  10280. this._stencilFuncMask = value;
  10281. this._isStencilFuncDirty = true;
  10282. },
  10283. enumerable: true,
  10284. configurable: true
  10285. });
  10286. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10287. get: function () {
  10288. return this._stencilOpStencilFail;
  10289. },
  10290. set: function (value) {
  10291. if (this._stencilOpStencilFail === value) {
  10292. return;
  10293. }
  10294. this._stencilOpStencilFail = value;
  10295. this._isStencilOpDirty = true;
  10296. },
  10297. enumerable: true,
  10298. configurable: true
  10299. });
  10300. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10301. get: function () {
  10302. return this._stencilOpDepthFail;
  10303. },
  10304. set: function (value) {
  10305. if (this._stencilOpDepthFail === value) {
  10306. return;
  10307. }
  10308. this._stencilOpDepthFail = value;
  10309. this._isStencilOpDirty = true;
  10310. },
  10311. enumerable: true,
  10312. configurable: true
  10313. });
  10314. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10315. get: function () {
  10316. return this._stencilOpStencilDepthPass;
  10317. },
  10318. set: function (value) {
  10319. if (this._stencilOpStencilDepthPass === value) {
  10320. return;
  10321. }
  10322. this._stencilOpStencilDepthPass = value;
  10323. this._isStencilOpDirty = true;
  10324. },
  10325. enumerable: true,
  10326. configurable: true
  10327. });
  10328. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10329. get: function () {
  10330. return this._stencilMask;
  10331. },
  10332. set: function (value) {
  10333. if (this._stencilMask === value) {
  10334. return;
  10335. }
  10336. this._stencilMask = value;
  10337. this._isStencilMaskDirty = true;
  10338. },
  10339. enumerable: true,
  10340. configurable: true
  10341. });
  10342. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10343. get: function () {
  10344. return this._stencilTest;
  10345. },
  10346. set: function (value) {
  10347. if (this._stencilTest === value) {
  10348. return;
  10349. }
  10350. this._stencilTest = value;
  10351. this._isStencilTestDirty = true;
  10352. },
  10353. enumerable: true,
  10354. configurable: true
  10355. });
  10356. _StencilState.prototype.reset = function () {
  10357. this._stencilTest = false;
  10358. this._stencilMask = 0xFF;
  10359. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10360. this._stencilFuncRef = 1;
  10361. this._stencilFuncMask = 0xFF;
  10362. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10363. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10364. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10365. this._isStencilTestDirty = true;
  10366. this._isStencilMaskDirty = true;
  10367. this._isStencilFuncDirty = true;
  10368. this._isStencilOpDirty = true;
  10369. };
  10370. _StencilState.prototype.apply = function (gl) {
  10371. if (!this.isDirty) {
  10372. return;
  10373. }
  10374. // Stencil test
  10375. if (this._isStencilTestDirty) {
  10376. if (this.stencilTest) {
  10377. gl.enable(gl.STENCIL_TEST);
  10378. }
  10379. else {
  10380. gl.disable(gl.STENCIL_TEST);
  10381. }
  10382. this._isStencilTestDirty = false;
  10383. }
  10384. // Stencil mask
  10385. if (this._isStencilMaskDirty) {
  10386. gl.stencilMask(this.stencilMask);
  10387. this._isStencilMaskDirty = false;
  10388. }
  10389. // Stencil func
  10390. if (this._isStencilFuncDirty) {
  10391. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10392. this._isStencilFuncDirty = false;
  10393. }
  10394. // Stencil op
  10395. if (this._isStencilOpDirty) {
  10396. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10397. this._isStencilOpDirty = false;
  10398. }
  10399. };
  10400. return _StencilState;
  10401. }());
  10402. BABYLON._StencilState = _StencilState;
  10403. })(BABYLON || (BABYLON = {}));
  10404. //# sourceMappingURL=babylon.stencilState.js.map
  10405. "use strict";
  10406. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10407. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10408. s = arguments[i];
  10409. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10410. t[p] = s[p];
  10411. }
  10412. return t;
  10413. };
  10414. var BABYLON;
  10415. (function (BABYLON) {
  10416. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10417. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10418. };
  10419. var compileRawShader = function (gl, source, type) {
  10420. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10421. gl.shaderSource(shader, source);
  10422. gl.compileShader(shader);
  10423. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10424. var log = gl.getShaderInfoLog(shader);
  10425. if (log) {
  10426. throw new Error(log);
  10427. }
  10428. }
  10429. if (!shader) {
  10430. throw new Error("Something went wrong while compile the shader.");
  10431. }
  10432. return shader;
  10433. };
  10434. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10435. var magFilter = gl.NEAREST;
  10436. var minFilter = gl.NEAREST;
  10437. switch (samplingMode) {
  10438. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10439. magFilter = gl.LINEAR;
  10440. if (generateMipMaps) {
  10441. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10442. }
  10443. else {
  10444. minFilter = gl.LINEAR;
  10445. }
  10446. break;
  10447. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10448. magFilter = gl.LINEAR;
  10449. if (generateMipMaps) {
  10450. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10451. }
  10452. else {
  10453. minFilter = gl.LINEAR;
  10454. }
  10455. break;
  10456. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10457. magFilter = gl.NEAREST;
  10458. if (generateMipMaps) {
  10459. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10460. }
  10461. else {
  10462. minFilter = gl.NEAREST;
  10463. }
  10464. break;
  10465. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10466. magFilter = gl.NEAREST;
  10467. if (generateMipMaps) {
  10468. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10469. }
  10470. else {
  10471. minFilter = gl.NEAREST;
  10472. }
  10473. break;
  10474. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10475. magFilter = gl.NEAREST;
  10476. if (generateMipMaps) {
  10477. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10478. }
  10479. else {
  10480. minFilter = gl.LINEAR;
  10481. }
  10482. break;
  10483. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10484. magFilter = gl.NEAREST;
  10485. if (generateMipMaps) {
  10486. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10487. }
  10488. else {
  10489. minFilter = gl.LINEAR;
  10490. }
  10491. break;
  10492. case BABYLON.Texture.NEAREST_LINEAR:
  10493. magFilter = gl.NEAREST;
  10494. minFilter = gl.LINEAR;
  10495. break;
  10496. case BABYLON.Texture.NEAREST_NEAREST:
  10497. magFilter = gl.NEAREST;
  10498. minFilter = gl.NEAREST;
  10499. break;
  10500. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10501. magFilter = gl.LINEAR;
  10502. if (generateMipMaps) {
  10503. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10504. }
  10505. else {
  10506. minFilter = gl.NEAREST;
  10507. }
  10508. break;
  10509. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10510. magFilter = gl.LINEAR;
  10511. if (generateMipMaps) {
  10512. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10513. }
  10514. else {
  10515. minFilter = gl.NEAREST;
  10516. }
  10517. break;
  10518. case BABYLON.Texture.LINEAR_LINEAR:
  10519. magFilter = gl.LINEAR;
  10520. minFilter = gl.LINEAR;
  10521. break;
  10522. case BABYLON.Texture.LINEAR_NEAREST:
  10523. magFilter = gl.LINEAR;
  10524. minFilter = gl.NEAREST;
  10525. break;
  10526. }
  10527. return {
  10528. min: minFilter,
  10529. mag: magFilter
  10530. };
  10531. };
  10532. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10533. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10534. var img;
  10535. var onload = function () {
  10536. loadedImages[index] = img;
  10537. loadedImages._internalCount++;
  10538. if (scene) {
  10539. scene._removePendingData(img);
  10540. }
  10541. if (loadedImages._internalCount === 6) {
  10542. onfinish(loadedImages);
  10543. }
  10544. };
  10545. var onerror = function (message, exception) {
  10546. if (scene) {
  10547. scene._removePendingData(img);
  10548. }
  10549. if (onErrorCallBack) {
  10550. onErrorCallBack(message, exception);
  10551. }
  10552. };
  10553. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10554. if (scene) {
  10555. scene._addPendingData(img);
  10556. }
  10557. };
  10558. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10559. if (onError === void 0) { onError = null; }
  10560. var loadedImages = [];
  10561. loadedImages._internalCount = 0;
  10562. for (var index = 0; index < 6; index++) {
  10563. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10564. }
  10565. };
  10566. var BufferPointer = /** @class */ (function () {
  10567. function BufferPointer() {
  10568. }
  10569. return BufferPointer;
  10570. }());
  10571. var InstancingAttributeInfo = /** @class */ (function () {
  10572. function InstancingAttributeInfo() {
  10573. }
  10574. return InstancingAttributeInfo;
  10575. }());
  10576. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10577. /**
  10578. * Define options used to create a render target texture
  10579. */
  10580. var RenderTargetCreationOptions = /** @class */ (function () {
  10581. function RenderTargetCreationOptions() {
  10582. }
  10583. return RenderTargetCreationOptions;
  10584. }());
  10585. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10586. /**
  10587. * Define options used to create a depth texture
  10588. */
  10589. var DepthTextureCreationOptions = /** @class */ (function () {
  10590. function DepthTextureCreationOptions() {
  10591. }
  10592. return DepthTextureCreationOptions;
  10593. }());
  10594. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10595. /**
  10596. * Regroup several parameters relative to the browser in use
  10597. */
  10598. var EngineCapabilities = /** @class */ (function () {
  10599. function EngineCapabilities() {
  10600. }
  10601. return EngineCapabilities;
  10602. }());
  10603. BABYLON.EngineCapabilities = EngineCapabilities;
  10604. /**
  10605. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10606. */
  10607. var Engine = /** @class */ (function () {
  10608. /**
  10609. * @constructor
  10610. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10611. * @param antialias defines enable antialiasing (default: false)
  10612. * @param options defines further options to be sent to the getContext() function
  10613. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10614. */
  10615. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10616. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10617. var _this = this;
  10618. // Public members
  10619. this.forcePOTTextures = false;
  10620. this.isFullscreen = false;
  10621. this.isPointerLock = false;
  10622. this.cullBackFaces = true;
  10623. this.renderEvenInBackground = true;
  10624. this.preventCacheWipeBetweenFrames = false;
  10625. // To enable/disable IDB support and avoid XHR on .manifest
  10626. this.enableOfflineSupport = false;
  10627. this.scenes = new Array();
  10628. this.postProcesses = new Array();
  10629. // Observables
  10630. /**
  10631. * Observable event triggered each time the rendering canvas is resized
  10632. */
  10633. this.onResizeObservable = new BABYLON.Observable();
  10634. /**
  10635. * Observable event triggered each time the canvas loses focus
  10636. */
  10637. this.onCanvasBlurObservable = new BABYLON.Observable();
  10638. /**
  10639. * Observable event triggered each time the canvas gains focus
  10640. */
  10641. this.onCanvasFocusObservable = new BABYLON.Observable();
  10642. /**
  10643. * Observable event triggered each time the canvas receives pointerout event
  10644. */
  10645. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10646. /**
  10647. * Observable event triggered before each texture is initialized
  10648. */
  10649. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10650. //WebVR
  10651. this._vrDisplay = undefined;
  10652. this._vrSupported = false;
  10653. this._vrExclusivePointerMode = false;
  10654. // Uniform buffers list
  10655. this.disableUniformBuffers = false;
  10656. this._uniformBuffers = new Array();
  10657. // Observables
  10658. /**
  10659. * Observable raised when the engine begins a new frame
  10660. */
  10661. this.onBeginFrameObservable = new BABYLON.Observable();
  10662. /**
  10663. * Observable raised when the engine ends the current frame
  10664. */
  10665. this.onEndFrameObservable = new BABYLON.Observable();
  10666. /**
  10667. * Observable raised when the engine is about to compile a shader
  10668. */
  10669. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10670. /**
  10671. * Observable raised when the engine has jsut compiled a shader
  10672. */
  10673. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10674. this._windowIsBackground = false;
  10675. this._webGLVersion = 1.0;
  10676. this._badOS = false;
  10677. this._badDesktopOS = false;
  10678. /**
  10679. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10680. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10681. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10682. */
  10683. this.disableTextureBindingOptimization = false;
  10684. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10685. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10686. this.onVRRequestPresentStart = new BABYLON.Observable();
  10687. this._colorWrite = true;
  10688. this._drawCalls = new BABYLON.PerfCounter();
  10689. this._textureCollisions = new BABYLON.PerfCounter();
  10690. this._renderingQueueLaunched = false;
  10691. this._activeRenderLoops = new Array();
  10692. // Deterministic lockstepMaxSteps
  10693. this._deterministicLockstep = false;
  10694. this._lockstepMaxSteps = 4;
  10695. // Lost context
  10696. this.onContextLostObservable = new BABYLON.Observable();
  10697. this.onContextRestoredObservable = new BABYLON.Observable();
  10698. this._contextWasLost = false;
  10699. this._doNotHandleContextLost = false;
  10700. // FPS
  10701. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10702. this._fps = 60;
  10703. this._deltaTime = 0;
  10704. /**
  10705. * Turn this value on if you want to pause FPS computation when in background
  10706. */
  10707. this.disablePerformanceMonitorInBackground = false;
  10708. // States
  10709. this._depthCullingState = new BABYLON._DepthCullingState();
  10710. this._stencilState = new BABYLON._StencilState();
  10711. this._alphaState = new BABYLON._AlphaState();
  10712. this._alphaMode = Engine.ALPHA_DISABLE;
  10713. // Cache
  10714. this._internalTexturesCache = new Array();
  10715. this._activeChannel = 0;
  10716. this._currentTextureChannel = -1;
  10717. this._boundTexturesCache = {};
  10718. this._compiledEffects = {};
  10719. this._vertexAttribArraysEnabled = [];
  10720. this._uintIndicesCurrentlySet = false;
  10721. this._currentBoundBuffer = new Array();
  10722. this._currentBufferPointers = new Array();
  10723. this._currentInstanceLocations = new Array();
  10724. this._currentInstanceBuffers = new Array();
  10725. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10726. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10727. this._vaoRecordInProgress = false;
  10728. this._mustWipeVertexAttributes = false;
  10729. this._nextFreeTextureSlots = new Array();
  10730. this._maxSimultaneousTextures = 0;
  10731. this._activeRequests = new Array();
  10732. // Hardware supported Compressed Textures
  10733. this._texturesSupported = new Array();
  10734. this._onVRFullScreenTriggered = function () {
  10735. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10736. //get the old size before we change
  10737. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10738. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10739. //get the width and height, change the render size
  10740. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10741. _this.setHardwareScalingLevel(1);
  10742. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10743. }
  10744. else {
  10745. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10746. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10747. }
  10748. };
  10749. this._boundUniforms = {};
  10750. // Register promises
  10751. BABYLON.PromisePolyfill.Apply();
  10752. var canvas = null;
  10753. Engine.Instances.push(this);
  10754. if (!canvasOrContext) {
  10755. return;
  10756. }
  10757. options = options || {};
  10758. if (canvasOrContext.getContext) {
  10759. canvas = canvasOrContext;
  10760. this._renderingCanvas = canvas;
  10761. if (antialias != null) {
  10762. options.antialias = antialias;
  10763. }
  10764. if (options.deterministicLockstep === undefined) {
  10765. options.deterministicLockstep = false;
  10766. }
  10767. if (options.lockstepMaxSteps === undefined) {
  10768. options.lockstepMaxSteps = 4;
  10769. }
  10770. if (options.preserveDrawingBuffer === undefined) {
  10771. options.preserveDrawingBuffer = false;
  10772. }
  10773. if (options.audioEngine === undefined) {
  10774. options.audioEngine = true;
  10775. }
  10776. if (options.stencil === undefined) {
  10777. options.stencil = true;
  10778. }
  10779. this._deterministicLockstep = options.deterministicLockstep;
  10780. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10781. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10782. // Exceptions
  10783. if (navigator && navigator.userAgent) {
  10784. var ua = navigator.userAgent;
  10785. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10786. var exception = _a[_i];
  10787. var key = exception.key;
  10788. var targets = exception.targets;
  10789. if (ua.indexOf(key) > -1) {
  10790. if (exception.capture && exception.captureConstraint) {
  10791. var capture = exception.capture;
  10792. var constraint = exception.captureConstraint;
  10793. var regex = new RegExp(capture);
  10794. var matches = regex.exec(ua);
  10795. if (matches && matches.length > 0) {
  10796. var capturedValue = parseInt(matches[matches.length - 1]);
  10797. if (capturedValue >= constraint) {
  10798. continue;
  10799. }
  10800. }
  10801. }
  10802. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10803. var target = targets_1[_b];
  10804. switch (target) {
  10805. case "uniformBuffer":
  10806. this.disableUniformBuffers = true;
  10807. break;
  10808. case "textureBindingOptimization":
  10809. this.disableTextureBindingOptimization = true;
  10810. break;
  10811. }
  10812. }
  10813. }
  10814. }
  10815. }
  10816. // GL
  10817. if (!options.disableWebGL2Support) {
  10818. try {
  10819. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10820. if (this._gl) {
  10821. this._webGLVersion = 2.0;
  10822. }
  10823. }
  10824. catch (e) {
  10825. // Do nothing
  10826. }
  10827. }
  10828. if (!this._gl) {
  10829. if (!canvas) {
  10830. throw new Error("The provided canvas is null or undefined.");
  10831. }
  10832. try {
  10833. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10834. }
  10835. catch (e) {
  10836. throw new Error("WebGL not supported");
  10837. }
  10838. }
  10839. if (!this._gl) {
  10840. throw new Error("WebGL not supported");
  10841. }
  10842. this._onCanvasFocus = function () {
  10843. _this.onCanvasFocusObservable.notifyObservers(_this);
  10844. };
  10845. this._onCanvasBlur = function () {
  10846. _this.onCanvasBlurObservable.notifyObservers(_this);
  10847. };
  10848. canvas.addEventListener("focus", this._onCanvasFocus);
  10849. canvas.addEventListener("blur", this._onCanvasBlur);
  10850. this._onBlur = function () {
  10851. if (_this.disablePerformanceMonitorInBackground) {
  10852. _this._performanceMonitor.disable();
  10853. }
  10854. _this._windowIsBackground = true;
  10855. };
  10856. this._onFocus = function () {
  10857. if (_this.disablePerformanceMonitorInBackground) {
  10858. _this._performanceMonitor.enable();
  10859. }
  10860. _this._windowIsBackground = false;
  10861. };
  10862. this._onCanvasPointerOut = function (ev) {
  10863. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10864. };
  10865. window.addEventListener("blur", this._onBlur);
  10866. window.addEventListener("focus", this._onFocus);
  10867. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10868. // Context lost
  10869. if (!this._doNotHandleContextLost) {
  10870. this._onContextLost = function (evt) {
  10871. evt.preventDefault();
  10872. _this._contextWasLost = true;
  10873. BABYLON.Tools.Warn("WebGL context lost.");
  10874. _this.onContextLostObservable.notifyObservers(_this);
  10875. };
  10876. this._onContextRestored = function (evt) {
  10877. // Adding a timeout to avoid race condition at browser level
  10878. setTimeout(function () {
  10879. // Rebuild gl context
  10880. _this._initGLContext();
  10881. // Rebuild effects
  10882. _this._rebuildEffects();
  10883. // Rebuild textures
  10884. _this._rebuildInternalTextures();
  10885. // Rebuild buffers
  10886. _this._rebuildBuffers();
  10887. // Cache
  10888. _this.wipeCaches(true);
  10889. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10890. _this.onContextRestoredObservable.notifyObservers(_this);
  10891. _this._contextWasLost = false;
  10892. }, 0);
  10893. };
  10894. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10895. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10896. }
  10897. }
  10898. else {
  10899. this._gl = canvasOrContext;
  10900. this._renderingCanvas = this._gl.canvas;
  10901. if (this._gl.renderbufferStorageMultisample) {
  10902. this._webGLVersion = 2.0;
  10903. }
  10904. options.stencil = this._gl.getContextAttributes().stencil;
  10905. }
  10906. // Viewport
  10907. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10908. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10909. this.resize();
  10910. this._isStencilEnable = options.stencil ? true : false;
  10911. this._initGLContext();
  10912. if (canvas) {
  10913. // Fullscreen
  10914. this._onFullscreenChange = function () {
  10915. if (document.fullscreen !== undefined) {
  10916. _this.isFullscreen = document.fullscreen;
  10917. }
  10918. else if (document.mozFullScreen !== undefined) {
  10919. _this.isFullscreen = document.mozFullScreen;
  10920. }
  10921. else if (document.webkitIsFullScreen !== undefined) {
  10922. _this.isFullscreen = document.webkitIsFullScreen;
  10923. }
  10924. else if (document.msIsFullScreen !== undefined) {
  10925. _this.isFullscreen = document.msIsFullScreen;
  10926. }
  10927. // Pointer lock
  10928. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10929. canvas.requestPointerLock = canvas.requestPointerLock ||
  10930. canvas.msRequestPointerLock ||
  10931. canvas.mozRequestPointerLock ||
  10932. canvas.webkitRequestPointerLock;
  10933. if (canvas.requestPointerLock) {
  10934. canvas.requestPointerLock();
  10935. }
  10936. }
  10937. };
  10938. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10939. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10940. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10941. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10942. // Pointer lock
  10943. this._onPointerLockChange = function () {
  10944. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10945. document.webkitPointerLockElement === canvas ||
  10946. document.msPointerLockElement === canvas ||
  10947. document.pointerLockElement === canvas);
  10948. };
  10949. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10950. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10951. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10952. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10953. this._onVRDisplayPointerRestricted = function () {
  10954. if (canvas) {
  10955. canvas.requestPointerLock();
  10956. }
  10957. };
  10958. this._onVRDisplayPointerUnrestricted = function () {
  10959. document.exitPointerLock();
  10960. };
  10961. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10962. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10963. }
  10964. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10965. Engine.audioEngine = new BABYLON.AudioEngine();
  10966. }
  10967. // Prepare buffer pointers
  10968. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10969. this._currentBufferPointers[i] = new BufferPointer();
  10970. }
  10971. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10972. // Load WebVR Devices
  10973. if (options.autoEnableWebVR) {
  10974. this.initWebVR();
  10975. }
  10976. // Detect if we are running on a faulty buggy OS.
  10977. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10978. // Detect if we are running on a faulty buggy desktop OS.
  10979. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10980. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10981. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10982. }
  10983. Object.defineProperty(Engine, "LastCreatedEngine", {
  10984. get: function () {
  10985. if (Engine.Instances.length === 0) {
  10986. return null;
  10987. }
  10988. return Engine.Instances[Engine.Instances.length - 1];
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(Engine, "LastCreatedScene", {
  10994. get: function () {
  10995. var lastCreatedEngine = Engine.LastCreatedEngine;
  10996. if (!lastCreatedEngine) {
  10997. return null;
  10998. }
  10999. if (lastCreatedEngine.scenes.length === 0) {
  11000. return null;
  11001. }
  11002. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. /**
  11008. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11009. */
  11010. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11011. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11012. var engine = Engine.Instances[engineIndex];
  11013. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11014. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11015. }
  11016. }
  11017. };
  11018. Object.defineProperty(Engine, "NEVER", {
  11019. get: function () {
  11020. return Engine._NEVER;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(Engine, "ALWAYS", {
  11026. get: function () {
  11027. return Engine._ALWAYS;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(Engine, "LESS", {
  11033. get: function () {
  11034. return Engine._LESS;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(Engine, "EQUAL", {
  11040. get: function () {
  11041. return Engine._EQUAL;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(Engine, "LEQUAL", {
  11047. get: function () {
  11048. return Engine._LEQUAL;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. Object.defineProperty(Engine, "GREATER", {
  11054. get: function () {
  11055. return Engine._GREATER;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. Object.defineProperty(Engine, "GEQUAL", {
  11061. get: function () {
  11062. return Engine._GEQUAL;
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(Engine, "NOTEQUAL", {
  11068. get: function () {
  11069. return Engine._NOTEQUAL;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Object.defineProperty(Engine, "KEEP", {
  11075. get: function () {
  11076. return Engine._KEEP;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. Object.defineProperty(Engine, "REPLACE", {
  11082. get: function () {
  11083. return Engine._REPLACE;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(Engine, "INCR", {
  11089. get: function () {
  11090. return Engine._INCR;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(Engine, "DECR", {
  11096. get: function () {
  11097. return Engine._DECR;
  11098. },
  11099. enumerable: true,
  11100. configurable: true
  11101. });
  11102. Object.defineProperty(Engine, "INVERT", {
  11103. get: function () {
  11104. return Engine._INVERT;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. Object.defineProperty(Engine, "INCR_WRAP", {
  11110. get: function () {
  11111. return Engine._INCR_WRAP;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(Engine, "DECR_WRAP", {
  11117. get: function () {
  11118. return Engine._DECR_WRAP;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11124. get: function () {
  11125. return Engine._ALPHA_DISABLE;
  11126. },
  11127. enumerable: true,
  11128. configurable: true
  11129. });
  11130. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11131. get: function () {
  11132. return Engine._ALPHA_ONEONE;
  11133. },
  11134. enumerable: true,
  11135. configurable: true
  11136. });
  11137. Object.defineProperty(Engine, "ALPHA_ADD", {
  11138. get: function () {
  11139. return Engine._ALPHA_ADD;
  11140. },
  11141. enumerable: true,
  11142. configurable: true
  11143. });
  11144. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11145. get: function () {
  11146. return Engine._ALPHA_COMBINE;
  11147. },
  11148. enumerable: true,
  11149. configurable: true
  11150. });
  11151. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11152. get: function () {
  11153. return Engine._ALPHA_SUBTRACT;
  11154. },
  11155. enumerable: true,
  11156. configurable: true
  11157. });
  11158. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11159. get: function () {
  11160. return Engine._ALPHA_MULTIPLY;
  11161. },
  11162. enumerable: true,
  11163. configurable: true
  11164. });
  11165. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11166. get: function () {
  11167. return Engine._ALPHA_MAXIMIZED;
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11173. get: function () {
  11174. return Engine._ALPHA_PREMULTIPLIED;
  11175. },
  11176. enumerable: true,
  11177. configurable: true
  11178. });
  11179. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11180. get: function () {
  11181. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11182. },
  11183. enumerable: true,
  11184. configurable: true
  11185. });
  11186. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11187. get: function () {
  11188. return Engine._ALPHA_INTERPOLATE;
  11189. },
  11190. enumerable: true,
  11191. configurable: true
  11192. });
  11193. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11194. get: function () {
  11195. return Engine._ALPHA_SCREENMODE;
  11196. },
  11197. enumerable: true,
  11198. configurable: true
  11199. });
  11200. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11201. get: function () {
  11202. return Engine._DELAYLOADSTATE_NONE;
  11203. },
  11204. enumerable: true,
  11205. configurable: true
  11206. });
  11207. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11208. get: function () {
  11209. return Engine._DELAYLOADSTATE_LOADED;
  11210. },
  11211. enumerable: true,
  11212. configurable: true
  11213. });
  11214. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11215. get: function () {
  11216. return Engine._DELAYLOADSTATE_LOADING;
  11217. },
  11218. enumerable: true,
  11219. configurable: true
  11220. });
  11221. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11222. get: function () {
  11223. return Engine._DELAYLOADSTATE_NOTLOADED;
  11224. },
  11225. enumerable: true,
  11226. configurable: true
  11227. });
  11228. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11229. get: function () {
  11230. return Engine._TEXTUREFORMAT_ALPHA;
  11231. },
  11232. enumerable: true,
  11233. configurable: true
  11234. });
  11235. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11236. get: function () {
  11237. return Engine._TEXTUREFORMAT_LUMINANCE;
  11238. },
  11239. enumerable: true,
  11240. configurable: true
  11241. });
  11242. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11243. /**
  11244. * R32F
  11245. */
  11246. get: function () {
  11247. return Engine._TEXTUREFORMAT_R32F;
  11248. },
  11249. enumerable: true,
  11250. configurable: true
  11251. });
  11252. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11253. /**
  11254. * RG32F
  11255. */
  11256. get: function () {
  11257. return Engine._TEXTUREFORMAT_RG32F;
  11258. },
  11259. enumerable: true,
  11260. configurable: true
  11261. });
  11262. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11263. /**
  11264. * RGB32F
  11265. */
  11266. get: function () {
  11267. return Engine._TEXTUREFORMAT_RGB32F;
  11268. },
  11269. enumerable: true,
  11270. configurable: true
  11271. });
  11272. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11273. /**
  11274. * RGBA32F
  11275. */
  11276. get: function () {
  11277. return Engine._TEXTUREFORMAT_RGBA32F;
  11278. },
  11279. enumerable: true,
  11280. configurable: true
  11281. });
  11282. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11283. get: function () {
  11284. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11285. },
  11286. enumerable: true,
  11287. configurable: true
  11288. });
  11289. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11290. get: function () {
  11291. return Engine._TEXTUREFORMAT_RGB;
  11292. },
  11293. enumerable: true,
  11294. configurable: true
  11295. });
  11296. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11297. get: function () {
  11298. return Engine._TEXTUREFORMAT_RGBA;
  11299. },
  11300. enumerable: true,
  11301. configurable: true
  11302. });
  11303. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11304. get: function () {
  11305. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11306. },
  11307. enumerable: true,
  11308. configurable: true
  11309. });
  11310. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11311. get: function () {
  11312. return Engine._TEXTURETYPE_FLOAT;
  11313. },
  11314. enumerable: true,
  11315. configurable: true
  11316. });
  11317. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11318. get: function () {
  11319. return Engine._TEXTURETYPE_HALF_FLOAT;
  11320. },
  11321. enumerable: true,
  11322. configurable: true
  11323. });
  11324. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11325. get: function () {
  11326. return Engine._SCALEMODE_FLOOR;
  11327. },
  11328. enumerable: true,
  11329. configurable: true
  11330. });
  11331. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11332. get: function () {
  11333. return Engine._SCALEMODE_NEAREST;
  11334. },
  11335. enumerable: true,
  11336. configurable: true
  11337. });
  11338. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11339. get: function () {
  11340. return Engine._SCALEMODE_CEILING;
  11341. },
  11342. enumerable: true,
  11343. configurable: true
  11344. });
  11345. Object.defineProperty(Engine, "Version", {
  11346. get: function () {
  11347. return "3.2.0-beta.1";
  11348. },
  11349. enumerable: true,
  11350. configurable: true
  11351. });
  11352. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11353. get: function () {
  11354. return this._vrExclusivePointerMode;
  11355. },
  11356. enumerable: true,
  11357. configurable: true
  11358. });
  11359. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11360. get: function () {
  11361. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11362. },
  11363. enumerable: true,
  11364. configurable: true
  11365. });
  11366. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11367. get: function () {
  11368. return this._webGLVersion < 2 || this.forcePOTTextures;
  11369. },
  11370. enumerable: true,
  11371. configurable: true
  11372. });
  11373. Object.defineProperty(Engine.prototype, "badOS", {
  11374. get: function () {
  11375. return this._badOS;
  11376. },
  11377. enumerable: true,
  11378. configurable: true
  11379. });
  11380. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11381. get: function () {
  11382. return this._badDesktopOS;
  11383. },
  11384. enumerable: true,
  11385. configurable: true
  11386. });
  11387. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11388. get: function () {
  11389. return this._performanceMonitor;
  11390. },
  11391. enumerable: true,
  11392. configurable: true
  11393. });
  11394. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11395. get: function () {
  11396. return this._texturesSupported;
  11397. },
  11398. enumerable: true,
  11399. configurable: true
  11400. });
  11401. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11402. get: function () {
  11403. return this._textureFormatInUse;
  11404. },
  11405. enumerable: true,
  11406. configurable: true
  11407. });
  11408. Object.defineProperty(Engine.prototype, "currentViewport", {
  11409. get: function () {
  11410. return this._cachedViewport;
  11411. },
  11412. enumerable: true,
  11413. configurable: true
  11414. });
  11415. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11416. // Empty texture
  11417. get: function () {
  11418. if (!this._emptyTexture) {
  11419. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11420. }
  11421. return this._emptyTexture;
  11422. },
  11423. enumerable: true,
  11424. configurable: true
  11425. });
  11426. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11427. get: function () {
  11428. if (!this._emptyTexture3D) {
  11429. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11430. }
  11431. return this._emptyTexture3D;
  11432. },
  11433. enumerable: true,
  11434. configurable: true
  11435. });
  11436. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11437. get: function () {
  11438. if (!this._emptyCubeTexture) {
  11439. var faceData = new Uint8Array(4);
  11440. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11441. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11442. }
  11443. return this._emptyCubeTexture;
  11444. },
  11445. enumerable: true,
  11446. configurable: true
  11447. });
  11448. Engine.prototype._rebuildInternalTextures = function () {
  11449. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11450. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11451. var internalTexture = currentState_1[_i];
  11452. internalTexture._rebuild();
  11453. }
  11454. };
  11455. Engine.prototype._rebuildEffects = function () {
  11456. for (var key in this._compiledEffects) {
  11457. var effect = this._compiledEffects[key];
  11458. effect._prepareEffect();
  11459. }
  11460. BABYLON.Effect.ResetCache();
  11461. };
  11462. Engine.prototype._rebuildBuffers = function () {
  11463. // Index / Vertex
  11464. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11465. var scene = _a[_i];
  11466. scene.resetCachedMaterial();
  11467. scene._rebuildGeometries();
  11468. scene._rebuildTextures();
  11469. }
  11470. // Uniforms
  11471. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11472. var uniformBuffer = _c[_b];
  11473. uniformBuffer._rebuild();
  11474. }
  11475. };
  11476. Engine.prototype._initGLContext = function () {
  11477. // Caps
  11478. this._caps = new EngineCapabilities();
  11479. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11480. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11481. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11482. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11483. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11484. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11485. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11486. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11487. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11488. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11489. // Infos
  11490. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11491. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11492. if (rendererInfo != null) {
  11493. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11494. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11495. }
  11496. if (!this._glVendor) {
  11497. this._glVendor = "Unknown vendor";
  11498. }
  11499. if (!this._glRenderer) {
  11500. this._glRenderer = "Unknown renderer";
  11501. }
  11502. // Constants
  11503. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11504. if (this._gl.RGBA16F !== 0x881A) {
  11505. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11506. }
  11507. if (this._gl.RGBA32F !== 0x8814) {
  11508. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11509. }
  11510. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11511. this._gl.DEPTH24_STENCIL8 = 35056;
  11512. }
  11513. // Extensions
  11514. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11515. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11516. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11517. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11518. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11519. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11520. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11521. 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');
  11522. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11523. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11524. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11525. this._caps.highPrecisionShaderSupported = true;
  11526. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11527. if (this._caps.timerQuery) {
  11528. if (this._webGLVersion === 1) {
  11529. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11530. }
  11531. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11532. }
  11533. // Checks if some of the format renders first to allow the use of webgl inspector.
  11534. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11535. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11536. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11537. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11538. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11539. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11540. if (this._webGLVersion > 1) {
  11541. this._gl.HALF_FLOAT_OES = 0x140B;
  11542. }
  11543. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11544. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11545. // Draw buffers
  11546. if (this._webGLVersion > 1) {
  11547. this._caps.drawBuffersExtension = true;
  11548. }
  11549. else {
  11550. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11551. if (drawBuffersExtension !== null) {
  11552. this._caps.drawBuffersExtension = true;
  11553. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11554. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11555. for (var i = 0; i < 16; i++) {
  11556. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11557. }
  11558. }
  11559. else {
  11560. this._caps.drawBuffersExtension = false;
  11561. }
  11562. }
  11563. // Depth Texture
  11564. if (this._webGLVersion > 1) {
  11565. this._caps.depthTextureExtension = true;
  11566. }
  11567. else {
  11568. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11569. if (depthTextureExtension != null) {
  11570. this._caps.depthTextureExtension = true;
  11571. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11572. }
  11573. }
  11574. // Vertex array object
  11575. if (this._webGLVersion > 1) {
  11576. this._caps.vertexArrayObject = true;
  11577. }
  11578. else {
  11579. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11580. if (vertexArrayObjectExtension != null) {
  11581. this._caps.vertexArrayObject = true;
  11582. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11583. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11584. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11585. }
  11586. else {
  11587. this._caps.vertexArrayObject = false;
  11588. }
  11589. }
  11590. // Instances count
  11591. if (this._webGLVersion > 1) {
  11592. this._caps.instancedArrays = true;
  11593. }
  11594. else {
  11595. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11596. if (instanceExtension != null) {
  11597. this._caps.instancedArrays = true;
  11598. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11599. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11600. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11601. }
  11602. else {
  11603. this._caps.instancedArrays = false;
  11604. }
  11605. }
  11606. // Intelligently add supported compressed formats in order to check for.
  11607. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11608. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11609. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11610. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11611. if (this._caps.astc)
  11612. this.texturesSupported.push('-astc.ktx');
  11613. if (this._caps.s3tc)
  11614. this.texturesSupported.push('-dxt.ktx');
  11615. if (this._caps.pvrtc)
  11616. this.texturesSupported.push('-pvrtc.ktx');
  11617. if (this._caps.etc2)
  11618. this.texturesSupported.push('-etc2.ktx');
  11619. if (this._caps.etc1)
  11620. this.texturesSupported.push('-etc1.ktx');
  11621. if (this._gl.getShaderPrecisionFormat) {
  11622. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11623. if (highp) {
  11624. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11625. }
  11626. }
  11627. // Depth buffer
  11628. this.setDepthBuffer(true);
  11629. this.setDepthFunctionToLessOrEqual();
  11630. this.setDepthWrite(true);
  11631. // Texture maps
  11632. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11633. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11634. this._nextFreeTextureSlots.push(slot);
  11635. }
  11636. };
  11637. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11638. get: function () {
  11639. return this._webGLVersion;
  11640. },
  11641. enumerable: true,
  11642. configurable: true
  11643. });
  11644. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11645. /**
  11646. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11647. */
  11648. get: function () {
  11649. return this._isStencilEnable;
  11650. },
  11651. enumerable: true,
  11652. configurable: true
  11653. });
  11654. Engine.prototype._prepareWorkingCanvas = function () {
  11655. if (this._workingCanvas) {
  11656. return;
  11657. }
  11658. this._workingCanvas = document.createElement("canvas");
  11659. var context = this._workingCanvas.getContext("2d");
  11660. if (context) {
  11661. this._workingContext = context;
  11662. }
  11663. };
  11664. Engine.prototype.resetTextureCache = function () {
  11665. for (var key in this._boundTexturesCache) {
  11666. var boundTexture = this._boundTexturesCache[key];
  11667. if (boundTexture) {
  11668. this._removeDesignatedSlot(boundTexture);
  11669. }
  11670. this._boundTexturesCache[key] = null;
  11671. }
  11672. if (!this.disableTextureBindingOptimization) {
  11673. this._nextFreeTextureSlots = [];
  11674. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11675. this._nextFreeTextureSlots.push(slot);
  11676. }
  11677. }
  11678. this._currentTextureChannel = -1;
  11679. };
  11680. Engine.prototype.isDeterministicLockStep = function () {
  11681. return this._deterministicLockstep;
  11682. };
  11683. Engine.prototype.getLockstepMaxSteps = function () {
  11684. return this._lockstepMaxSteps;
  11685. };
  11686. Engine.prototype.getGlInfo = function () {
  11687. return {
  11688. vendor: this._glVendor,
  11689. renderer: this._glRenderer,
  11690. version: this._glVersion
  11691. };
  11692. };
  11693. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11694. if (useScreen === void 0) { useScreen = false; }
  11695. var viewport = camera.viewport;
  11696. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11697. };
  11698. Engine.prototype.getRenderWidth = function (useScreen) {
  11699. if (useScreen === void 0) { useScreen = false; }
  11700. if (!useScreen && this._currentRenderTarget) {
  11701. return this._currentRenderTarget.width;
  11702. }
  11703. return this._gl.drawingBufferWidth;
  11704. };
  11705. Engine.prototype.getRenderHeight = function (useScreen) {
  11706. if (useScreen === void 0) { useScreen = false; }
  11707. if (!useScreen && this._currentRenderTarget) {
  11708. return this._currentRenderTarget.height;
  11709. }
  11710. return this._gl.drawingBufferHeight;
  11711. };
  11712. Engine.prototype.getRenderingCanvas = function () {
  11713. return this._renderingCanvas;
  11714. };
  11715. Engine.prototype.getRenderingCanvasClientRect = function () {
  11716. if (!this._renderingCanvas) {
  11717. return null;
  11718. }
  11719. return this._renderingCanvas.getBoundingClientRect();
  11720. };
  11721. Engine.prototype.setHardwareScalingLevel = function (level) {
  11722. this._hardwareScalingLevel = level;
  11723. this.resize();
  11724. };
  11725. Engine.prototype.getHardwareScalingLevel = function () {
  11726. return this._hardwareScalingLevel;
  11727. };
  11728. Engine.prototype.getLoadedTexturesCache = function () {
  11729. return this._internalTexturesCache;
  11730. };
  11731. Engine.prototype.getCaps = function () {
  11732. return this._caps;
  11733. };
  11734. Object.defineProperty(Engine.prototype, "drawCalls", {
  11735. /** The number of draw calls submitted last frame */
  11736. get: function () {
  11737. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11738. return 0;
  11739. },
  11740. enumerable: true,
  11741. configurable: true
  11742. });
  11743. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11744. get: function () {
  11745. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11746. return null;
  11747. },
  11748. enumerable: true,
  11749. configurable: true
  11750. });
  11751. Engine.prototype.getDepthFunction = function () {
  11752. return this._depthCullingState.depthFunc;
  11753. };
  11754. Engine.prototype.setDepthFunction = function (depthFunc) {
  11755. this._depthCullingState.depthFunc = depthFunc;
  11756. };
  11757. Engine.prototype.setDepthFunctionToGreater = function () {
  11758. this._depthCullingState.depthFunc = this._gl.GREATER;
  11759. };
  11760. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11761. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11762. };
  11763. Engine.prototype.setDepthFunctionToLess = function () {
  11764. this._depthCullingState.depthFunc = this._gl.LESS;
  11765. };
  11766. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11767. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11768. };
  11769. Engine.prototype.getStencilBuffer = function () {
  11770. return this._stencilState.stencilTest;
  11771. };
  11772. Engine.prototype.setStencilBuffer = function (enable) {
  11773. this._stencilState.stencilTest = enable;
  11774. };
  11775. Engine.prototype.getStencilMask = function () {
  11776. return this._stencilState.stencilMask;
  11777. };
  11778. Engine.prototype.setStencilMask = function (mask) {
  11779. this._stencilState.stencilMask = mask;
  11780. };
  11781. Engine.prototype.getStencilFunction = function () {
  11782. return this._stencilState.stencilFunc;
  11783. };
  11784. Engine.prototype.getStencilFunctionReference = function () {
  11785. return this._stencilState.stencilFuncRef;
  11786. };
  11787. Engine.prototype.getStencilFunctionMask = function () {
  11788. return this._stencilState.stencilFuncMask;
  11789. };
  11790. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11791. this._stencilState.stencilFunc = stencilFunc;
  11792. };
  11793. Engine.prototype.setStencilFunctionReference = function (reference) {
  11794. this._stencilState.stencilFuncRef = reference;
  11795. };
  11796. Engine.prototype.setStencilFunctionMask = function (mask) {
  11797. this._stencilState.stencilFuncMask = mask;
  11798. };
  11799. Engine.prototype.getStencilOperationFail = function () {
  11800. return this._stencilState.stencilOpStencilFail;
  11801. };
  11802. Engine.prototype.getStencilOperationDepthFail = function () {
  11803. return this._stencilState.stencilOpDepthFail;
  11804. };
  11805. Engine.prototype.getStencilOperationPass = function () {
  11806. return this._stencilState.stencilOpStencilDepthPass;
  11807. };
  11808. Engine.prototype.setStencilOperationFail = function (operation) {
  11809. this._stencilState.stencilOpStencilFail = operation;
  11810. };
  11811. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11812. this._stencilState.stencilOpDepthFail = operation;
  11813. };
  11814. Engine.prototype.setStencilOperationPass = function (operation) {
  11815. this._stencilState.stencilOpStencilDepthPass = operation;
  11816. };
  11817. Engine.prototype.setDitheringState = function (value) {
  11818. if (value) {
  11819. this._gl.enable(this._gl.DITHER);
  11820. }
  11821. else {
  11822. this._gl.disable(this._gl.DITHER);
  11823. }
  11824. };
  11825. Engine.prototype.setRasterizerState = function (value) {
  11826. if (value) {
  11827. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11828. }
  11829. else {
  11830. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11831. }
  11832. };
  11833. /**
  11834. * stop executing a render loop function and remove it from the execution array
  11835. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11836. */
  11837. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11838. if (!renderFunction) {
  11839. this._activeRenderLoops = [];
  11840. return;
  11841. }
  11842. var index = this._activeRenderLoops.indexOf(renderFunction);
  11843. if (index >= 0) {
  11844. this._activeRenderLoops.splice(index, 1);
  11845. }
  11846. };
  11847. Engine.prototype._renderLoop = function () {
  11848. if (!this._contextWasLost) {
  11849. var shouldRender = true;
  11850. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11851. shouldRender = false;
  11852. }
  11853. if (shouldRender) {
  11854. // Start new frame
  11855. this.beginFrame();
  11856. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11857. var renderFunction = this._activeRenderLoops[index];
  11858. renderFunction();
  11859. }
  11860. // Present
  11861. this.endFrame();
  11862. }
  11863. }
  11864. if (this._activeRenderLoops.length > 0) {
  11865. // Register new frame
  11866. var requester = null;
  11867. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11868. requester = this._vrDisplay;
  11869. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11870. }
  11871. else {
  11872. this._renderingQueueLaunched = false;
  11873. }
  11874. };
  11875. /**
  11876. * Register and execute a render loop. The engine can have more than one render function.
  11877. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11878. * @example
  11879. * engine.runRenderLoop(function () {
  11880. * scene.render()
  11881. * })
  11882. */
  11883. Engine.prototype.runRenderLoop = function (renderFunction) {
  11884. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11885. return;
  11886. }
  11887. this._activeRenderLoops.push(renderFunction);
  11888. if (!this._renderingQueueLaunched) {
  11889. this._renderingQueueLaunched = true;
  11890. this._bindedRenderFunction = this._renderLoop.bind(this);
  11891. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11892. }
  11893. };
  11894. /**
  11895. * Toggle full screen mode.
  11896. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11897. * @param {any} options - an options object to be sent to the requestFullscreen function
  11898. */
  11899. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11900. if (this.isFullscreen) {
  11901. BABYLON.Tools.ExitFullscreen();
  11902. }
  11903. else {
  11904. this._pointerLockRequested = requestPointerLock;
  11905. if (this._renderingCanvas) {
  11906. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11907. }
  11908. }
  11909. };
  11910. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11911. if (stencil === void 0) { stencil = false; }
  11912. this.applyStates();
  11913. var mode = 0;
  11914. if (backBuffer && color) {
  11915. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11916. mode |= this._gl.COLOR_BUFFER_BIT;
  11917. }
  11918. if (depth) {
  11919. this._gl.clearDepth(1.0);
  11920. mode |= this._gl.DEPTH_BUFFER_BIT;
  11921. }
  11922. if (stencil) {
  11923. this._gl.clearStencil(0);
  11924. mode |= this._gl.STENCIL_BUFFER_BIT;
  11925. }
  11926. this._gl.clear(mode);
  11927. };
  11928. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11929. var gl = this._gl;
  11930. // Save state
  11931. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11932. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11933. // Change state
  11934. gl.enable(gl.SCISSOR_TEST);
  11935. gl.scissor(x, y, width, height);
  11936. // Clear
  11937. this.clear(clearColor, true, true, true);
  11938. // Restore state
  11939. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11940. if (curScissor === true) {
  11941. gl.enable(gl.SCISSOR_TEST);
  11942. }
  11943. else {
  11944. gl.disable(gl.SCISSOR_TEST);
  11945. }
  11946. };
  11947. /**
  11948. * Set the WebGL's viewport
  11949. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11950. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11951. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11952. */
  11953. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11954. var width = requiredWidth || this.getRenderWidth();
  11955. var height = requiredHeight || this.getRenderHeight();
  11956. var x = viewport.x || 0;
  11957. var y = viewport.y || 0;
  11958. this._cachedViewport = viewport;
  11959. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11960. };
  11961. /**
  11962. * Directly set the WebGL Viewport
  11963. * The x, y, width & height are directly passed to the WebGL call
  11964. * @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.
  11965. */
  11966. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11967. var currentViewport = this._cachedViewport;
  11968. this._cachedViewport = null;
  11969. this._gl.viewport(x, y, width, height);
  11970. return currentViewport;
  11971. };
  11972. Engine.prototype.beginFrame = function () {
  11973. this.onBeginFrameObservable.notifyObservers(this);
  11974. this._measureFps();
  11975. };
  11976. Engine.prototype.endFrame = function () {
  11977. //force a flush in case we are using a bad OS.
  11978. if (this._badOS) {
  11979. this.flushFramebuffer();
  11980. }
  11981. //submit frame to the vr device, if enabled
  11982. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11983. // TODO: We should only submit the frame if we read frameData successfully.
  11984. this._vrDisplay.submitFrame();
  11985. }
  11986. this.onEndFrameObservable.notifyObservers(this);
  11987. };
  11988. /**
  11989. * resize the view according to the canvas' size.
  11990. * @example
  11991. * window.addEventListener("resize", function () {
  11992. * engine.resize();
  11993. * });
  11994. */
  11995. Engine.prototype.resize = function () {
  11996. // We're not resizing the size of the canvas while in VR mode & presenting
  11997. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11998. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11999. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12000. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12001. }
  12002. };
  12003. /**
  12004. * force a specific size of the canvas
  12005. * @param {number} width - the new canvas' width
  12006. * @param {number} height - the new canvas' height
  12007. */
  12008. Engine.prototype.setSize = function (width, height) {
  12009. if (!this._renderingCanvas) {
  12010. return;
  12011. }
  12012. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12013. return;
  12014. }
  12015. this._renderingCanvas.width = width;
  12016. this._renderingCanvas.height = height;
  12017. for (var index = 0; index < this.scenes.length; index++) {
  12018. var scene = this.scenes[index];
  12019. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12020. var cam = scene.cameras[camIndex];
  12021. cam._currentRenderId = 0;
  12022. }
  12023. }
  12024. if (this.onResizeObservable.hasObservers) {
  12025. this.onResizeObservable.notifyObservers(this);
  12026. }
  12027. };
  12028. // WebVR functions
  12029. Engine.prototype.isVRDevicePresent = function () {
  12030. return !!this._vrDisplay;
  12031. };
  12032. Engine.prototype.getVRDevice = function () {
  12033. return this._vrDisplay;
  12034. };
  12035. /**
  12036. * Initializes a webVR display and starts listening to display change events.
  12037. * The onVRDisplayChangedObservable will be notified upon these changes.
  12038. * @returns The onVRDisplayChangedObservable.
  12039. */
  12040. Engine.prototype.initWebVR = function () {
  12041. this.initWebVRAsync();
  12042. return this.onVRDisplayChangedObservable;
  12043. };
  12044. /**
  12045. * Initializes a webVR display and starts listening to display change events.
  12046. * The onVRDisplayChangedObservable will be notified upon these changes.
  12047. * @returns A promise containing a VRDisplay and if vr is supported.
  12048. */
  12049. Engine.prototype.initWebVRAsync = function () {
  12050. var _this = this;
  12051. var notifyObservers = function () {
  12052. var eventArgs = {
  12053. vrDisplay: _this._vrDisplay,
  12054. vrSupported: _this._vrSupported
  12055. };
  12056. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12057. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12058. };
  12059. if (!this._onVrDisplayConnect) {
  12060. this._onVrDisplayConnect = function (event) {
  12061. _this._vrDisplay = event.display;
  12062. notifyObservers();
  12063. };
  12064. this._onVrDisplayDisconnect = function () {
  12065. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12066. _this._vrDisplay = undefined;
  12067. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12068. notifyObservers();
  12069. };
  12070. this._onVrDisplayPresentChange = function () {
  12071. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12072. };
  12073. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12074. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12075. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12076. }
  12077. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12078. this._webVRInitPromise.then(notifyObservers);
  12079. return this._webVRInitPromise;
  12080. };
  12081. Engine.prototype.enableVR = function () {
  12082. var _this = this;
  12083. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12084. var onResolved = function () {
  12085. _this.onVRRequestPresentComplete.notifyObservers(true);
  12086. _this._onVRFullScreenTriggered();
  12087. };
  12088. var onRejected = function () {
  12089. _this.onVRRequestPresentComplete.notifyObservers(false);
  12090. };
  12091. this.onVRRequestPresentStart.notifyObservers(this);
  12092. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12093. }
  12094. };
  12095. Engine.prototype.disableVR = function () {
  12096. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12097. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12098. }
  12099. };
  12100. Engine.prototype._getVRDisplaysAsync = function () {
  12101. var _this = this;
  12102. return new Promise(function (res, rej) {
  12103. if (navigator.getVRDisplays) {
  12104. navigator.getVRDisplays().then(function (devices) {
  12105. _this._vrSupported = true;
  12106. // note that devices may actually be an empty array. This is fine;
  12107. // we expect this._vrDisplay to be undefined in this case.
  12108. _this._vrDisplay = devices[0];
  12109. res({
  12110. vrDisplay: _this._vrDisplay,
  12111. vrSupported: _this._vrSupported
  12112. });
  12113. });
  12114. }
  12115. else {
  12116. _this._vrDisplay = undefined;
  12117. _this._vrSupported = false;
  12118. res({
  12119. vrDisplay: _this._vrDisplay,
  12120. vrSupported: _this._vrSupported
  12121. });
  12122. }
  12123. });
  12124. };
  12125. /**
  12126. * Binds the frame buffer to the specified texture.
  12127. * @param texture The texture to render to or null for the default canvas
  12128. * @param faceIndex The face of the texture to render to in case of cube texture
  12129. * @param requiredWidth The width of the target to render to
  12130. * @param requiredHeight The height of the target to render to
  12131. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12132. * @param depthStencilTexture The depth stencil texture to use to render
  12133. */
  12134. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12135. if (this._currentRenderTarget) {
  12136. this.unBindFramebuffer(this._currentRenderTarget);
  12137. }
  12138. this._currentRenderTarget = texture;
  12139. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12140. var gl = this._gl;
  12141. if (texture.isCube) {
  12142. if (faceIndex === undefined) {
  12143. faceIndex = 0;
  12144. }
  12145. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12146. if (depthStencilTexture) {
  12147. if (depthStencilTexture._generateStencilBuffer) {
  12148. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12149. }
  12150. else {
  12151. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12152. }
  12153. }
  12154. }
  12155. if (this._cachedViewport && !forceFullscreenViewport) {
  12156. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12157. }
  12158. else {
  12159. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12160. }
  12161. this.wipeCaches();
  12162. };
  12163. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12164. if (this._currentFramebuffer !== framebuffer) {
  12165. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12166. this._currentFramebuffer = framebuffer;
  12167. }
  12168. };
  12169. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12170. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12171. this._currentRenderTarget = null;
  12172. // If MSAA, we need to bitblt back to main texture
  12173. var gl = this._gl;
  12174. if (texture._MSAAFramebuffer) {
  12175. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12176. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12177. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12178. }
  12179. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12180. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12181. gl.generateMipmap(gl.TEXTURE_2D);
  12182. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12183. }
  12184. if (onBeforeUnbind) {
  12185. if (texture._MSAAFramebuffer) {
  12186. // Bind the correct framebuffer
  12187. this.bindUnboundFramebuffer(texture._framebuffer);
  12188. }
  12189. onBeforeUnbind();
  12190. }
  12191. this.bindUnboundFramebuffer(null);
  12192. };
  12193. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12194. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12195. this._currentRenderTarget = null;
  12196. // If MSAA, we need to bitblt back to main texture
  12197. var gl = this._gl;
  12198. if (textures[0]._MSAAFramebuffer) {
  12199. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12200. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12201. var attachments = textures[0]._attachments;
  12202. if (!attachments) {
  12203. attachments = new Array(textures.length);
  12204. textures[0]._attachments = attachments;
  12205. }
  12206. for (var i = 0; i < textures.length; i++) {
  12207. var texture = textures[i];
  12208. for (var j = 0; j < attachments.length; j++) {
  12209. attachments[j] = gl.NONE;
  12210. }
  12211. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12212. gl.readBuffer(attachments[i]);
  12213. gl.drawBuffers(attachments);
  12214. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12215. }
  12216. for (var i = 0; i < attachments.length; i++) {
  12217. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12218. }
  12219. gl.drawBuffers(attachments);
  12220. }
  12221. for (var i = 0; i < textures.length; i++) {
  12222. var texture = textures[i];
  12223. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12224. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12225. gl.generateMipmap(gl.TEXTURE_2D);
  12226. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12227. }
  12228. }
  12229. if (onBeforeUnbind) {
  12230. if (textures[0]._MSAAFramebuffer) {
  12231. // Bind the correct framebuffer
  12232. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12233. }
  12234. onBeforeUnbind();
  12235. }
  12236. this.bindUnboundFramebuffer(null);
  12237. };
  12238. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12239. if (texture.generateMipMaps) {
  12240. var gl = this._gl;
  12241. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12242. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12243. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12244. }
  12245. };
  12246. Engine.prototype.flushFramebuffer = function () {
  12247. this._gl.flush();
  12248. };
  12249. Engine.prototype.restoreDefaultFramebuffer = function () {
  12250. if (this._currentRenderTarget) {
  12251. this.unBindFramebuffer(this._currentRenderTarget);
  12252. }
  12253. else {
  12254. this.bindUnboundFramebuffer(null);
  12255. }
  12256. if (this._cachedViewport) {
  12257. this.setViewport(this._cachedViewport);
  12258. }
  12259. this.wipeCaches();
  12260. };
  12261. // UBOs
  12262. Engine.prototype.createUniformBuffer = function (elements) {
  12263. var ubo = this._gl.createBuffer();
  12264. if (!ubo) {
  12265. throw new Error("Unable to create uniform buffer");
  12266. }
  12267. this.bindUniformBuffer(ubo);
  12268. if (elements instanceof Float32Array) {
  12269. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12270. }
  12271. else {
  12272. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12273. }
  12274. this.bindUniformBuffer(null);
  12275. ubo.references = 1;
  12276. return ubo;
  12277. };
  12278. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12279. var ubo = this._gl.createBuffer();
  12280. if (!ubo) {
  12281. throw new Error("Unable to create dynamic uniform buffer");
  12282. }
  12283. this.bindUniformBuffer(ubo);
  12284. if (elements instanceof Float32Array) {
  12285. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12286. }
  12287. else {
  12288. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12289. }
  12290. this.bindUniformBuffer(null);
  12291. ubo.references = 1;
  12292. return ubo;
  12293. };
  12294. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12295. this.bindUniformBuffer(uniformBuffer);
  12296. if (offset === undefined) {
  12297. offset = 0;
  12298. }
  12299. if (count === undefined) {
  12300. if (elements instanceof Float32Array) {
  12301. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12302. }
  12303. else {
  12304. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12305. }
  12306. }
  12307. else {
  12308. if (elements instanceof Float32Array) {
  12309. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12310. }
  12311. else {
  12312. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12313. }
  12314. }
  12315. this.bindUniformBuffer(null);
  12316. };
  12317. // VBOs
  12318. Engine.prototype._resetVertexBufferBinding = function () {
  12319. this.bindArrayBuffer(null);
  12320. this._cachedVertexBuffers = null;
  12321. };
  12322. Engine.prototype.createVertexBuffer = function (vertices) {
  12323. var vbo = this._gl.createBuffer();
  12324. if (!vbo) {
  12325. throw new Error("Unable to create vertex buffer");
  12326. }
  12327. this.bindArrayBuffer(vbo);
  12328. if (vertices instanceof Float32Array) {
  12329. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12330. }
  12331. else {
  12332. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12333. }
  12334. this._resetVertexBufferBinding();
  12335. vbo.references = 1;
  12336. return vbo;
  12337. };
  12338. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12339. var vbo = this._gl.createBuffer();
  12340. if (!vbo) {
  12341. throw new Error("Unable to create dynamic vertex buffer");
  12342. }
  12343. this.bindArrayBuffer(vbo);
  12344. if (vertices instanceof Float32Array) {
  12345. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12346. }
  12347. else {
  12348. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12349. }
  12350. this._resetVertexBufferBinding();
  12351. vbo.references = 1;
  12352. return vbo;
  12353. };
  12354. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12355. if (offset === void 0) { offset = 0; }
  12356. // Force cache update
  12357. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12358. this.bindIndexBuffer(indexBuffer);
  12359. var arrayBuffer;
  12360. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12361. arrayBuffer = indices;
  12362. }
  12363. else {
  12364. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12365. }
  12366. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12367. this._resetIndexBufferBinding();
  12368. };
  12369. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12370. this.bindArrayBuffer(vertexBuffer);
  12371. if (offset === undefined) {
  12372. offset = 0;
  12373. }
  12374. if (count === undefined) {
  12375. if (vertices instanceof Float32Array) {
  12376. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12377. }
  12378. else {
  12379. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12380. }
  12381. }
  12382. else {
  12383. if (vertices instanceof Float32Array) {
  12384. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12385. }
  12386. else {
  12387. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12388. }
  12389. }
  12390. this._resetVertexBufferBinding();
  12391. };
  12392. Engine.prototype._resetIndexBufferBinding = function () {
  12393. this.bindIndexBuffer(null);
  12394. this._cachedIndexBuffer = null;
  12395. };
  12396. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12397. var vbo = this._gl.createBuffer();
  12398. if (!vbo) {
  12399. throw new Error("Unable to create index buffer");
  12400. }
  12401. this.bindIndexBuffer(vbo);
  12402. // Check for 32 bits indices
  12403. var arrayBuffer;
  12404. var need32Bits = false;
  12405. if (indices instanceof Uint16Array) {
  12406. arrayBuffer = indices;
  12407. }
  12408. else {
  12409. //check 32 bit support
  12410. if (this._caps.uintIndices) {
  12411. if (indices instanceof Uint32Array) {
  12412. arrayBuffer = indices;
  12413. need32Bits = true;
  12414. }
  12415. else {
  12416. //number[] or Int32Array, check if 32 bit is necessary
  12417. for (var index = 0; index < indices.length; index++) {
  12418. if (indices[index] > 65535) {
  12419. need32Bits = true;
  12420. break;
  12421. }
  12422. }
  12423. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12424. }
  12425. }
  12426. else {
  12427. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12428. arrayBuffer = new Uint16Array(indices);
  12429. }
  12430. }
  12431. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12432. this._resetIndexBufferBinding();
  12433. vbo.references = 1;
  12434. vbo.is32Bits = need32Bits;
  12435. return vbo;
  12436. };
  12437. Engine.prototype.bindArrayBuffer = function (buffer) {
  12438. if (!this._vaoRecordInProgress) {
  12439. this._unbindVertexArrayObject();
  12440. }
  12441. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12442. };
  12443. Engine.prototype.bindUniformBuffer = function (buffer) {
  12444. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12445. };
  12446. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12447. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12448. };
  12449. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12450. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12451. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12452. };
  12453. ;
  12454. Engine.prototype.bindIndexBuffer = function (buffer) {
  12455. if (!this._vaoRecordInProgress) {
  12456. this._unbindVertexArrayObject();
  12457. }
  12458. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12459. };
  12460. Engine.prototype.bindBuffer = function (buffer, target) {
  12461. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12462. this._gl.bindBuffer(target, buffer);
  12463. this._currentBoundBuffer[target] = buffer;
  12464. }
  12465. };
  12466. Engine.prototype.updateArrayBuffer = function (data) {
  12467. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12468. };
  12469. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12470. var pointer = this._currentBufferPointers[indx];
  12471. var changed = false;
  12472. if (!pointer.active) {
  12473. changed = true;
  12474. pointer.active = true;
  12475. pointer.index = indx;
  12476. pointer.size = size;
  12477. pointer.type = type;
  12478. pointer.normalized = normalized;
  12479. pointer.stride = stride;
  12480. pointer.offset = offset;
  12481. pointer.buffer = buffer;
  12482. }
  12483. else {
  12484. if (pointer.buffer !== buffer) {
  12485. pointer.buffer = buffer;
  12486. changed = true;
  12487. }
  12488. if (pointer.size !== size) {
  12489. pointer.size = size;
  12490. changed = true;
  12491. }
  12492. if (pointer.type !== type) {
  12493. pointer.type = type;
  12494. changed = true;
  12495. }
  12496. if (pointer.normalized !== normalized) {
  12497. pointer.normalized = normalized;
  12498. changed = true;
  12499. }
  12500. if (pointer.stride !== stride) {
  12501. pointer.stride = stride;
  12502. changed = true;
  12503. }
  12504. if (pointer.offset !== offset) {
  12505. pointer.offset = offset;
  12506. changed = true;
  12507. }
  12508. }
  12509. if (changed || this._vaoRecordInProgress) {
  12510. this.bindArrayBuffer(buffer);
  12511. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12512. }
  12513. };
  12514. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12515. if (indexBuffer == null) {
  12516. return;
  12517. }
  12518. if (this._cachedIndexBuffer !== indexBuffer) {
  12519. this._cachedIndexBuffer = indexBuffer;
  12520. this.bindIndexBuffer(indexBuffer);
  12521. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12522. }
  12523. };
  12524. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12525. var attributes = effect.getAttributesNames();
  12526. if (!this._vaoRecordInProgress) {
  12527. this._unbindVertexArrayObject();
  12528. }
  12529. this.unbindAllAttributes();
  12530. for (var index = 0; index < attributes.length; index++) {
  12531. var order = effect.getAttributeLocation(index);
  12532. if (order >= 0) {
  12533. var vertexBuffer = vertexBuffers[attributes[index]];
  12534. if (!vertexBuffer) {
  12535. continue;
  12536. }
  12537. this._gl.enableVertexAttribArray(order);
  12538. if (!this._vaoRecordInProgress) {
  12539. this._vertexAttribArraysEnabled[order] = true;
  12540. }
  12541. var buffer = vertexBuffer.getBuffer();
  12542. if (buffer) {
  12543. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12544. if (vertexBuffer.getIsInstanced()) {
  12545. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12546. if (!this._vaoRecordInProgress) {
  12547. this._currentInstanceLocations.push(order);
  12548. this._currentInstanceBuffers.push(buffer);
  12549. }
  12550. }
  12551. }
  12552. }
  12553. }
  12554. };
  12555. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12556. var vao = this._gl.createVertexArray();
  12557. this._vaoRecordInProgress = true;
  12558. this._gl.bindVertexArray(vao);
  12559. this._mustWipeVertexAttributes = true;
  12560. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12561. this.bindIndexBuffer(indexBuffer);
  12562. this._vaoRecordInProgress = false;
  12563. this._gl.bindVertexArray(null);
  12564. return vao;
  12565. };
  12566. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12567. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12568. this._cachedVertexArrayObject = vertexArrayObject;
  12569. this._gl.bindVertexArray(vertexArrayObject);
  12570. this._cachedVertexBuffers = null;
  12571. this._cachedIndexBuffer = null;
  12572. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12573. this._mustWipeVertexAttributes = true;
  12574. }
  12575. };
  12576. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12577. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12578. this._cachedVertexBuffers = vertexBuffer;
  12579. this._cachedEffectForVertexBuffers = effect;
  12580. var attributesCount = effect.getAttributesCount();
  12581. this._unbindVertexArrayObject();
  12582. this.unbindAllAttributes();
  12583. var offset = 0;
  12584. for (var index = 0; index < attributesCount; index++) {
  12585. if (index < vertexDeclaration.length) {
  12586. var order = effect.getAttributeLocation(index);
  12587. if (order >= 0) {
  12588. this._gl.enableVertexAttribArray(order);
  12589. this._vertexAttribArraysEnabled[order] = true;
  12590. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12591. }
  12592. offset += vertexDeclaration[index] * 4;
  12593. }
  12594. }
  12595. }
  12596. this._bindIndexBufferWithCache(indexBuffer);
  12597. };
  12598. Engine.prototype._unbindVertexArrayObject = function () {
  12599. if (!this._cachedVertexArrayObject) {
  12600. return;
  12601. }
  12602. this._cachedVertexArrayObject = null;
  12603. this._gl.bindVertexArray(null);
  12604. };
  12605. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12606. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12607. this._cachedVertexBuffers = vertexBuffers;
  12608. this._cachedEffectForVertexBuffers = effect;
  12609. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12610. }
  12611. this._bindIndexBufferWithCache(indexBuffer);
  12612. };
  12613. Engine.prototype.unbindInstanceAttributes = function () {
  12614. var boundBuffer;
  12615. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12616. var instancesBuffer = this._currentInstanceBuffers[i];
  12617. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12618. boundBuffer = instancesBuffer;
  12619. this.bindArrayBuffer(instancesBuffer);
  12620. }
  12621. var offsetLocation = this._currentInstanceLocations[i];
  12622. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12623. }
  12624. this._currentInstanceBuffers.length = 0;
  12625. this._currentInstanceLocations.length = 0;
  12626. };
  12627. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12628. this._gl.deleteVertexArray(vao);
  12629. };
  12630. Engine.prototype._releaseBuffer = function (buffer) {
  12631. buffer.references--;
  12632. if (buffer.references === 0) {
  12633. this._gl.deleteBuffer(buffer);
  12634. return true;
  12635. }
  12636. return false;
  12637. };
  12638. Engine.prototype.createInstancesBuffer = function (capacity) {
  12639. var buffer = this._gl.createBuffer();
  12640. if (!buffer) {
  12641. throw new Error("Unable to create instance buffer");
  12642. }
  12643. buffer.capacity = capacity;
  12644. this.bindArrayBuffer(buffer);
  12645. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12646. return buffer;
  12647. };
  12648. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12649. this._gl.deleteBuffer(buffer);
  12650. };
  12651. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12652. this.bindArrayBuffer(instancesBuffer);
  12653. if (data) {
  12654. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12655. }
  12656. if (offsetLocations[0].index !== undefined) {
  12657. var stride = 0;
  12658. for (var i = 0; i < offsetLocations.length; i++) {
  12659. var ai = offsetLocations[i];
  12660. stride += ai.attributeSize * 4;
  12661. }
  12662. for (var i = 0; i < offsetLocations.length; i++) {
  12663. var ai = offsetLocations[i];
  12664. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12665. this._gl.enableVertexAttribArray(ai.index);
  12666. this._vertexAttribArraysEnabled[ai.index] = true;
  12667. }
  12668. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12669. this._gl.vertexAttribDivisor(ai.index, 1);
  12670. this._currentInstanceLocations.push(ai.index);
  12671. this._currentInstanceBuffers.push(instancesBuffer);
  12672. }
  12673. }
  12674. else {
  12675. for (var index = 0; index < 4; index++) {
  12676. var offsetLocation = offsetLocations[index];
  12677. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12678. this._gl.enableVertexAttribArray(offsetLocation);
  12679. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12680. }
  12681. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12682. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12683. this._currentInstanceLocations.push(offsetLocation);
  12684. this._currentInstanceBuffers.push(instancesBuffer);
  12685. }
  12686. }
  12687. };
  12688. Engine.prototype.applyStates = function () {
  12689. this._depthCullingState.apply(this._gl);
  12690. this._stencilState.apply(this._gl);
  12691. this._alphaState.apply(this._gl);
  12692. };
  12693. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12694. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12695. };
  12696. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12697. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12698. };
  12699. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12700. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12701. };
  12702. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12703. // Apply states
  12704. this.applyStates();
  12705. this._drawCalls.addCount(1, false);
  12706. // Render
  12707. var drawMode = this._drawMode(fillMode);
  12708. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12709. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12710. if (instancesCount) {
  12711. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12712. }
  12713. else {
  12714. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12715. }
  12716. };
  12717. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12718. // Apply states
  12719. this.applyStates();
  12720. this._drawCalls.addCount(1, false);
  12721. var drawMode = this._drawMode(fillMode);
  12722. if (instancesCount) {
  12723. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12724. }
  12725. else {
  12726. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12727. }
  12728. };
  12729. Engine.prototype._drawMode = function (fillMode) {
  12730. switch (fillMode) {
  12731. // Triangle views
  12732. case BABYLON.Material.TriangleFillMode:
  12733. return this._gl.TRIANGLES;
  12734. case BABYLON.Material.PointFillMode:
  12735. return this._gl.POINTS;
  12736. case BABYLON.Material.WireFrameFillMode:
  12737. return this._gl.LINES;
  12738. // Draw modes
  12739. case BABYLON.Material.PointListDrawMode:
  12740. return this._gl.POINTS;
  12741. case BABYLON.Material.LineListDrawMode:
  12742. return this._gl.LINES;
  12743. case BABYLON.Material.LineLoopDrawMode:
  12744. return this._gl.LINE_LOOP;
  12745. case BABYLON.Material.LineStripDrawMode:
  12746. return this._gl.LINE_STRIP;
  12747. case BABYLON.Material.TriangleStripDrawMode:
  12748. return this._gl.TRIANGLE_STRIP;
  12749. case BABYLON.Material.TriangleFanDrawMode:
  12750. return this._gl.TRIANGLE_FAN;
  12751. default:
  12752. return this._gl.TRIANGLES;
  12753. }
  12754. };
  12755. // Shaders
  12756. Engine.prototype._releaseEffect = function (effect) {
  12757. if (this._compiledEffects[effect._key]) {
  12758. delete this._compiledEffects[effect._key];
  12759. this._deleteProgram(effect.getProgram());
  12760. }
  12761. };
  12762. Engine.prototype._deleteProgram = function (program) {
  12763. if (program) {
  12764. program.__SPECTOR_rebuildProgram = null;
  12765. if (program.transformFeedback) {
  12766. this.deleteTransformFeedback(program.transformFeedback);
  12767. program.transformFeedback = null;
  12768. }
  12769. this._gl.deleteProgram(program);
  12770. }
  12771. };
  12772. /**
  12773. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12774. * @param samplers An array of string used to represent textures
  12775. */
  12776. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12777. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12778. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12779. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12780. if (this._compiledEffects[name]) {
  12781. var compiledEffect = this._compiledEffects[name];
  12782. if (onCompiled && compiledEffect.isReady()) {
  12783. onCompiled(compiledEffect);
  12784. }
  12785. return compiledEffect;
  12786. }
  12787. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12788. effect._key = name;
  12789. this._compiledEffects[name] = effect;
  12790. return effect;
  12791. };
  12792. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12793. if (uniformsNames === void 0) { uniformsNames = []; }
  12794. if (samplers === void 0) { samplers = []; }
  12795. if (defines === void 0) { defines = ""; }
  12796. return this.createEffect({
  12797. vertex: "particles",
  12798. fragmentElement: fragmentName
  12799. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12800. };
  12801. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12802. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12803. context = context || this._gl;
  12804. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12805. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12806. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12807. };
  12808. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12809. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12810. context = context || this._gl;
  12811. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12812. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12813. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12814. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12815. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12816. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12817. return program;
  12818. };
  12819. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12820. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12821. var shaderProgram = context.createProgram();
  12822. if (!shaderProgram) {
  12823. throw new Error("Unable to create program");
  12824. }
  12825. context.attachShader(shaderProgram, vertexShader);
  12826. context.attachShader(shaderProgram, fragmentShader);
  12827. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12828. var transformFeedback = this.createTransformFeedback();
  12829. this.bindTransformFeedback(transformFeedback);
  12830. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12831. shaderProgram.transformFeedback = transformFeedback;
  12832. }
  12833. context.linkProgram(shaderProgram);
  12834. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12835. this.bindTransformFeedback(null);
  12836. }
  12837. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12838. if (!linked) {
  12839. context.validateProgram(shaderProgram);
  12840. var error = context.getProgramInfoLog(shaderProgram);
  12841. if (error) {
  12842. throw new Error(error);
  12843. }
  12844. }
  12845. context.deleteShader(vertexShader);
  12846. context.deleteShader(fragmentShader);
  12847. return shaderProgram;
  12848. };
  12849. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12850. var results = new Array();
  12851. for (var index = 0; index < uniformsNames.length; index++) {
  12852. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12853. }
  12854. return results;
  12855. };
  12856. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12857. var results = [];
  12858. for (var index = 0; index < attributesNames.length; index++) {
  12859. try {
  12860. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12861. }
  12862. catch (e) {
  12863. results.push(-1);
  12864. }
  12865. }
  12866. return results;
  12867. };
  12868. Engine.prototype.enableEffect = function (effect) {
  12869. if (!effect) {
  12870. return;
  12871. }
  12872. // Use program
  12873. this.bindSamplers(effect);
  12874. this._currentEffect = effect;
  12875. if (effect.onBind) {
  12876. effect.onBind(effect);
  12877. }
  12878. effect.onBindObservable.notifyObservers(effect);
  12879. };
  12880. Engine.prototype.setIntArray = function (uniform, array) {
  12881. if (!uniform)
  12882. return;
  12883. this._gl.uniform1iv(uniform, array);
  12884. };
  12885. Engine.prototype.setIntArray2 = function (uniform, array) {
  12886. if (!uniform || array.length % 2 !== 0)
  12887. return;
  12888. this._gl.uniform2iv(uniform, array);
  12889. };
  12890. Engine.prototype.setIntArray3 = function (uniform, array) {
  12891. if (!uniform || array.length % 3 !== 0)
  12892. return;
  12893. this._gl.uniform3iv(uniform, array);
  12894. };
  12895. Engine.prototype.setIntArray4 = function (uniform, array) {
  12896. if (!uniform || array.length % 4 !== 0)
  12897. return;
  12898. this._gl.uniform4iv(uniform, array);
  12899. };
  12900. Engine.prototype.setFloatArray = function (uniform, array) {
  12901. if (!uniform)
  12902. return;
  12903. this._gl.uniform1fv(uniform, array);
  12904. };
  12905. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12906. if (!uniform || array.length % 2 !== 0)
  12907. return;
  12908. this._gl.uniform2fv(uniform, array);
  12909. };
  12910. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12911. if (!uniform || array.length % 3 !== 0)
  12912. return;
  12913. this._gl.uniform3fv(uniform, array);
  12914. };
  12915. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12916. if (!uniform || array.length % 4 !== 0)
  12917. return;
  12918. this._gl.uniform4fv(uniform, array);
  12919. };
  12920. Engine.prototype.setArray = function (uniform, array) {
  12921. if (!uniform)
  12922. return;
  12923. this._gl.uniform1fv(uniform, array);
  12924. };
  12925. Engine.prototype.setArray2 = function (uniform, array) {
  12926. if (!uniform || array.length % 2 !== 0)
  12927. return;
  12928. this._gl.uniform2fv(uniform, array);
  12929. };
  12930. Engine.prototype.setArray3 = function (uniform, array) {
  12931. if (!uniform || array.length % 3 !== 0)
  12932. return;
  12933. this._gl.uniform3fv(uniform, array);
  12934. };
  12935. Engine.prototype.setArray4 = function (uniform, array) {
  12936. if (!uniform || array.length % 4 !== 0)
  12937. return;
  12938. this._gl.uniform4fv(uniform, array);
  12939. };
  12940. Engine.prototype.setMatrices = function (uniform, matrices) {
  12941. if (!uniform)
  12942. return;
  12943. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12944. };
  12945. Engine.prototype.setMatrix = function (uniform, matrix) {
  12946. if (!uniform)
  12947. return;
  12948. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12949. };
  12950. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12951. if (!uniform)
  12952. return;
  12953. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12954. };
  12955. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12956. if (!uniform)
  12957. return;
  12958. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12959. };
  12960. Engine.prototype.setInt = function (uniform, value) {
  12961. if (!uniform)
  12962. return;
  12963. this._gl.uniform1i(uniform, value);
  12964. };
  12965. Engine.prototype.setFloat = function (uniform, value) {
  12966. if (!uniform)
  12967. return;
  12968. this._gl.uniform1f(uniform, value);
  12969. };
  12970. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12971. if (!uniform)
  12972. return;
  12973. this._gl.uniform2f(uniform, x, y);
  12974. };
  12975. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12976. if (!uniform)
  12977. return;
  12978. this._gl.uniform3f(uniform, x, y, z);
  12979. };
  12980. Engine.prototype.setBool = function (uniform, bool) {
  12981. if (!uniform)
  12982. return;
  12983. this._gl.uniform1i(uniform, bool);
  12984. };
  12985. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12986. if (!uniform)
  12987. return;
  12988. this._gl.uniform4f(uniform, x, y, z, w);
  12989. };
  12990. Engine.prototype.setColor3 = function (uniform, color3) {
  12991. if (!uniform)
  12992. return;
  12993. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12994. };
  12995. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12996. if (!uniform)
  12997. return;
  12998. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12999. };
  13000. /**
  13001. * Sets a Color4 on a uniform variable
  13002. * @param uniform defines the uniform location
  13003. * @param color4 defines the value to be set
  13004. */
  13005. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13006. if (!uniform)
  13007. return;
  13008. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13009. };
  13010. // States
  13011. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13012. if (zOffset === void 0) { zOffset = 0; }
  13013. if (reverseSide === void 0) { reverseSide = false; }
  13014. // Culling
  13015. if (this._depthCullingState.cull !== culling || force) {
  13016. this._depthCullingState.cull = culling;
  13017. }
  13018. // Cull face
  13019. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13020. if (this._depthCullingState.cullFace !== cullFace || force) {
  13021. this._depthCullingState.cullFace = cullFace;
  13022. }
  13023. // Z offset
  13024. this.setZOffset(zOffset);
  13025. // Front face
  13026. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13027. if (this._depthCullingState.frontFace !== frontFace || force) {
  13028. this._depthCullingState.frontFace = frontFace;
  13029. }
  13030. };
  13031. Engine.prototype.setZOffset = function (value) {
  13032. this._depthCullingState.zOffset = value;
  13033. };
  13034. Engine.prototype.getZOffset = function () {
  13035. return this._depthCullingState.zOffset;
  13036. };
  13037. Engine.prototype.setDepthBuffer = function (enable) {
  13038. this._depthCullingState.depthTest = enable;
  13039. };
  13040. Engine.prototype.getDepthWrite = function () {
  13041. return this._depthCullingState.depthMask;
  13042. };
  13043. Engine.prototype.setDepthWrite = function (enable) {
  13044. this._depthCullingState.depthMask = enable;
  13045. };
  13046. Engine.prototype.setColorWrite = function (enable) {
  13047. this._gl.colorMask(enable, enable, enable, enable);
  13048. this._colorWrite = enable;
  13049. };
  13050. Engine.prototype.getColorWrite = function () {
  13051. return this._colorWrite;
  13052. };
  13053. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  13054. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  13055. };
  13056. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  13057. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  13058. if (this._alphaMode === mode) {
  13059. return;
  13060. }
  13061. switch (mode) {
  13062. case Engine.ALPHA_DISABLE:
  13063. this._alphaState.alphaBlend = false;
  13064. break;
  13065. case Engine.ALPHA_PREMULTIPLIED:
  13066. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13067. this._alphaState.alphaBlend = true;
  13068. break;
  13069. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  13070. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13071. this._alphaState.alphaBlend = true;
  13072. break;
  13073. case Engine.ALPHA_COMBINE:
  13074. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13075. this._alphaState.alphaBlend = true;
  13076. break;
  13077. case Engine.ALPHA_ONEONE:
  13078. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13079. this._alphaState.alphaBlend = true;
  13080. break;
  13081. case Engine.ALPHA_ADD:
  13082. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13083. this._alphaState.alphaBlend = true;
  13084. break;
  13085. case Engine.ALPHA_SUBTRACT:
  13086. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13087. this._alphaState.alphaBlend = true;
  13088. break;
  13089. case Engine.ALPHA_MULTIPLY:
  13090. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  13091. this._alphaState.alphaBlend = true;
  13092. break;
  13093. case Engine.ALPHA_MAXIMIZED:
  13094. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13095. this._alphaState.alphaBlend = true;
  13096. break;
  13097. case Engine.ALPHA_INTERPOLATE:
  13098. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  13099. this._alphaState.alphaBlend = true;
  13100. break;
  13101. case Engine.ALPHA_SCREENMODE:
  13102. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13103. this._alphaState.alphaBlend = true;
  13104. break;
  13105. }
  13106. if (!noDepthWriteChange) {
  13107. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13108. }
  13109. this._alphaMode = mode;
  13110. };
  13111. Engine.prototype.getAlphaMode = function () {
  13112. return this._alphaMode;
  13113. };
  13114. // Textures
  13115. Engine.prototype.wipeCaches = function (bruteForce) {
  13116. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13117. return;
  13118. }
  13119. this._currentEffect = null;
  13120. // 6/8/2017: deltakosh: Should not be required anymore.
  13121. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13122. if (bruteForce) {
  13123. this.resetTextureCache();
  13124. this._currentProgram = null;
  13125. this._stencilState.reset();
  13126. this._depthCullingState.reset();
  13127. this.setDepthFunctionToLessOrEqual();
  13128. this._alphaState.reset();
  13129. }
  13130. this._resetVertexBufferBinding();
  13131. this._cachedIndexBuffer = null;
  13132. this._cachedEffectForVertexBuffers = null;
  13133. this._unbindVertexArrayObject();
  13134. this.bindIndexBuffer(null);
  13135. };
  13136. /**
  13137. * Set the compressed texture format to use, based on the formats you have, and the formats
  13138. * supported by the hardware / browser.
  13139. *
  13140. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13141. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13142. * to API arguments needed to compressed textures. This puts the burden on the container
  13143. * generator to house the arcane code for determining these for current & future formats.
  13144. *
  13145. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13146. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13147. *
  13148. * Note: The result of this call is not taken into account when a texture is base64.
  13149. *
  13150. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13151. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13152. *
  13153. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13154. * @returns The extension selected.
  13155. */
  13156. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13157. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13158. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13159. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13160. return this._textureFormatInUse = this._texturesSupported[i];
  13161. }
  13162. }
  13163. }
  13164. // actively set format to nothing, to allow this to be called more than once
  13165. // and possibly fail the 2nd time
  13166. this._textureFormatInUse = null;
  13167. return null;
  13168. };
  13169. Engine.prototype._createTexture = function () {
  13170. var texture = this._gl.createTexture();
  13171. if (!texture) {
  13172. throw new Error("Unable to create texture");
  13173. }
  13174. return texture;
  13175. };
  13176. /**
  13177. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13178. * @param {string} urlArg- This contains one of the following:
  13179. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13180. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13181. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13182. *
  13183. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13184. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13185. * @param {Scene} scene- Needed for loading to the correct scene.
  13186. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13187. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13188. * @param {callback} onError- Optional callback to be called upon failure.
  13189. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13190. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13191. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13192. *
  13193. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13194. */
  13195. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13196. var _this = this;
  13197. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13198. if (onLoad === void 0) { onLoad = null; }
  13199. if (onError === void 0) { onError = null; }
  13200. if (buffer === void 0) { buffer = null; }
  13201. if (fallBack === void 0) { fallBack = null; }
  13202. if (format === void 0) { format = null; }
  13203. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13204. var fromData = url.substr(0, 5) === "data:";
  13205. var fromBlob = url.substr(0, 5) === "blob:";
  13206. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13207. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13208. // establish the file extension, if possible
  13209. var lastDot = url.lastIndexOf('.');
  13210. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13211. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13212. var isTGA = (extension.indexOf(".tga") === 0);
  13213. // determine if a ktx file should be substituted
  13214. var isKTX = false;
  13215. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13216. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13217. isKTX = true;
  13218. }
  13219. if (scene) {
  13220. scene._addPendingData(texture);
  13221. }
  13222. texture.url = url;
  13223. texture.generateMipMaps = !noMipmap;
  13224. texture.samplingMode = samplingMode;
  13225. texture.invertY = invertY;
  13226. if (!this._doNotHandleContextLost) {
  13227. // Keep a link to the buffer only if we plan to handle context lost
  13228. texture._buffer = buffer;
  13229. }
  13230. var onLoadObserver = null;
  13231. if (onLoad && !fallBack) {
  13232. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13233. }
  13234. if (!fallBack)
  13235. this._internalTexturesCache.push(texture);
  13236. var onerror = function (message, exception) {
  13237. if (scene) {
  13238. scene._removePendingData(texture);
  13239. }
  13240. if (onLoadObserver) {
  13241. texture.onLoadedObservable.remove(onLoadObserver);
  13242. }
  13243. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13244. if (isKTX) {
  13245. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13246. }
  13247. else if (BABYLON.Tools.UseFallbackTexture) {
  13248. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13249. }
  13250. if (onError) {
  13251. onError(message || "Unknown error", exception);
  13252. }
  13253. };
  13254. var callback = null;
  13255. // processing for non-image formats
  13256. if (isKTX || isTGA || isDDS) {
  13257. if (isKTX) {
  13258. callback = function (data) {
  13259. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13260. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13261. ktx.uploadLevels(_this._gl, !noMipmap);
  13262. return false;
  13263. }, samplingMode);
  13264. };
  13265. }
  13266. else if (isTGA) {
  13267. callback = function (arrayBuffer) {
  13268. var data = new Uint8Array(arrayBuffer);
  13269. var header = BABYLON.TGATools.GetTGAHeader(data);
  13270. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13271. BABYLON.TGATools.UploadContent(_this._gl, data);
  13272. return false;
  13273. }, samplingMode);
  13274. };
  13275. }
  13276. else if (isDDS) {
  13277. callback = function (data) {
  13278. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13279. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13280. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13281. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13282. return false;
  13283. }, samplingMode);
  13284. };
  13285. }
  13286. if (!buffer) {
  13287. this._loadFile(url, function (data) {
  13288. if (callback) {
  13289. callback(data);
  13290. }
  13291. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13292. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13293. });
  13294. }
  13295. else {
  13296. if (callback) {
  13297. callback(buffer);
  13298. }
  13299. }
  13300. // image format processing
  13301. }
  13302. else {
  13303. var onload = function (img) {
  13304. if (fromBlob && !_this._doNotHandleContextLost) {
  13305. // We need to store the image if we need to rebuild the texture
  13306. // in case of a webgl context lost
  13307. texture._buffer = img;
  13308. }
  13309. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13310. var gl = _this._gl;
  13311. var isPot = (img.width === potWidth && img.height === potHeight);
  13312. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13313. if (isPot) {
  13314. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13315. return false;
  13316. }
  13317. // Using shaders to rescale because canvas.drawImage is lossy
  13318. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13319. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13320. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13321. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13322. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13323. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13324. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13325. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13326. _this._releaseTexture(source);
  13327. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13328. continuationCallback();
  13329. });
  13330. return true;
  13331. }, samplingMode);
  13332. };
  13333. if (!fromData || isBase64)
  13334. if (buffer instanceof HTMLImageElement) {
  13335. onload(buffer);
  13336. }
  13337. else {
  13338. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13339. }
  13340. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13341. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13342. else
  13343. onload(buffer);
  13344. }
  13345. return texture;
  13346. };
  13347. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13348. var _this = this;
  13349. var rtt = this.createRenderTargetTexture({
  13350. width: destination.width,
  13351. height: destination.height,
  13352. }, {
  13353. generateMipMaps: false,
  13354. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13355. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13356. generateDepthBuffer: false,
  13357. generateStencilBuffer: false
  13358. });
  13359. if (!this._rescalePostProcess) {
  13360. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13361. }
  13362. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13363. _this._rescalePostProcess.onApply = function (effect) {
  13364. effect._bindTexture("textureSampler", source);
  13365. };
  13366. var hostingScene = scene;
  13367. if (!hostingScene) {
  13368. hostingScene = _this.scenes[_this.scenes.length - 1];
  13369. }
  13370. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13371. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13372. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13373. _this.unBindFramebuffer(rtt);
  13374. _this._releaseTexture(rtt);
  13375. if (onComplete) {
  13376. onComplete();
  13377. }
  13378. });
  13379. };
  13380. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13381. if (compression === void 0) { compression = null; }
  13382. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13383. if (!texture) {
  13384. return;
  13385. }
  13386. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13387. var internalFormat = this._getInternalFormat(format);
  13388. var textureType = this._getWebGLTextureType(type);
  13389. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13390. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13391. if (!this._doNotHandleContextLost) {
  13392. texture._bufferView = data;
  13393. texture.format = format;
  13394. texture.type = type;
  13395. texture.invertY = invertY;
  13396. texture._compression = compression;
  13397. }
  13398. if (texture.width % 4 !== 0) {
  13399. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13400. }
  13401. if (compression && data) {
  13402. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13403. }
  13404. else {
  13405. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13406. }
  13407. if (texture.generateMipMaps) {
  13408. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13409. }
  13410. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13411. // this.resetTextureCache();
  13412. texture.isReady = true;
  13413. };
  13414. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13415. if (compression === void 0) { compression = null; }
  13416. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13417. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13418. texture.baseWidth = width;
  13419. texture.baseHeight = height;
  13420. texture.width = width;
  13421. texture.height = height;
  13422. texture.format = format;
  13423. texture.generateMipMaps = generateMipMaps;
  13424. texture.samplingMode = samplingMode;
  13425. texture.invertY = invertY;
  13426. texture._compression = compression;
  13427. texture.type = type;
  13428. if (!this._doNotHandleContextLost) {
  13429. texture._bufferView = data;
  13430. }
  13431. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13432. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13433. // Filters
  13434. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13435. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13436. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13437. if (generateMipMaps) {
  13438. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13439. }
  13440. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13441. this._internalTexturesCache.push(texture);
  13442. return texture;
  13443. };
  13444. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13445. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13446. texture.baseWidth = width;
  13447. texture.baseHeight = height;
  13448. if (generateMipMaps) {
  13449. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13450. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13451. }
  13452. // this.resetTextureCache();
  13453. texture.width = width;
  13454. texture.height = height;
  13455. texture.isReady = false;
  13456. texture.generateMipMaps = generateMipMaps;
  13457. texture.samplingMode = samplingMode;
  13458. this.updateTextureSamplingMode(samplingMode, texture);
  13459. this._internalTexturesCache.push(texture);
  13460. return texture;
  13461. };
  13462. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13463. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13464. if (texture.isCube) {
  13465. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13466. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13467. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13468. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13469. }
  13470. else if (texture.is3D) {
  13471. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13472. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13473. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13474. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13475. }
  13476. else {
  13477. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13478. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13479. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13480. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13481. }
  13482. texture.samplingMode = samplingMode;
  13483. };
  13484. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13485. if (premulAlpha === void 0) { premulAlpha = false; }
  13486. if (!texture) {
  13487. return;
  13488. }
  13489. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13490. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13491. if (premulAlpha) {
  13492. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13493. }
  13494. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13495. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13496. if (texture.generateMipMaps) {
  13497. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13498. }
  13499. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13500. if (premulAlpha) {
  13501. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13502. }
  13503. texture.isReady = true;
  13504. };
  13505. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13506. if (!texture || texture._isDisabled) {
  13507. return;
  13508. }
  13509. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13510. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13511. try {
  13512. // Testing video texture support
  13513. if (this._videoTextureSupported === undefined) {
  13514. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13515. if (this._gl.getError() !== 0) {
  13516. this._videoTextureSupported = false;
  13517. }
  13518. else {
  13519. this._videoTextureSupported = true;
  13520. }
  13521. }
  13522. // Copy video through the current working canvas if video texture is not supported
  13523. if (!this._videoTextureSupported) {
  13524. if (!texture._workingCanvas) {
  13525. texture._workingCanvas = document.createElement("canvas");
  13526. var context = texture._workingCanvas.getContext("2d");
  13527. if (!context) {
  13528. throw new Error("Unable to get 2d context");
  13529. }
  13530. texture._workingContext = context;
  13531. texture._workingCanvas.width = texture.width;
  13532. texture._workingCanvas.height = texture.height;
  13533. }
  13534. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13535. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13536. }
  13537. else {
  13538. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13539. }
  13540. if (texture.generateMipMaps) {
  13541. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13542. }
  13543. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13544. // this.resetTextureCache();
  13545. texture.isReady = true;
  13546. }
  13547. catch (ex) {
  13548. // Something unexpected
  13549. // Let's disable the texture
  13550. texture._isDisabled = true;
  13551. }
  13552. };
  13553. /**
  13554. * Updates a depth texture Comparison Mode and Function.
  13555. * If the comparison Function is equal to 0, the mode will be set to none.
  13556. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13557. * @param texture The texture to set the comparison function for
  13558. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13559. */
  13560. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13561. if (this.webGLVersion === 1) {
  13562. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13563. return;
  13564. }
  13565. var gl = this._gl;
  13566. if (texture.isCube) {
  13567. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13568. if (comparisonFunction === 0) {
  13569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13571. }
  13572. else {
  13573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13575. }
  13576. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13577. }
  13578. else {
  13579. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13580. if (comparisonFunction === 0) {
  13581. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13582. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13583. }
  13584. else {
  13585. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13586. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13587. }
  13588. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13589. }
  13590. texture._comparisonFunction = comparisonFunction;
  13591. };
  13592. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13593. var width = size.width || size;
  13594. var height = size.height || size;
  13595. internalTexture.baseWidth = width;
  13596. internalTexture.baseHeight = height;
  13597. internalTexture.width = width;
  13598. internalTexture.height = height;
  13599. internalTexture.isReady = true;
  13600. internalTexture.samples = 1;
  13601. internalTexture.generateMipMaps = false;
  13602. internalTexture._generateDepthBuffer = true;
  13603. internalTexture._generateStencilBuffer = generateStencil;
  13604. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13605. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13606. internalTexture._comparisonFunction = comparisonFunction;
  13607. var gl = this._gl;
  13608. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13609. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13610. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13611. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13612. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13613. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13614. if (comparisonFunction === 0) {
  13615. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13616. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13617. }
  13618. else {
  13619. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13620. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13621. }
  13622. };
  13623. /**
  13624. * Creates a depth stencil texture.
  13625. * This is only available in WebGL 2 or with the depth texture extension available.
  13626. * @param size The size of face edge in the texture.
  13627. * @param options The options defining the texture.
  13628. * @returns The texture
  13629. */
  13630. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13631. if (options.isCube) {
  13632. var width = size.width || size;
  13633. return this._createDepthStencilCubeTexture(width, options);
  13634. }
  13635. else {
  13636. return this._createDepthStencilTexture(size, options);
  13637. }
  13638. };
  13639. /**
  13640. * Creates a depth stencil texture.
  13641. * This is only available in WebGL 2 or with the depth texture extension available.
  13642. * @param size The size of face edge in the texture.
  13643. * @param options The options defining the texture.
  13644. * @returns The texture
  13645. */
  13646. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13647. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13648. if (!this._caps.depthTextureExtension) {
  13649. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13650. return internalTexture;
  13651. }
  13652. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13653. var gl = this._gl;
  13654. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13655. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13656. if (this.webGLVersion > 1) {
  13657. if (internalOptions.generateStencil) {
  13658. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13659. }
  13660. else {
  13661. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13662. }
  13663. }
  13664. else {
  13665. if (internalOptions.generateStencil) {
  13666. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13667. }
  13668. else {
  13669. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13670. }
  13671. }
  13672. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13673. return internalTexture;
  13674. };
  13675. /**
  13676. * Creates a depth stencil cube texture.
  13677. * This is only available in WebGL 2.
  13678. * @param size The size of face edge in the cube texture.
  13679. * @param options The options defining the cube texture.
  13680. * @returns The cube texture
  13681. */
  13682. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13683. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13684. internalTexture.isCube = true;
  13685. if (this.webGLVersion === 1) {
  13686. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13687. return internalTexture;
  13688. }
  13689. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13690. var gl = this._gl;
  13691. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13692. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13693. // Create the depth/stencil buffer
  13694. for (var face = 0; face < 6; face++) {
  13695. if (internalOptions.generateStencil) {
  13696. 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);
  13697. }
  13698. else {
  13699. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13700. }
  13701. }
  13702. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13703. return internalTexture;
  13704. };
  13705. /**
  13706. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13707. * @param renderTarget The render target to set the frame buffer for
  13708. */
  13709. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13710. // Create the framebuffer
  13711. var internalTexture = renderTarget.getInternalTexture();
  13712. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13713. return;
  13714. }
  13715. var gl = this._gl;
  13716. var depthStencilTexture = renderTarget.depthStencilTexture;
  13717. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13718. if (depthStencilTexture.isCube) {
  13719. if (depthStencilTexture._generateStencilBuffer) {
  13720. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13721. }
  13722. else {
  13723. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13724. }
  13725. }
  13726. else {
  13727. if (depthStencilTexture._generateStencilBuffer) {
  13728. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13729. }
  13730. else {
  13731. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13732. }
  13733. }
  13734. this.bindUnboundFramebuffer(null);
  13735. };
  13736. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13737. var fullOptions = new RenderTargetCreationOptions();
  13738. if (options !== undefined && typeof options === "object") {
  13739. fullOptions.generateMipMaps = options.generateMipMaps;
  13740. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13741. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13742. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13743. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13744. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13745. }
  13746. else {
  13747. fullOptions.generateMipMaps = options;
  13748. fullOptions.generateDepthBuffer = true;
  13749. fullOptions.generateStencilBuffer = false;
  13750. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13751. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13752. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13753. }
  13754. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13755. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13756. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13757. }
  13758. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13759. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13760. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13761. }
  13762. var gl = this._gl;
  13763. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13764. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13765. var width = size.width || size;
  13766. var height = size.height || size;
  13767. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13768. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13769. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13770. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13771. }
  13772. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13773. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13774. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13775. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13776. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13777. // Create the framebuffer
  13778. var framebuffer = gl.createFramebuffer();
  13779. this.bindUnboundFramebuffer(framebuffer);
  13780. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13781. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13782. if (fullOptions.generateMipMaps) {
  13783. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13784. }
  13785. // Unbind
  13786. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13787. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13788. this.bindUnboundFramebuffer(null);
  13789. texture._framebuffer = framebuffer;
  13790. texture.baseWidth = width;
  13791. texture.baseHeight = height;
  13792. texture.width = width;
  13793. texture.height = height;
  13794. texture.isReady = true;
  13795. texture.samples = 1;
  13796. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13797. texture.samplingMode = fullOptions.samplingMode;
  13798. texture.type = fullOptions.type;
  13799. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13800. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13801. // this.resetTextureCache();
  13802. this._internalTexturesCache.push(texture);
  13803. return texture;
  13804. };
  13805. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13806. var generateMipMaps = false;
  13807. var generateDepthBuffer = true;
  13808. var generateStencilBuffer = false;
  13809. var generateDepthTexture = false;
  13810. var textureCount = 1;
  13811. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13812. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13813. var types = [], samplingModes = [];
  13814. if (options !== undefined) {
  13815. generateMipMaps = options.generateMipMaps;
  13816. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13817. generateStencilBuffer = options.generateStencilBuffer;
  13818. generateDepthTexture = options.generateDepthTexture;
  13819. textureCount = options.textureCount || 1;
  13820. if (options.types) {
  13821. types = options.types;
  13822. }
  13823. if (options.samplingModes) {
  13824. samplingModes = options.samplingModes;
  13825. }
  13826. }
  13827. var gl = this._gl;
  13828. // Create the framebuffer
  13829. var framebuffer = gl.createFramebuffer();
  13830. this.bindUnboundFramebuffer(framebuffer);
  13831. var width = size.width || size;
  13832. var height = size.height || size;
  13833. var textures = [];
  13834. var attachments = [];
  13835. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13836. for (var i = 0; i < textureCount; i++) {
  13837. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13838. var type = types[i] || defaultType;
  13839. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13840. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13841. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13842. }
  13843. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13844. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13845. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13846. }
  13847. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13848. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13849. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13850. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13851. }
  13852. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13853. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13854. textures.push(texture);
  13855. attachments.push(attachment);
  13856. gl.activeTexture(gl["TEXTURE" + i]);
  13857. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13858. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13859. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13860. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13861. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13862. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13863. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13864. if (generateMipMaps) {
  13865. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13866. }
  13867. // Unbind
  13868. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13869. texture._framebuffer = framebuffer;
  13870. texture._depthStencilBuffer = depthStencilBuffer;
  13871. texture.baseWidth = width;
  13872. texture.baseHeight = height;
  13873. texture.width = width;
  13874. texture.height = height;
  13875. texture.isReady = true;
  13876. texture.samples = 1;
  13877. texture.generateMipMaps = generateMipMaps;
  13878. texture.samplingMode = samplingMode;
  13879. texture.type = type;
  13880. texture._generateDepthBuffer = generateDepthBuffer;
  13881. texture._generateStencilBuffer = generateStencilBuffer;
  13882. texture._attachments = attachments;
  13883. this._internalTexturesCache.push(texture);
  13884. }
  13885. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13886. // Depth texture
  13887. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13888. gl.activeTexture(gl.TEXTURE0);
  13889. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13890. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13891. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13894. 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);
  13895. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13896. depthTexture._framebuffer = framebuffer;
  13897. depthTexture.baseWidth = width;
  13898. depthTexture.baseHeight = height;
  13899. depthTexture.width = width;
  13900. depthTexture.height = height;
  13901. depthTexture.isReady = true;
  13902. depthTexture.samples = 1;
  13903. depthTexture.generateMipMaps = generateMipMaps;
  13904. depthTexture.samplingMode = gl.NEAREST;
  13905. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13906. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13907. textures.push(depthTexture);
  13908. this._internalTexturesCache.push(depthTexture);
  13909. }
  13910. gl.drawBuffers(attachments);
  13911. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13912. this.bindUnboundFramebuffer(null);
  13913. this.resetTextureCache();
  13914. return textures;
  13915. };
  13916. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13917. if (samples === void 0) { samples = 1; }
  13918. var depthStencilBuffer = null;
  13919. var gl = this._gl;
  13920. // Create the depth/stencil buffer
  13921. if (generateStencilBuffer) {
  13922. depthStencilBuffer = gl.createRenderbuffer();
  13923. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13924. if (samples > 1) {
  13925. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13926. }
  13927. else {
  13928. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13929. }
  13930. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13931. }
  13932. else if (generateDepthBuffer) {
  13933. depthStencilBuffer = gl.createRenderbuffer();
  13934. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13935. if (samples > 1) {
  13936. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13937. }
  13938. else {
  13939. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13940. }
  13941. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13942. }
  13943. return depthStencilBuffer;
  13944. };
  13945. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13946. if (this.webGLVersion < 2 || !texture) {
  13947. return 1;
  13948. }
  13949. if (texture.samples === samples) {
  13950. return samples;
  13951. }
  13952. var gl = this._gl;
  13953. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13954. // Dispose previous render buffers
  13955. if (texture._depthStencilBuffer) {
  13956. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13957. texture._depthStencilBuffer = null;
  13958. }
  13959. if (texture._MSAAFramebuffer) {
  13960. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13961. texture._MSAAFramebuffer = null;
  13962. }
  13963. if (texture._MSAARenderBuffer) {
  13964. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13965. texture._MSAARenderBuffer = null;
  13966. }
  13967. if (samples > 1) {
  13968. var framebuffer = gl.createFramebuffer();
  13969. if (!framebuffer) {
  13970. throw new Error("Unable to create multi sampled framebuffer");
  13971. }
  13972. texture._MSAAFramebuffer = framebuffer;
  13973. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13974. var colorRenderbuffer = gl.createRenderbuffer();
  13975. if (!colorRenderbuffer) {
  13976. throw new Error("Unable to create multi sampled framebuffer");
  13977. }
  13978. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13979. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13980. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13981. texture._MSAARenderBuffer = colorRenderbuffer;
  13982. }
  13983. else {
  13984. this.bindUnboundFramebuffer(texture._framebuffer);
  13985. }
  13986. texture.samples = samples;
  13987. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13988. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13989. this.bindUnboundFramebuffer(null);
  13990. return samples;
  13991. };
  13992. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13993. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13994. return 1;
  13995. }
  13996. if (textures[0].samples === samples) {
  13997. return samples;
  13998. }
  13999. var gl = this._gl;
  14000. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  14001. // Dispose previous render buffers
  14002. if (textures[0]._depthStencilBuffer) {
  14003. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  14004. textures[0]._depthStencilBuffer = null;
  14005. }
  14006. if (textures[0]._MSAAFramebuffer) {
  14007. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  14008. textures[0]._MSAAFramebuffer = null;
  14009. }
  14010. for (var i = 0; i < textures.length; i++) {
  14011. if (textures[i]._MSAARenderBuffer) {
  14012. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  14013. textures[i]._MSAARenderBuffer = null;
  14014. }
  14015. }
  14016. if (samples > 1) {
  14017. var framebuffer = gl.createFramebuffer();
  14018. if (!framebuffer) {
  14019. throw new Error("Unable to create multi sampled framebuffer");
  14020. }
  14021. this.bindUnboundFramebuffer(framebuffer);
  14022. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  14023. var attachments = [];
  14024. for (var i = 0; i < textures.length; i++) {
  14025. var texture = textures[i];
  14026. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14027. var colorRenderbuffer = gl.createRenderbuffer();
  14028. if (!colorRenderbuffer) {
  14029. throw new Error("Unable to create multi sampled framebuffer");
  14030. }
  14031. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  14032. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14033. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  14034. texture._MSAAFramebuffer = framebuffer;
  14035. texture._MSAARenderBuffer = colorRenderbuffer;
  14036. texture.samples = samples;
  14037. texture._depthStencilBuffer = depthStencilBuffer;
  14038. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14039. attachments.push(attachment);
  14040. }
  14041. gl.drawBuffers(attachments);
  14042. }
  14043. else {
  14044. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  14045. }
  14046. this.bindUnboundFramebuffer(null);
  14047. return samples;
  14048. };
  14049. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  14050. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  14051. };
  14052. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  14053. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  14054. };
  14055. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  14056. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  14057. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  14058. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14059. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14060. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14061. }
  14062. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14063. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14064. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14065. }
  14066. var gl = this._gl;
  14067. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14068. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14069. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  14070. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14071. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14072. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  14073. }
  14074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14076. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14077. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14078. for (var face = 0; face < 6; face++) {
  14079. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14080. }
  14081. // Create the framebuffer
  14082. var framebuffer = gl.createFramebuffer();
  14083. this.bindUnboundFramebuffer(framebuffer);
  14084. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  14085. // MipMaps
  14086. if (fullOptions.generateMipMaps) {
  14087. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14088. }
  14089. // Unbind
  14090. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14091. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14092. this.bindUnboundFramebuffer(null);
  14093. texture._framebuffer = framebuffer;
  14094. texture.width = size;
  14095. texture.height = size;
  14096. texture.isReady = true;
  14097. texture.isCube = true;
  14098. texture.samples = 1;
  14099. texture.generateMipMaps = fullOptions.generateMipMaps;
  14100. texture.samplingMode = fullOptions.samplingMode;
  14101. texture.type = fullOptions.type;
  14102. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14103. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  14104. this._internalTexturesCache.push(texture);
  14105. return texture;
  14106. };
  14107. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14108. var _this = this;
  14109. if (onLoad === void 0) { onLoad = null; }
  14110. if (onError === void 0) { onError = null; }
  14111. if (forcedExtension === void 0) { forcedExtension = null; }
  14112. var callback = function (loadData) {
  14113. if (!loadData) {
  14114. if (onLoad) {
  14115. onLoad(null);
  14116. }
  14117. return;
  14118. }
  14119. var texture = loadData.texture;
  14120. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14121. texture._lodGenerationScale = scale;
  14122. texture._lodGenerationOffset = offset;
  14123. if (_this._caps.textureLOD) {
  14124. // Do not add extra process if texture lod is supported.
  14125. if (onLoad) {
  14126. onLoad(texture);
  14127. }
  14128. return;
  14129. }
  14130. var mipSlices = 3;
  14131. var gl = _this._gl;
  14132. var width = loadData.width;
  14133. if (!width) {
  14134. return;
  14135. }
  14136. var textures = [];
  14137. for (var i = 0; i < mipSlices; i++) {
  14138. //compute LOD from even spacing in smoothness (matching shader calculation)
  14139. var smoothness = i / (mipSlices - 1);
  14140. var roughness = 1 - smoothness;
  14141. var minLODIndex = offset; // roughness = 0
  14142. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14143. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14144. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14145. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14146. glTextureFromLod.isCube = true;
  14147. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14149. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14151. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14152. if (loadData.isDDS) {
  14153. var info = loadData.info;
  14154. var data = loadData.data;
  14155. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14156. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14157. }
  14158. else {
  14159. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14160. }
  14161. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14162. // Wrap in a base texture for easy binding.
  14163. var lodTexture = new BABYLON.BaseTexture(scene);
  14164. lodTexture.isCube = true;
  14165. lodTexture._texture = glTextureFromLod;
  14166. glTextureFromLod.isReady = true;
  14167. textures.push(lodTexture);
  14168. }
  14169. texture._lodTextureHigh = textures[2];
  14170. texture._lodTextureMid = textures[1];
  14171. texture._lodTextureLow = textures[0];
  14172. if (onLoad) {
  14173. onLoad(texture);
  14174. }
  14175. };
  14176. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14177. };
  14178. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14179. var _this = this;
  14180. if (onLoad === void 0) { onLoad = null; }
  14181. if (onError === void 0) { onError = null; }
  14182. if (forcedExtension === void 0) { forcedExtension = null; }
  14183. var gl = this._gl;
  14184. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14185. texture.isCube = true;
  14186. texture.url = rootUrl;
  14187. texture.generateMipMaps = !noMipmap;
  14188. if (!this._doNotHandleContextLost) {
  14189. texture._extension = forcedExtension;
  14190. texture._files = files;
  14191. }
  14192. var isKTX = false;
  14193. var isDDS = false;
  14194. var lastDot = rootUrl.lastIndexOf('.');
  14195. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14196. if (this._textureFormatInUse) {
  14197. extension = this._textureFormatInUse;
  14198. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14199. isKTX = true;
  14200. }
  14201. else {
  14202. isDDS = (extension === ".dds");
  14203. }
  14204. var onerror = function (request, exception) {
  14205. if (onError && request) {
  14206. onError(request.status + " " + request.statusText, exception);
  14207. }
  14208. };
  14209. if (isKTX) {
  14210. this._loadFile(rootUrl, function (data) {
  14211. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14212. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14213. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14214. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14215. ktx.uploadLevels(_this._gl, !noMipmap);
  14216. _this.setCubeMapTextureParams(gl, loadMipmap);
  14217. texture.width = ktx.pixelWidth;
  14218. texture.height = ktx.pixelHeight;
  14219. texture.isReady = true;
  14220. }, undefined, undefined, true, onerror);
  14221. }
  14222. else if (isDDS) {
  14223. if (files && files.length === 6) {
  14224. this._cascadeLoadFiles(scene, function (imgs) {
  14225. var info;
  14226. var loadMipmap = false;
  14227. var width = 0;
  14228. for (var index = 0; index < imgs.length; index++) {
  14229. var data = imgs[index];
  14230. info = BABYLON.DDSTools.GetDDSInfo(data);
  14231. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14232. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14233. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14234. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14235. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14236. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14237. }
  14238. texture.width = info.width;
  14239. texture.height = info.height;
  14240. texture.type = info.textureType;
  14241. width = info.width;
  14242. }
  14243. _this.setCubeMapTextureParams(gl, loadMipmap);
  14244. texture.isReady = true;
  14245. if (onLoad) {
  14246. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14247. }
  14248. }, files, onError);
  14249. }
  14250. else {
  14251. this._loadFile(rootUrl, function (data) {
  14252. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14253. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14254. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14255. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14256. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14257. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14258. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14259. }
  14260. _this.setCubeMapTextureParams(gl, loadMipmap);
  14261. texture.width = info.width;
  14262. texture.height = info.height;
  14263. texture.isReady = true;
  14264. texture.type = info.textureType;
  14265. if (onLoad) {
  14266. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14267. }
  14268. }, undefined, undefined, true, onerror);
  14269. }
  14270. }
  14271. else {
  14272. if (!files) {
  14273. throw new Error("Cannot load cubemap because files were not defined");
  14274. }
  14275. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14276. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14277. var height = width;
  14278. _this._prepareWorkingCanvas();
  14279. if (!_this._workingCanvas || !_this._workingContext) {
  14280. return;
  14281. }
  14282. _this._workingCanvas.width = width;
  14283. _this._workingCanvas.height = height;
  14284. var faces = [
  14285. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14286. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14287. ];
  14288. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14289. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14290. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14291. for (var index = 0; index < faces.length; index++) {
  14292. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14293. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14294. }
  14295. if (!noMipmap) {
  14296. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14297. }
  14298. _this.setCubeMapTextureParams(gl, !noMipmap);
  14299. texture.width = width;
  14300. texture.height = height;
  14301. texture.isReady = true;
  14302. if (format) {
  14303. texture.format = format;
  14304. }
  14305. texture.onLoadedObservable.notifyObservers(texture);
  14306. texture.onLoadedObservable.clear();
  14307. if (onLoad) {
  14308. onLoad();
  14309. }
  14310. }, files, onError);
  14311. }
  14312. this._internalTexturesCache.push(texture);
  14313. return texture;
  14314. };
  14315. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14316. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14317. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14318. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14319. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14320. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14321. // this.resetTextureCache();
  14322. };
  14323. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14324. if (compression === void 0) { compression = null; }
  14325. if (level === void 0) { level = 0; }
  14326. texture._bufferViewArray = data;
  14327. texture.format = format;
  14328. texture.type = type;
  14329. texture.invertY = invertY;
  14330. texture._compression = compression;
  14331. var gl = this._gl;
  14332. var textureType = this._getWebGLTextureType(type);
  14333. var internalFormat = this._getInternalFormat(format);
  14334. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14335. var needConversion = false;
  14336. if (internalFormat === gl.RGB) {
  14337. internalFormat = gl.RGBA;
  14338. needConversion = true;
  14339. }
  14340. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14341. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14342. if (texture.width % 4 !== 0) {
  14343. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14344. }
  14345. // Data are known to be in +X +Y +Z -X -Y -Z
  14346. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14347. var faceData = data[faceIndex];
  14348. if (compression) {
  14349. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14350. }
  14351. else {
  14352. if (needConversion) {
  14353. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14354. }
  14355. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14356. }
  14357. }
  14358. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14359. if (isPot && texture.generateMipMaps && level === 0) {
  14360. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14361. }
  14362. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14363. // this.resetTextureCache();
  14364. texture.isReady = true;
  14365. };
  14366. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14367. if (compression === void 0) { compression = null; }
  14368. var gl = this._gl;
  14369. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14370. texture.isCube = true;
  14371. texture.generateMipMaps = generateMipMaps;
  14372. texture.format = format;
  14373. texture.type = type;
  14374. if (!this._doNotHandleContextLost) {
  14375. texture._bufferViewArray = data;
  14376. }
  14377. var textureType = this._getWebGLTextureType(type);
  14378. var internalFormat = this._getInternalFormat(format);
  14379. if (internalFormat === gl.RGB) {
  14380. internalFormat = gl.RGBA;
  14381. }
  14382. var width = size;
  14383. var height = width;
  14384. texture.width = width;
  14385. texture.height = height;
  14386. // Double check on POT to generate Mips.
  14387. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14388. if (!isPot) {
  14389. generateMipMaps = false;
  14390. }
  14391. // Upload data if needed. The texture won't be ready until then.
  14392. if (data) {
  14393. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14394. }
  14395. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14396. // Filters
  14397. if (data && generateMipMaps) {
  14398. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14399. }
  14400. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14401. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14402. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14403. }
  14404. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14405. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14406. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14407. }
  14408. else {
  14409. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14410. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14411. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14412. }
  14413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14414. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14415. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14416. return texture;
  14417. };
  14418. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14419. var _this = this;
  14420. if (onLoad === void 0) { onLoad = null; }
  14421. if (onError === void 0) { onError = null; }
  14422. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14423. if (invertY === void 0) { invertY = false; }
  14424. var gl = this._gl;
  14425. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14426. scene._addPendingData(texture);
  14427. texture.url = url;
  14428. this._internalTexturesCache.push(texture);
  14429. var onerror = function (request, exception) {
  14430. scene._removePendingData(texture);
  14431. if (onError && request) {
  14432. onError(request.status + " " + request.statusText, exception);
  14433. }
  14434. };
  14435. var internalCallback = function (data) {
  14436. var width = texture.width;
  14437. var faceDataArrays = callback(data);
  14438. if (!faceDataArrays) {
  14439. return;
  14440. }
  14441. if (mipmmapGenerator) {
  14442. var textureType = _this._getWebGLTextureType(type);
  14443. var internalFormat = _this._getInternalFormat(format);
  14444. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14445. var needConversion = false;
  14446. if (internalFormat === gl.RGB) {
  14447. internalFormat = gl.RGBA;
  14448. needConversion = true;
  14449. }
  14450. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14451. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14452. var mipData = mipmmapGenerator(faceDataArrays);
  14453. for (var level = 0; level < mipData.length; level++) {
  14454. var mipSize = width >> level;
  14455. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14456. var mipFaceData = mipData[level][faceIndex];
  14457. if (needConversion) {
  14458. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14459. }
  14460. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14461. }
  14462. }
  14463. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14464. }
  14465. else {
  14466. texture.generateMipMaps = !noMipmap;
  14467. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14468. }
  14469. texture.isReady = true;
  14470. // this.resetTextureCache();
  14471. scene._removePendingData(texture);
  14472. if (onLoad) {
  14473. onLoad();
  14474. }
  14475. };
  14476. this._loadFile(url, function (data) {
  14477. internalCallback(data);
  14478. }, undefined, scene.database, true, onerror);
  14479. return texture;
  14480. };
  14481. ;
  14482. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14483. if (compression === void 0) { compression = null; }
  14484. var internalFormat = this._getInternalFormat(format);
  14485. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14486. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14487. if (!this._doNotHandleContextLost) {
  14488. texture._bufferView = data;
  14489. texture.format = format;
  14490. texture.invertY = invertY;
  14491. texture._compression = compression;
  14492. }
  14493. if (texture.width % 4 !== 0) {
  14494. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14495. }
  14496. if (compression && data) {
  14497. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14498. }
  14499. else {
  14500. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14501. }
  14502. if (texture.generateMipMaps) {
  14503. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14504. }
  14505. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14506. // this.resetTextureCache();
  14507. texture.isReady = true;
  14508. };
  14509. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14510. if (compression === void 0) { compression = null; }
  14511. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14512. texture.baseWidth = width;
  14513. texture.baseHeight = height;
  14514. texture.baseDepth = depth;
  14515. texture.width = width;
  14516. texture.height = height;
  14517. texture.depth = depth;
  14518. texture.format = format;
  14519. texture.generateMipMaps = generateMipMaps;
  14520. texture.samplingMode = samplingMode;
  14521. texture.is3D = true;
  14522. if (!this._doNotHandleContextLost) {
  14523. texture._bufferView = data;
  14524. }
  14525. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14526. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14527. // Filters
  14528. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14529. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14530. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14531. if (generateMipMaps) {
  14532. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14533. }
  14534. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14535. this._internalTexturesCache.push(texture);
  14536. return texture;
  14537. };
  14538. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14539. var gl = this._gl;
  14540. if (!gl) {
  14541. return;
  14542. }
  14543. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14544. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14545. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14546. if (!noMipmap && !isCompressed) {
  14547. gl.generateMipmap(gl.TEXTURE_2D);
  14548. }
  14549. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14550. // this.resetTextureCache();
  14551. if (scene) {
  14552. scene._removePendingData(texture);
  14553. }
  14554. texture.onLoadedObservable.notifyObservers(texture);
  14555. texture.onLoadedObservable.clear();
  14556. };
  14557. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14558. var _this = this;
  14559. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14560. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14561. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14562. var gl = this._gl;
  14563. if (!gl) {
  14564. return;
  14565. }
  14566. if (!texture._webGLTexture) {
  14567. // this.resetTextureCache();
  14568. if (scene) {
  14569. scene._removePendingData(texture);
  14570. }
  14571. return;
  14572. }
  14573. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14574. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14575. texture.baseWidth = width;
  14576. texture.baseHeight = height;
  14577. texture.width = potWidth;
  14578. texture.height = potHeight;
  14579. texture.isReady = true;
  14580. if (processFunction(potWidth, potHeight, function () {
  14581. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14582. })) {
  14583. // Returning as texture needs extra async steps
  14584. return;
  14585. }
  14586. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14587. };
  14588. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14589. // Create new RGBA data container.
  14590. var rgbaData;
  14591. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14592. rgbaData = new Float32Array(width * height * 4);
  14593. }
  14594. else {
  14595. rgbaData = new Uint32Array(width * height * 4);
  14596. }
  14597. // Convert each pixel.
  14598. for (var x = 0; x < width; x++) {
  14599. for (var y = 0; y < height; y++) {
  14600. var index = (y * width + x) * 3;
  14601. var newIndex = (y * width + x) * 4;
  14602. // Map Old Value to new value.
  14603. rgbaData[newIndex + 0] = rgbData[index + 0];
  14604. rgbaData[newIndex + 1] = rgbData[index + 1];
  14605. rgbaData[newIndex + 2] = rgbData[index + 2];
  14606. // Add fully opaque alpha channel.
  14607. rgbaData[newIndex + 3] = 1;
  14608. }
  14609. }
  14610. return rgbaData;
  14611. };
  14612. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14613. var gl = this._gl;
  14614. if (texture._framebuffer) {
  14615. gl.deleteFramebuffer(texture._framebuffer);
  14616. texture._framebuffer = null;
  14617. }
  14618. if (texture._depthStencilBuffer) {
  14619. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14620. texture._depthStencilBuffer = null;
  14621. }
  14622. if (texture._MSAAFramebuffer) {
  14623. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14624. texture._MSAAFramebuffer = null;
  14625. }
  14626. if (texture._MSAARenderBuffer) {
  14627. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14628. texture._MSAARenderBuffer = null;
  14629. }
  14630. };
  14631. Engine.prototype._releaseTexture = function (texture) {
  14632. var gl = this._gl;
  14633. this._releaseFramebufferObjects(texture);
  14634. gl.deleteTexture(texture._webGLTexture);
  14635. // Unbind channels
  14636. this.unbindAllTextures();
  14637. var index = this._internalTexturesCache.indexOf(texture);
  14638. if (index !== -1) {
  14639. this._internalTexturesCache.splice(index, 1);
  14640. }
  14641. // Integrated fixed lod samplers.
  14642. if (texture._lodTextureHigh) {
  14643. texture._lodTextureHigh.dispose();
  14644. }
  14645. if (texture._lodTextureMid) {
  14646. texture._lodTextureMid.dispose();
  14647. }
  14648. if (texture._lodTextureLow) {
  14649. texture._lodTextureLow.dispose();
  14650. }
  14651. // Set output texture of post process to null if the texture has been released/disposed
  14652. this.scenes.forEach(function (scene) {
  14653. scene.postProcesses.forEach(function (postProcess) {
  14654. if (postProcess._outputTexture == texture) {
  14655. postProcess._outputTexture = null;
  14656. }
  14657. });
  14658. scene.cameras.forEach(function (camera) {
  14659. camera._postProcesses.forEach(function (postProcess) {
  14660. if (postProcess) {
  14661. if (postProcess._outputTexture == texture) {
  14662. postProcess._outputTexture = null;
  14663. }
  14664. }
  14665. });
  14666. });
  14667. });
  14668. };
  14669. Engine.prototype.setProgram = function (program) {
  14670. if (this._currentProgram !== program) {
  14671. this._gl.useProgram(program);
  14672. this._currentProgram = program;
  14673. }
  14674. };
  14675. Engine.prototype.bindSamplers = function (effect) {
  14676. this.setProgram(effect.getProgram());
  14677. var samplers = effect.getSamplers();
  14678. for (var index = 0; index < samplers.length; index++) {
  14679. var uniform = effect.getUniform(samplers[index]);
  14680. if (uniform) {
  14681. this._boundUniforms[index] = uniform;
  14682. }
  14683. }
  14684. this._currentEffect = null;
  14685. };
  14686. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14687. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14688. return;
  14689. }
  14690. // Remove
  14691. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14692. // Bind last to it
  14693. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14694. // Bind to dummy
  14695. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14696. };
  14697. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14698. if (!internalTexture) {
  14699. return -1;
  14700. }
  14701. internalTexture._initialSlot = channel;
  14702. if (this.disableTextureBindingOptimization) {
  14703. if (channel !== internalTexture._designatedSlot) {
  14704. this._textureCollisions.addCount(1, false);
  14705. }
  14706. }
  14707. else {
  14708. if (channel !== internalTexture._designatedSlot) {
  14709. if (internalTexture._designatedSlot > -1) {
  14710. return internalTexture._designatedSlot;
  14711. }
  14712. else {
  14713. // No slot for this texture, let's pick a new one (if we find a free slot)
  14714. if (this._nextFreeTextureSlots.length) {
  14715. return this._nextFreeTextureSlots[0];
  14716. }
  14717. // We need to recycle the oldest bound texture, sorry.
  14718. this._textureCollisions.addCount(1, false);
  14719. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14720. }
  14721. }
  14722. }
  14723. return channel;
  14724. };
  14725. Engine.prototype._linkTrackers = function (previous, next) {
  14726. previous.next = next;
  14727. next.previous = previous;
  14728. };
  14729. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14730. var currentSlot = internalTexture._designatedSlot;
  14731. if (currentSlot === -1) {
  14732. return -1;
  14733. }
  14734. internalTexture._designatedSlot = -1;
  14735. if (this.disableTextureBindingOptimization) {
  14736. return -1;
  14737. }
  14738. // Remove from bound list
  14739. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14740. // Free the slot
  14741. this._boundTexturesCache[currentSlot] = null;
  14742. this._nextFreeTextureSlots.push(currentSlot);
  14743. return currentSlot;
  14744. };
  14745. Engine.prototype._activateCurrentTexture = function () {
  14746. if (this._currentTextureChannel !== this._activeChannel) {
  14747. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14748. this._currentTextureChannel = this._activeChannel;
  14749. }
  14750. };
  14751. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14752. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14753. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14754. this._activeChannel = texture._designatedSlot;
  14755. }
  14756. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14757. var isTextureForRendering = texture && texture._initialSlot > -1;
  14758. if (currentTextureBound !== texture) {
  14759. if (currentTextureBound) {
  14760. this._removeDesignatedSlot(currentTextureBound);
  14761. }
  14762. this._activateCurrentTexture();
  14763. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14764. this._boundTexturesCache[this._activeChannel] = texture;
  14765. if (texture) {
  14766. if (!this.disableTextureBindingOptimization) {
  14767. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14768. if (slotIndex > -1) {
  14769. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14770. }
  14771. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14772. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14773. }
  14774. texture._designatedSlot = this._activeChannel;
  14775. }
  14776. }
  14777. else if (forTextureDataUpdate) {
  14778. this._activateCurrentTexture();
  14779. }
  14780. if (isTextureForRendering && !forTextureDataUpdate) {
  14781. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14782. }
  14783. };
  14784. Engine.prototype._bindTexture = function (channel, texture) {
  14785. if (channel < 0) {
  14786. return;
  14787. }
  14788. if (texture) {
  14789. channel = this._getCorrectTextureChannel(channel, texture);
  14790. }
  14791. this._activeChannel = channel;
  14792. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14793. };
  14794. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14795. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14796. };
  14797. /**
  14798. * Binds the output of the passed in post process to the texture channel specified
  14799. * @param channel The channel the texture should be bound to
  14800. * @param postProcess The post process which's output should be bound
  14801. */
  14802. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14803. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14804. };
  14805. Engine.prototype.unbindAllTextures = function () {
  14806. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14807. this._activeChannel = channel;
  14808. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14809. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14810. if (this.webGLVersion > 1) {
  14811. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14812. }
  14813. }
  14814. };
  14815. /**
  14816. * Sets a texture to the according uniform.
  14817. * @param channel The texture channel
  14818. * @param uniform The uniform to set
  14819. * @param texture The texture to apply
  14820. */
  14821. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14822. if (channel < 0) {
  14823. return;
  14824. }
  14825. if (uniform) {
  14826. this._boundUniforms[channel] = uniform;
  14827. }
  14828. this._setTexture(channel, texture);
  14829. };
  14830. /**
  14831. * Sets a depth stencil texture from a render target to the according uniform.
  14832. * @param channel The texture channel
  14833. * @param uniform The uniform to set
  14834. * @param texture The render target texture containing the depth stencil texture to apply
  14835. */
  14836. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14837. if (channel < 0) {
  14838. return;
  14839. }
  14840. if (uniform) {
  14841. this._boundUniforms[channel] = uniform;
  14842. }
  14843. if (!texture || !texture.depthStencilTexture) {
  14844. this._setTexture(channel, null);
  14845. }
  14846. else {
  14847. this._setTexture(channel, texture, false, true);
  14848. }
  14849. };
  14850. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14851. var uniform = this._boundUniforms[sourceSlot];
  14852. if (uniform._currentState === destination) {
  14853. return;
  14854. }
  14855. this._gl.uniform1i(uniform, destination);
  14856. uniform._currentState = destination;
  14857. };
  14858. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14859. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14860. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14861. // Not ready?
  14862. if (!texture) {
  14863. if (this._boundTexturesCache[channel] != null) {
  14864. this._activeChannel = channel;
  14865. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14866. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14867. if (this.webGLVersion > 1) {
  14868. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14869. }
  14870. }
  14871. return false;
  14872. }
  14873. // Video
  14874. if (texture.video) {
  14875. this._activeChannel = channel;
  14876. texture.update();
  14877. }
  14878. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14879. texture.delayLoad();
  14880. return false;
  14881. }
  14882. var internalTexture;
  14883. if (depthStencilTexture) {
  14884. internalTexture = texture.depthStencilTexture;
  14885. }
  14886. else if (texture.isReady()) {
  14887. internalTexture = texture.getInternalTexture();
  14888. }
  14889. else if (texture.isCube) {
  14890. internalTexture = this.emptyCubeTexture;
  14891. }
  14892. else if (texture.is3D) {
  14893. internalTexture = this.emptyTexture3D;
  14894. }
  14895. else {
  14896. internalTexture = this.emptyTexture;
  14897. }
  14898. if (!isPartOfTextureArray) {
  14899. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14900. }
  14901. if (this._boundTexturesCache[channel] === internalTexture) {
  14902. this._moveBoundTextureOnTop(internalTexture);
  14903. if (!isPartOfTextureArray) {
  14904. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14905. }
  14906. return false;
  14907. }
  14908. this._activeChannel = channel;
  14909. if (internalTexture && internalTexture.is3D) {
  14910. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14911. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14912. internalTexture._cachedWrapU = texture.wrapU;
  14913. switch (texture.wrapU) {
  14914. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14915. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14916. break;
  14917. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14918. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14919. break;
  14920. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14921. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14922. break;
  14923. }
  14924. }
  14925. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14926. internalTexture._cachedWrapV = texture.wrapV;
  14927. switch (texture.wrapV) {
  14928. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14929. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14930. break;
  14931. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14932. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14933. break;
  14934. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14935. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14936. break;
  14937. }
  14938. }
  14939. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14940. internalTexture._cachedWrapR = texture.wrapR;
  14941. switch (texture.wrapR) {
  14942. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14943. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14944. break;
  14945. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14946. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14947. break;
  14948. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14949. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14950. break;
  14951. }
  14952. }
  14953. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14954. }
  14955. else if (internalTexture && internalTexture.isCube) {
  14956. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14957. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14958. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14959. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14960. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14961. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14962. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14963. }
  14964. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14965. }
  14966. else {
  14967. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14968. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14969. internalTexture._cachedWrapU = texture.wrapU;
  14970. switch (texture.wrapU) {
  14971. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14972. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14973. break;
  14974. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14975. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14976. break;
  14977. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14978. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14979. break;
  14980. }
  14981. }
  14982. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14983. internalTexture._cachedWrapV = texture.wrapV;
  14984. switch (texture.wrapV) {
  14985. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14986. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14987. break;
  14988. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14989. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14990. break;
  14991. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14992. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14993. break;
  14994. }
  14995. }
  14996. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14997. }
  14998. return true;
  14999. };
  15000. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  15001. if (channel < 0 || !uniform) {
  15002. return;
  15003. }
  15004. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  15005. this._textureUnits = new Int32Array(textures.length);
  15006. }
  15007. for (var i = 0; i < textures.length; i++) {
  15008. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  15009. }
  15010. this._gl.uniform1iv(uniform, this._textureUnits);
  15011. for (var index = 0; index < textures.length; index++) {
  15012. this._setTexture(this._textureUnits[index], textures[index], true);
  15013. }
  15014. };
  15015. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  15016. var internalTexture = texture.getInternalTexture();
  15017. if (!internalTexture) {
  15018. return;
  15019. }
  15020. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  15021. var value = texture.anisotropicFilteringLevel;
  15022. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  15023. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  15024. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  15025. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  15026. }
  15027. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  15028. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  15029. internalTexture._cachedAnisotropicFilteringLevel = value;
  15030. }
  15031. };
  15032. Engine.prototype.readPixels = function (x, y, width, height) {
  15033. var data = new Uint8Array(height * width * 4);
  15034. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  15035. return data;
  15036. };
  15037. /**
  15038. * Add an externaly attached data from its key.
  15039. * This method call will fail and return false, if such key already exists.
  15040. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  15041. * @param key the unique key that identifies the data
  15042. * @param data the data object to associate to the key for this Engine instance
  15043. * @return true if no such key were already present and the data was added successfully, false otherwise
  15044. */
  15045. Engine.prototype.addExternalData = function (key, data) {
  15046. if (!this._externalData) {
  15047. this._externalData = new BABYLON.StringDictionary();
  15048. }
  15049. return this._externalData.add(key, data);
  15050. };
  15051. /**
  15052. * Get an externaly attached data from its key
  15053. * @param key the unique key that identifies the data
  15054. * @return the associated data, if present (can be null), or undefined if not present
  15055. */
  15056. Engine.prototype.getExternalData = function (key) {
  15057. if (!this._externalData) {
  15058. this._externalData = new BABYLON.StringDictionary();
  15059. }
  15060. return this._externalData.get(key);
  15061. };
  15062. /**
  15063. * Get an externaly attached data from its key, create it using a factory if it's not already present
  15064. * @param key the unique key that identifies the data
  15065. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  15066. * @return the associated data, can be null if the factory returned null.
  15067. */
  15068. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  15069. if (!this._externalData) {
  15070. this._externalData = new BABYLON.StringDictionary();
  15071. }
  15072. return this._externalData.getOrAddWithFactory(key, factory);
  15073. };
  15074. /**
  15075. * Remove an externaly attached data from the Engine instance
  15076. * @param key the unique key that identifies the data
  15077. * @return true if the data was successfully removed, false if it doesn't exist
  15078. */
  15079. Engine.prototype.removeExternalData = function (key) {
  15080. if (!this._externalData) {
  15081. this._externalData = new BABYLON.StringDictionary();
  15082. }
  15083. return this._externalData.remove(key);
  15084. };
  15085. Engine.prototype.unbindAllAttributes = function () {
  15086. if (this._mustWipeVertexAttributes) {
  15087. this._mustWipeVertexAttributes = false;
  15088. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  15089. this._gl.disableVertexAttribArray(i);
  15090. this._vertexAttribArraysEnabled[i] = false;
  15091. this._currentBufferPointers[i].active = false;
  15092. }
  15093. return;
  15094. }
  15095. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  15096. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  15097. continue;
  15098. }
  15099. this._gl.disableVertexAttribArray(i);
  15100. this._vertexAttribArraysEnabled[i] = false;
  15101. this._currentBufferPointers[i].active = false;
  15102. }
  15103. };
  15104. Engine.prototype.releaseEffects = function () {
  15105. for (var name in this._compiledEffects) {
  15106. this._deleteProgram(this._compiledEffects[name]._program);
  15107. }
  15108. this._compiledEffects = {};
  15109. };
  15110. // Dispose
  15111. Engine.prototype.dispose = function () {
  15112. this.hideLoadingUI();
  15113. this.stopRenderLoop();
  15114. // Release postProcesses
  15115. while (this.postProcesses.length) {
  15116. this.postProcesses[0].dispose();
  15117. }
  15118. // Empty texture
  15119. if (this._emptyTexture) {
  15120. this._releaseTexture(this._emptyTexture);
  15121. this._emptyTexture = null;
  15122. }
  15123. if (this._emptyCubeTexture) {
  15124. this._releaseTexture(this._emptyCubeTexture);
  15125. this._emptyCubeTexture = null;
  15126. }
  15127. // Rescale PP
  15128. if (this._rescalePostProcess) {
  15129. this._rescalePostProcess.dispose();
  15130. }
  15131. // Release scenes
  15132. while (this.scenes.length) {
  15133. this.scenes[0].dispose();
  15134. }
  15135. // Release audio engine
  15136. if (Engine.audioEngine) {
  15137. Engine.audioEngine.dispose();
  15138. }
  15139. // Release effects
  15140. this.releaseEffects();
  15141. // Unbind
  15142. this.unbindAllAttributes();
  15143. if (this._dummyFramebuffer) {
  15144. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15145. }
  15146. //WebVR
  15147. this.disableVR();
  15148. // Events
  15149. if (BABYLON.Tools.IsWindowObjectExist()) {
  15150. window.removeEventListener("blur", this._onBlur);
  15151. window.removeEventListener("focus", this._onFocus);
  15152. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15153. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15154. if (this._renderingCanvas) {
  15155. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15156. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15157. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15158. if (!this._doNotHandleContextLost) {
  15159. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15160. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15161. }
  15162. }
  15163. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15164. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15165. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15166. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15167. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15168. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15169. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15170. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15171. if (this._onVrDisplayConnect) {
  15172. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15173. if (this._onVrDisplayDisconnect) {
  15174. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15175. }
  15176. if (this._onVrDisplayPresentChange) {
  15177. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15178. }
  15179. this._onVrDisplayConnect = null;
  15180. this._onVrDisplayDisconnect = null;
  15181. }
  15182. }
  15183. // Remove from Instances
  15184. var index = Engine.Instances.indexOf(this);
  15185. if (index >= 0) {
  15186. Engine.Instances.splice(index, 1);
  15187. }
  15188. this._workingCanvas = null;
  15189. this._workingContext = null;
  15190. this._currentBufferPointers = [];
  15191. this._renderingCanvas = null;
  15192. this._currentProgram = null;
  15193. this._bindedRenderFunction = null;
  15194. this.onResizeObservable.clear();
  15195. this.onCanvasBlurObservable.clear();
  15196. this.onCanvasFocusObservable.clear();
  15197. this.onCanvasPointerOutObservable.clear();
  15198. this.onBeginFrameObservable.clear();
  15199. this.onEndFrameObservable.clear();
  15200. BABYLON.Effect.ResetCache();
  15201. // Abort active requests
  15202. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15203. var request = _a[_i];
  15204. request.abort();
  15205. }
  15206. };
  15207. // Loading screen
  15208. Engine.prototype.displayLoadingUI = function () {
  15209. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15210. return;
  15211. }
  15212. var loadingScreen = this.loadingScreen;
  15213. if (loadingScreen) {
  15214. loadingScreen.displayLoadingUI();
  15215. }
  15216. };
  15217. Engine.prototype.hideLoadingUI = function () {
  15218. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15219. return;
  15220. }
  15221. var loadingScreen = this.loadingScreen;
  15222. if (loadingScreen) {
  15223. loadingScreen.hideLoadingUI();
  15224. }
  15225. };
  15226. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15227. get: function () {
  15228. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15229. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15230. return this._loadingScreen;
  15231. },
  15232. set: function (loadingScreen) {
  15233. this._loadingScreen = loadingScreen;
  15234. },
  15235. enumerable: true,
  15236. configurable: true
  15237. });
  15238. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15239. set: function (text) {
  15240. this.loadingScreen.loadingUIText = text;
  15241. },
  15242. enumerable: true,
  15243. configurable: true
  15244. });
  15245. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15246. set: function (color) {
  15247. this.loadingScreen.loadingUIBackgroundColor = color;
  15248. },
  15249. enumerable: true,
  15250. configurable: true
  15251. });
  15252. Engine.prototype.attachContextLostEvent = function (callback) {
  15253. if (this._renderingCanvas) {
  15254. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15255. }
  15256. };
  15257. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15258. if (this._renderingCanvas) {
  15259. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15260. }
  15261. };
  15262. Engine.prototype.getVertexShaderSource = function (program) {
  15263. var shaders = this._gl.getAttachedShaders(program);
  15264. if (!shaders) {
  15265. return null;
  15266. }
  15267. return this._gl.getShaderSource(shaders[0]);
  15268. };
  15269. Engine.prototype.getFragmentShaderSource = function (program) {
  15270. var shaders = this._gl.getAttachedShaders(program);
  15271. if (!shaders) {
  15272. return null;
  15273. }
  15274. return this._gl.getShaderSource(shaders[1]);
  15275. };
  15276. Engine.prototype.getError = function () {
  15277. return this._gl.getError();
  15278. };
  15279. // FPS
  15280. Engine.prototype.getFps = function () {
  15281. return this._fps;
  15282. };
  15283. Engine.prototype.getDeltaTime = function () {
  15284. return this._deltaTime;
  15285. };
  15286. Engine.prototype._measureFps = function () {
  15287. this._performanceMonitor.sampleFrame();
  15288. this._fps = this._performanceMonitor.averageFPS;
  15289. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15290. };
  15291. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15292. if (faceIndex === void 0) { faceIndex = -1; }
  15293. var gl = this._gl;
  15294. if (!this._dummyFramebuffer) {
  15295. var dummy = gl.createFramebuffer();
  15296. if (!dummy) {
  15297. throw new Error("Unable to create dummy framebuffer");
  15298. }
  15299. this._dummyFramebuffer = dummy;
  15300. }
  15301. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15302. if (faceIndex > -1) {
  15303. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15304. }
  15305. else {
  15306. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15307. }
  15308. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15309. var buffer;
  15310. switch (readType) {
  15311. case gl.UNSIGNED_BYTE:
  15312. buffer = new Uint8Array(4 * width * height);
  15313. readType = gl.UNSIGNED_BYTE;
  15314. break;
  15315. default:
  15316. buffer = new Float32Array(4 * width * height);
  15317. readType = gl.FLOAT;
  15318. break;
  15319. }
  15320. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15321. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15322. return buffer;
  15323. };
  15324. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15325. if (this._webGLVersion > 1) {
  15326. return this._caps.colorBufferFloat;
  15327. }
  15328. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15329. };
  15330. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15331. if (this._webGLVersion > 1) {
  15332. return this._caps.colorBufferFloat;
  15333. }
  15334. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15335. };
  15336. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15337. Engine.prototype._canRenderToFramebuffer = function (type) {
  15338. var gl = this._gl;
  15339. //clear existing errors
  15340. while (gl.getError() !== gl.NO_ERROR) { }
  15341. var successful = true;
  15342. var texture = gl.createTexture();
  15343. gl.bindTexture(gl.TEXTURE_2D, texture);
  15344. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15345. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15346. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15347. var fb = gl.createFramebuffer();
  15348. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15349. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15350. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15351. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15352. successful = successful && (gl.getError() === gl.NO_ERROR);
  15353. //try render by clearing frame buffer's color buffer
  15354. if (successful) {
  15355. gl.clear(gl.COLOR_BUFFER_BIT);
  15356. successful = successful && (gl.getError() === gl.NO_ERROR);
  15357. }
  15358. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15359. if (successful) {
  15360. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15361. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15362. var readFormat = gl.RGBA;
  15363. var readType = gl.UNSIGNED_BYTE;
  15364. var buffer = new Uint8Array(4);
  15365. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15366. successful = successful && (gl.getError() === gl.NO_ERROR);
  15367. }
  15368. //clean up
  15369. gl.deleteTexture(texture);
  15370. gl.deleteFramebuffer(fb);
  15371. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15372. //clear accumulated errors
  15373. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15374. return successful;
  15375. };
  15376. Engine.prototype._getWebGLTextureType = function (type) {
  15377. if (type === Engine.TEXTURETYPE_FLOAT) {
  15378. return this._gl.FLOAT;
  15379. }
  15380. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15381. // Add Half Float Constant.
  15382. return this._gl.HALF_FLOAT_OES;
  15383. }
  15384. return this._gl.UNSIGNED_BYTE;
  15385. };
  15386. ;
  15387. Engine.prototype._getInternalFormat = function (format) {
  15388. var internalFormat = this._gl.RGBA;
  15389. switch (format) {
  15390. case Engine.TEXTUREFORMAT_ALPHA:
  15391. internalFormat = this._gl.ALPHA;
  15392. break;
  15393. case Engine.TEXTUREFORMAT_LUMINANCE:
  15394. internalFormat = this._gl.LUMINANCE;
  15395. break;
  15396. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15397. internalFormat = this._gl.LUMINANCE_ALPHA;
  15398. break;
  15399. case Engine.TEXTUREFORMAT_RGB:
  15400. case Engine.TEXTUREFORMAT_RGB32F:
  15401. internalFormat = this._gl.RGB;
  15402. break;
  15403. case Engine.TEXTUREFORMAT_RGBA:
  15404. case Engine.TEXTUREFORMAT_RGBA32F:
  15405. internalFormat = this._gl.RGBA;
  15406. break;
  15407. case Engine.TEXTUREFORMAT_R32F:
  15408. internalFormat = this._gl.RED;
  15409. break;
  15410. case Engine.TEXTUREFORMAT_RG32F:
  15411. internalFormat = this._gl.RG;
  15412. break;
  15413. }
  15414. return internalFormat;
  15415. };
  15416. /** @ignore */
  15417. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15418. if (this._webGLVersion === 1) {
  15419. if (format) {
  15420. switch (format) {
  15421. case Engine.TEXTUREFORMAT_LUMINANCE:
  15422. return this._gl.LUMINANCE;
  15423. }
  15424. }
  15425. return this._gl.RGBA;
  15426. }
  15427. if (type === Engine.TEXTURETYPE_FLOAT) {
  15428. if (format) {
  15429. switch (format) {
  15430. case Engine.TEXTUREFORMAT_R32F:
  15431. return this._gl.R32F;
  15432. case Engine.TEXTUREFORMAT_RG32F:
  15433. return this._gl.RG32F;
  15434. case Engine.TEXTUREFORMAT_RGB32F:
  15435. return this._gl.RGB32F;
  15436. }
  15437. }
  15438. return this._gl.RGBA32F;
  15439. }
  15440. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15441. return this._gl.RGBA16F;
  15442. }
  15443. if (format) {
  15444. switch (format) {
  15445. case Engine.TEXTUREFORMAT_LUMINANCE:
  15446. return this._gl.LUMINANCE;
  15447. }
  15448. }
  15449. return this._gl.RGBA;
  15450. };
  15451. ;
  15452. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15453. if (type === Engine.TEXTURETYPE_FLOAT) {
  15454. return this._gl.RGBA32F;
  15455. }
  15456. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15457. return this._gl.RGBA16F;
  15458. }
  15459. return this._gl.RGBA8;
  15460. };
  15461. ;
  15462. Engine.prototype.createQuery = function () {
  15463. return this._gl.createQuery();
  15464. };
  15465. Engine.prototype.deleteQuery = function (query) {
  15466. this._gl.deleteQuery(query);
  15467. return this;
  15468. };
  15469. Engine.prototype.isQueryResultAvailable = function (query) {
  15470. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15471. };
  15472. Engine.prototype.getQueryResult = function (query) {
  15473. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15474. };
  15475. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15476. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15477. this._gl.beginQuery(glAlgorithm, query);
  15478. return this;
  15479. };
  15480. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15481. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15482. this._gl.endQuery(glAlgorithm);
  15483. return this;
  15484. };
  15485. /* Time queries */
  15486. Engine.prototype._createTimeQuery = function () {
  15487. var timerQuery = this._caps.timerQuery;
  15488. if (timerQuery.createQueryEXT) {
  15489. return timerQuery.createQueryEXT();
  15490. }
  15491. return this.createQuery();
  15492. };
  15493. Engine.prototype._deleteTimeQuery = function (query) {
  15494. var timerQuery = this._caps.timerQuery;
  15495. if (timerQuery.deleteQueryEXT) {
  15496. timerQuery.deleteQueryEXT(query);
  15497. return;
  15498. }
  15499. this.deleteQuery(query);
  15500. };
  15501. Engine.prototype._getTimeQueryResult = function (query) {
  15502. var timerQuery = this._caps.timerQuery;
  15503. if (timerQuery.getQueryObjectEXT) {
  15504. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15505. }
  15506. return this.getQueryResult(query);
  15507. };
  15508. Engine.prototype._getTimeQueryAvailability = function (query) {
  15509. var timerQuery = this._caps.timerQuery;
  15510. if (timerQuery.getQueryObjectEXT) {
  15511. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15512. }
  15513. return this.isQueryResultAvailable(query);
  15514. };
  15515. Engine.prototype.startTimeQuery = function () {
  15516. var timerQuery = this._caps.timerQuery;
  15517. if (!timerQuery) {
  15518. return null;
  15519. }
  15520. var token = new BABYLON._TimeToken();
  15521. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15522. if (this._caps.canUseTimestampForTimerQuery) {
  15523. token._startTimeQuery = this._createTimeQuery();
  15524. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15525. }
  15526. else {
  15527. if (this._currentNonTimestampToken) {
  15528. return this._currentNonTimestampToken;
  15529. }
  15530. token._timeElapsedQuery = this._createTimeQuery();
  15531. if (timerQuery.beginQueryEXT) {
  15532. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15533. }
  15534. else {
  15535. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15536. }
  15537. this._currentNonTimestampToken = token;
  15538. }
  15539. return token;
  15540. };
  15541. Engine.prototype.endTimeQuery = function (token) {
  15542. var timerQuery = this._caps.timerQuery;
  15543. if (!timerQuery || !token) {
  15544. return -1;
  15545. }
  15546. if (this._caps.canUseTimestampForTimerQuery) {
  15547. if (!token._startTimeQuery) {
  15548. return -1;
  15549. }
  15550. if (!token._endTimeQuery) {
  15551. token._endTimeQuery = this._createTimeQuery();
  15552. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15553. }
  15554. }
  15555. else if (!token._timeElapsedQueryEnded) {
  15556. if (!token._timeElapsedQuery) {
  15557. return -1;
  15558. }
  15559. if (timerQuery.endQueryEXT) {
  15560. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15561. }
  15562. else {
  15563. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15564. }
  15565. token._timeElapsedQueryEnded = true;
  15566. }
  15567. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15568. var available = false;
  15569. if (token._endTimeQuery) {
  15570. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15571. }
  15572. else if (token._timeElapsedQuery) {
  15573. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15574. }
  15575. if (available && !disjoint) {
  15576. var result = 0;
  15577. if (this._caps.canUseTimestampForTimerQuery) {
  15578. if (!token._startTimeQuery || !token._endTimeQuery) {
  15579. return -1;
  15580. }
  15581. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15582. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15583. result = timeEnd - timeStart;
  15584. this._deleteTimeQuery(token._startTimeQuery);
  15585. this._deleteTimeQuery(token._endTimeQuery);
  15586. token._startTimeQuery = null;
  15587. token._endTimeQuery = null;
  15588. }
  15589. else {
  15590. if (!token._timeElapsedQuery) {
  15591. return -1;
  15592. }
  15593. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15594. this._deleteTimeQuery(token._timeElapsedQuery);
  15595. token._timeElapsedQuery = null;
  15596. token._timeElapsedQueryEnded = false;
  15597. this._currentNonTimestampToken = null;
  15598. }
  15599. return result;
  15600. }
  15601. return -1;
  15602. };
  15603. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15604. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15605. };
  15606. // Transform feedback
  15607. Engine.prototype.createTransformFeedback = function () {
  15608. return this._gl.createTransformFeedback();
  15609. };
  15610. Engine.prototype.deleteTransformFeedback = function (value) {
  15611. this._gl.deleteTransformFeedback(value);
  15612. };
  15613. Engine.prototype.bindTransformFeedback = function (value) {
  15614. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15615. };
  15616. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15617. if (usePoints === void 0) { usePoints = true; }
  15618. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15619. };
  15620. Engine.prototype.endTransformFeedback = function () {
  15621. this._gl.endTransformFeedback();
  15622. };
  15623. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15624. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15625. };
  15626. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15627. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15628. };
  15629. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15630. var _this = this;
  15631. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15632. this._activeRequests.push(request);
  15633. request.onCompleteObservable.add(function (request) {
  15634. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15635. });
  15636. return request;
  15637. };
  15638. /** @ignore */
  15639. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15640. var _this = this;
  15641. return new Promise(function (resolve, reject) {
  15642. _this._loadFile(url, function (data) {
  15643. resolve(data);
  15644. }, undefined, database, useArrayBuffer, function (request, exception) {
  15645. reject(exception);
  15646. });
  15647. });
  15648. };
  15649. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15650. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15651. var onload = function (data) {
  15652. loadedFiles[index] = data;
  15653. loadedFiles._internalCount++;
  15654. if (loadedFiles._internalCount === 6) {
  15655. onfinish(loadedFiles);
  15656. }
  15657. };
  15658. var onerror = function (request, exception) {
  15659. if (onErrorCallBack && request) {
  15660. onErrorCallBack(request.status + " " + request.statusText, exception);
  15661. }
  15662. };
  15663. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15664. };
  15665. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15666. if (onError === void 0) { onError = null; }
  15667. var loadedFiles = [];
  15668. loadedFiles._internalCount = 0;
  15669. for (var index = 0; index < 6; index++) {
  15670. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15671. }
  15672. };
  15673. // Statics
  15674. Engine.isSupported = function () {
  15675. try {
  15676. var tempcanvas = document.createElement("canvas");
  15677. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15678. return gl != null && !!window.WebGLRenderingContext;
  15679. }
  15680. catch (e) {
  15681. return false;
  15682. }
  15683. };
  15684. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15685. Engine.ExceptionList = [
  15686. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15687. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15688. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15689. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15690. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15691. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15692. ];
  15693. Engine.Instances = new Array();
  15694. // Const statics
  15695. Engine._ALPHA_DISABLE = 0;
  15696. Engine._ALPHA_ADD = 1;
  15697. Engine._ALPHA_COMBINE = 2;
  15698. Engine._ALPHA_SUBTRACT = 3;
  15699. Engine._ALPHA_MULTIPLY = 4;
  15700. Engine._ALPHA_MAXIMIZED = 5;
  15701. Engine._ALPHA_ONEONE = 6;
  15702. Engine._ALPHA_PREMULTIPLIED = 7;
  15703. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15704. Engine._ALPHA_INTERPOLATE = 9;
  15705. Engine._ALPHA_SCREENMODE = 10;
  15706. Engine._DELAYLOADSTATE_NONE = 0;
  15707. Engine._DELAYLOADSTATE_LOADED = 1;
  15708. Engine._DELAYLOADSTATE_LOADING = 2;
  15709. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15710. Engine._TEXTUREFORMAT_ALPHA = 0;
  15711. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15712. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15713. Engine._TEXTUREFORMAT_RGB = 4;
  15714. Engine._TEXTUREFORMAT_RGBA = 5;
  15715. Engine._TEXTUREFORMAT_R32F = 6;
  15716. Engine._TEXTUREFORMAT_RG32F = 7;
  15717. Engine._TEXTUREFORMAT_RGB32F = 8;
  15718. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15719. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15720. Engine._TEXTURETYPE_FLOAT = 1;
  15721. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15722. // Depht or Stencil test Constants.
  15723. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15724. 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.
  15725. 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.
  15726. 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.
  15727. 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.
  15728. 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.
  15729. 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.
  15730. 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.
  15731. // Stencil Actions Constants.
  15732. Engine._KEEP = 0x1E00;
  15733. Engine._REPLACE = 0x1E01;
  15734. Engine._INCR = 0x1E02;
  15735. Engine._DECR = 0x1E03;
  15736. Engine._INVERT = 0x150A;
  15737. Engine._INCR_WRAP = 0x8507;
  15738. Engine._DECR_WRAP = 0x8508;
  15739. // Texture rescaling mode
  15740. Engine._SCALEMODE_FLOOR = 1;
  15741. Engine._SCALEMODE_NEAREST = 2;
  15742. Engine._SCALEMODE_CEILING = 3;
  15743. // Updatable statics so stick with vars here
  15744. Engine.CollisionsEpsilon = 0.001;
  15745. Engine.CodeRepository = "src/";
  15746. Engine.ShadersRepository = "src/Shaders/";
  15747. return Engine;
  15748. }());
  15749. BABYLON.Engine = Engine;
  15750. })(BABYLON || (BABYLON = {}));
  15751. //# sourceMappingURL=babylon.engine.js.map
  15752. "use strict";
  15753. var BABYLON;
  15754. (function (BABYLON) {
  15755. /**
  15756. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15757. */
  15758. var Node = /** @class */ (function () {
  15759. /**
  15760. * Creates a new Node
  15761. * @param {string} name - the name and id to be given to this node
  15762. * @param {BABYLON.Scene} the scene this node will be added to
  15763. */
  15764. function Node(name, scene) {
  15765. if (scene === void 0) { scene = null; }
  15766. /**
  15767. * Gets or sets a string used to store user defined state for the node
  15768. */
  15769. this.state = "";
  15770. /**
  15771. * Gets or sets an object used to store user defined information for the node
  15772. */
  15773. this.metadata = null;
  15774. /**
  15775. * Gets or sets a boolean used to define if the node must be serialized
  15776. */
  15777. this.doNotSerialize = false;
  15778. /** @ignore */
  15779. this._isDisposed = false;
  15780. /**
  15781. * Gets a list of {BABYLON.Animation} associated with the node
  15782. */
  15783. this.animations = new Array();
  15784. this._ranges = {};
  15785. this._isEnabled = true;
  15786. this._isReady = true;
  15787. /** @ignore */
  15788. this._currentRenderId = -1;
  15789. this._parentRenderId = -1;
  15790. this._animationPropertiesOverride = null;
  15791. /**
  15792. * An event triggered when the mesh is disposed
  15793. * @type {BABYLON.Observable}
  15794. */
  15795. this.onDisposeObservable = new BABYLON.Observable();
  15796. // Behaviors
  15797. this._behaviors = new Array();
  15798. this.name = name;
  15799. this.id = name;
  15800. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15801. this.uniqueId = this._scene.getUniqueId();
  15802. this._initCache();
  15803. }
  15804. /**
  15805. * Gets a boolean indicating if the node has been disposed
  15806. * @returns true if the node was disposed
  15807. */
  15808. Node.prototype.isDisposed = function () {
  15809. return this._isDisposed;
  15810. };
  15811. Object.defineProperty(Node.prototype, "parent", {
  15812. get: function () {
  15813. return this._parentNode;
  15814. },
  15815. /**
  15816. * Gets or sets the parent of the node
  15817. */
  15818. set: function (parent) {
  15819. if (this._parentNode === parent) {
  15820. return;
  15821. }
  15822. // Remove self from list of children of parent
  15823. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15824. var index = this._parentNode._children.indexOf(this);
  15825. if (index !== -1) {
  15826. this._parentNode._children.splice(index, 1);
  15827. }
  15828. }
  15829. // Store new parent
  15830. this._parentNode = parent;
  15831. // Add as child to new parent
  15832. if (this._parentNode) {
  15833. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15834. this._parentNode._children = new Array();
  15835. }
  15836. this._parentNode._children.push(this);
  15837. }
  15838. },
  15839. enumerable: true,
  15840. configurable: true
  15841. });
  15842. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15843. /**
  15844. * Gets or sets the animation properties override
  15845. */
  15846. get: function () {
  15847. return this._animationPropertiesOverride;
  15848. },
  15849. set: function (value) {
  15850. this._animationPropertiesOverride = value;
  15851. },
  15852. enumerable: true,
  15853. configurable: true
  15854. });
  15855. /**
  15856. * Gets a string idenfifying the name of the class
  15857. * @returns "Node" string
  15858. */
  15859. Node.prototype.getClassName = function () {
  15860. return "Node";
  15861. };
  15862. Object.defineProperty(Node.prototype, "onDispose", {
  15863. /**
  15864. * Sets a callback that will be raised when the node will be disposed
  15865. */
  15866. set: function (callback) {
  15867. if (this._onDisposeObserver) {
  15868. this.onDisposeObservable.remove(this._onDisposeObserver);
  15869. }
  15870. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15871. },
  15872. enumerable: true,
  15873. configurable: true
  15874. });
  15875. /**
  15876. * Gets the scene of the node
  15877. * @returns a {BABYLON.Scene}
  15878. */
  15879. Node.prototype.getScene = function () {
  15880. return this._scene;
  15881. };
  15882. /**
  15883. * Gets the engine of the node
  15884. * @returns a {BABYLON.Engine}
  15885. */
  15886. Node.prototype.getEngine = function () {
  15887. return this._scene.getEngine();
  15888. };
  15889. /**
  15890. * Attach a behavior to the node
  15891. * @see http://doc.babylonjs.com/features/behaviour
  15892. * @param behavior defines the behavior to attach
  15893. * @returns the current Node
  15894. */
  15895. Node.prototype.addBehavior = function (behavior) {
  15896. var _this = this;
  15897. var index = this._behaviors.indexOf(behavior);
  15898. if (index !== -1) {
  15899. return this;
  15900. }
  15901. behavior.init();
  15902. if (this._scene.isLoading) {
  15903. // We defer the attach when the scene will be loaded
  15904. var observer = this._scene.onDataLoadedObservable.add(function () {
  15905. behavior.attach(_this);
  15906. setTimeout(function () {
  15907. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15908. _this._scene.onDataLoadedObservable.remove(observer);
  15909. }, 0);
  15910. });
  15911. }
  15912. else {
  15913. behavior.attach(this);
  15914. }
  15915. this._behaviors.push(behavior);
  15916. return this;
  15917. };
  15918. /**
  15919. * Remove an attached behavior
  15920. * @see http://doc.babylonjs.com/features/behaviour
  15921. * @param behavior defines the behavior to attach
  15922. * @returns the current Node
  15923. */
  15924. Node.prototype.removeBehavior = function (behavior) {
  15925. var index = this._behaviors.indexOf(behavior);
  15926. if (index === -1) {
  15927. return this;
  15928. }
  15929. this._behaviors[index].detach();
  15930. this._behaviors.splice(index, 1);
  15931. return this;
  15932. };
  15933. Object.defineProperty(Node.prototype, "behaviors", {
  15934. /**
  15935. * Gets the list of attached behaviors
  15936. * @see http://doc.babylonjs.com/features/behaviour
  15937. */
  15938. get: function () {
  15939. return this._behaviors;
  15940. },
  15941. enumerable: true,
  15942. configurable: true
  15943. });
  15944. /**
  15945. * Gets an attached behavior by name
  15946. * @param name defines the name of the behavior to look for
  15947. * @see http://doc.babylonjs.com/features/behaviour
  15948. * @returns null if behavior was not found else the requested behavior
  15949. */
  15950. Node.prototype.getBehaviorByName = function (name) {
  15951. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15952. var behavior = _a[_i];
  15953. if (behavior.name === name) {
  15954. return behavior;
  15955. }
  15956. }
  15957. return null;
  15958. };
  15959. /**
  15960. * Returns the world matrix of the node
  15961. * @returns a matrix containing the node's world matrix
  15962. */
  15963. Node.prototype.getWorldMatrix = function () {
  15964. return BABYLON.Matrix.Identity();
  15965. };
  15966. // override it in derived class if you add new variables to the cache
  15967. // and call the parent class method
  15968. /** @ignore */
  15969. Node.prototype._initCache = function () {
  15970. this._cache = {};
  15971. this._cache.parent = undefined;
  15972. };
  15973. /** @ignore */
  15974. Node.prototype.updateCache = function (force) {
  15975. if (!force && this.isSynchronized())
  15976. return;
  15977. this._cache.parent = this.parent;
  15978. this._updateCache();
  15979. };
  15980. // override it in derived class if you add new variables to the cache
  15981. // and call the parent class method if !ignoreParentClass
  15982. /** @ignore */
  15983. Node.prototype._updateCache = function (ignoreParentClass) {
  15984. };
  15985. // override it in derived class if you add new variables to the cache
  15986. /** @ignore */
  15987. Node.prototype._isSynchronized = function () {
  15988. return true;
  15989. };
  15990. /** @ignore */
  15991. Node.prototype._markSyncedWithParent = function () {
  15992. if (this.parent) {
  15993. this._parentRenderId = this.parent._currentRenderId;
  15994. }
  15995. };
  15996. /** @ignore */
  15997. Node.prototype.isSynchronizedWithParent = function () {
  15998. if (!this.parent) {
  15999. return true;
  16000. }
  16001. if (this._parentRenderId !== this.parent._currentRenderId) {
  16002. return false;
  16003. }
  16004. return this.parent.isSynchronized();
  16005. };
  16006. /** @ignore */
  16007. Node.prototype.isSynchronized = function (updateCache) {
  16008. var check = this.hasNewParent();
  16009. check = check || !this.isSynchronizedWithParent();
  16010. check = check || !this._isSynchronized();
  16011. if (updateCache)
  16012. this.updateCache(true);
  16013. return !check;
  16014. };
  16015. /** @ignore */
  16016. Node.prototype.hasNewParent = function (update) {
  16017. if (this._cache.parent === this.parent)
  16018. return false;
  16019. if (update)
  16020. this._cache.parent = this.parent;
  16021. return true;
  16022. };
  16023. /**
  16024. * Is this node ready to be used/rendered
  16025. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  16026. * @return true if the node is ready
  16027. */
  16028. Node.prototype.isReady = function (completeCheck) {
  16029. if (completeCheck === void 0) { completeCheck = false; }
  16030. return this._isReady;
  16031. };
  16032. /**
  16033. * Is this node enabled?
  16034. * 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
  16035. * @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
  16036. * @return whether this node (and its parent) is enabled
  16037. * @see setEnabled
  16038. */
  16039. Node.prototype.isEnabled = function (checkAncestors) {
  16040. if (checkAncestors === void 0) { checkAncestors = true; }
  16041. if (checkAncestors === false) {
  16042. return this._isEnabled;
  16043. }
  16044. if (this._isEnabled === false) {
  16045. return false;
  16046. }
  16047. if (this.parent !== undefined && this.parent !== null) {
  16048. return this.parent.isEnabled(checkAncestors);
  16049. }
  16050. return true;
  16051. };
  16052. /**
  16053. * Set the enabled state of this node
  16054. * @param value defines the new enabled state
  16055. * @see isEnabled
  16056. */
  16057. Node.prototype.setEnabled = function (value) {
  16058. this._isEnabled = value;
  16059. };
  16060. /**
  16061. * Is this node a descendant of the given node?
  16062. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  16063. * @param ancestor defines the parent node to inspect
  16064. * @see parent
  16065. * @returns a boolean indicating if this node is a descendant of the given node
  16066. */
  16067. Node.prototype.isDescendantOf = function (ancestor) {
  16068. if (this.parent) {
  16069. if (this.parent === ancestor) {
  16070. return true;
  16071. }
  16072. return this.parent.isDescendantOf(ancestor);
  16073. }
  16074. return false;
  16075. };
  16076. /** @ignore */
  16077. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  16078. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  16079. if (!this._children) {
  16080. return;
  16081. }
  16082. for (var index = 0; index < this._children.length; index++) {
  16083. var item = this._children[index];
  16084. if (!predicate || predicate(item)) {
  16085. results.push(item);
  16086. }
  16087. if (!directDescendantsOnly) {
  16088. item._getDescendants(results, false, predicate);
  16089. }
  16090. }
  16091. };
  16092. /**
  16093. * Will return all nodes that have this node as ascendant
  16094. * @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
  16095. * @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
  16096. * @return all children nodes of all types
  16097. */
  16098. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  16099. var results = new Array();
  16100. this._getDescendants(results, directDescendantsOnly, predicate);
  16101. return results;
  16102. };
  16103. /**
  16104. * Get all child-meshes of this node
  16105. * @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
  16106. * @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
  16107. * @returns an array of {BABYLON.AbstractMesh}
  16108. */
  16109. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  16110. var results = [];
  16111. this._getDescendants(results, directDescendantsOnly, function (node) {
  16112. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  16113. });
  16114. return results;
  16115. };
  16116. /**
  16117. * Get all child-transformNodes of this node
  16118. * @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
  16119. * @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
  16120. * @returns an array of {BABYLON.TransformNode}
  16121. */
  16122. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  16123. var results = [];
  16124. this._getDescendants(results, directDescendantsOnly, function (node) {
  16125. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16126. });
  16127. return results;
  16128. };
  16129. /**
  16130. * Get all direct children of this node
  16131. * @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
  16132. * @returns an array of {BABYLON.Node}
  16133. */
  16134. Node.prototype.getChildren = function (predicate) {
  16135. return this.getDescendants(true, predicate);
  16136. };
  16137. /** @ignore */
  16138. Node.prototype._setReady = function (state) {
  16139. if (state === this._isReady) {
  16140. return;
  16141. }
  16142. if (!state) {
  16143. this._isReady = false;
  16144. return;
  16145. }
  16146. if (this.onReady) {
  16147. this.onReady(this);
  16148. }
  16149. this._isReady = true;
  16150. };
  16151. /**
  16152. * Get an animation by name
  16153. * @param name defines the name of the animation to look for
  16154. * @returns null if not found else the requested animation
  16155. */
  16156. Node.prototype.getAnimationByName = function (name) {
  16157. for (var i = 0; i < this.animations.length; i++) {
  16158. var animation = this.animations[i];
  16159. if (animation.name === name) {
  16160. return animation;
  16161. }
  16162. }
  16163. return null;
  16164. };
  16165. /**
  16166. * Creates an animation range for this node
  16167. * @param name defines the name of the range
  16168. * @param from defines the starting key
  16169. * @param to defines the end key
  16170. */
  16171. Node.prototype.createAnimationRange = function (name, from, to) {
  16172. // check name not already in use
  16173. if (!this._ranges[name]) {
  16174. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16175. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16176. if (this.animations[i]) {
  16177. this.animations[i].createRange(name, from, to);
  16178. }
  16179. }
  16180. }
  16181. };
  16182. /**
  16183. * Delete a specific animation range
  16184. * @param name defines the name of the range to delete
  16185. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16186. */
  16187. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16188. if (deleteFrames === void 0) { deleteFrames = true; }
  16189. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16190. if (this.animations[i]) {
  16191. this.animations[i].deleteRange(name, deleteFrames);
  16192. }
  16193. }
  16194. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16195. };
  16196. /**
  16197. * Get an animation range by name
  16198. * @param name defines the name of the animation range to look for
  16199. * @returns null if not found else the requested animation range
  16200. */
  16201. Node.prototype.getAnimationRange = function (name) {
  16202. return this._ranges[name];
  16203. };
  16204. /**
  16205. * Will start the animation sequence
  16206. * @param name defines the range frames for animation sequence
  16207. * @param loop defines if the animation should loop (false by default)
  16208. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16209. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16210. * @returns the object created for this animation. If range does not exist, it will return null
  16211. */
  16212. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16213. var range = this.getAnimationRange(name);
  16214. if (!range) {
  16215. return null;
  16216. }
  16217. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16218. };
  16219. /**
  16220. * Serialize animation ranges into a JSON compatible object
  16221. * @returns serialization object
  16222. */
  16223. Node.prototype.serializeAnimationRanges = function () {
  16224. var serializationRanges = [];
  16225. for (var name in this._ranges) {
  16226. var localRange = this._ranges[name];
  16227. if (!localRange) {
  16228. continue;
  16229. }
  16230. var range = {};
  16231. range.name = name;
  16232. range.from = localRange.from;
  16233. range.to = localRange.to;
  16234. serializationRanges.push(range);
  16235. }
  16236. return serializationRanges;
  16237. };
  16238. /**
  16239. * Computes the world matrix of the node
  16240. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16241. * @returns the world matrix
  16242. */
  16243. Node.prototype.computeWorldMatrix = function (force) {
  16244. return BABYLON.Matrix.Identity();
  16245. };
  16246. /**
  16247. * Releases resources associated with this node.
  16248. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16249. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16250. */
  16251. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16252. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16253. if (!doNotRecurse) {
  16254. var nodes = this.getDescendants(true);
  16255. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16256. var node = nodes_1[_i];
  16257. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16258. }
  16259. }
  16260. else {
  16261. var transformNodes = this.getChildTransformNodes(true);
  16262. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16263. var transformNode = transformNodes_1[_a];
  16264. transformNode.parent = null;
  16265. transformNode.computeWorldMatrix(true);
  16266. }
  16267. }
  16268. this.parent = null;
  16269. // Callback
  16270. this.onDisposeObservable.notifyObservers(this);
  16271. this.onDisposeObservable.clear();
  16272. // Behaviors
  16273. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16274. var behavior = _c[_b];
  16275. behavior.detach();
  16276. }
  16277. this._behaviors = [];
  16278. this._isDisposed = true;
  16279. };
  16280. /**
  16281. * Parse animation range data from a serialization object and store them into a given node
  16282. * @param node defines where to store the animation ranges
  16283. * @param parsedNode defines the serialization object to read data from
  16284. * @param scene defines the hosting scene
  16285. */
  16286. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16287. if (parsedNode.ranges) {
  16288. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16289. var data = parsedNode.ranges[index];
  16290. node.createAnimationRange(data.name, data.from, data.to);
  16291. }
  16292. }
  16293. };
  16294. __decorate([
  16295. BABYLON.serialize()
  16296. ], Node.prototype, "name", void 0);
  16297. __decorate([
  16298. BABYLON.serialize()
  16299. ], Node.prototype, "id", void 0);
  16300. __decorate([
  16301. BABYLON.serialize()
  16302. ], Node.prototype, "uniqueId", void 0);
  16303. __decorate([
  16304. BABYLON.serialize()
  16305. ], Node.prototype, "state", void 0);
  16306. __decorate([
  16307. BABYLON.serialize()
  16308. ], Node.prototype, "metadata", void 0);
  16309. return Node;
  16310. }());
  16311. BABYLON.Node = Node;
  16312. })(BABYLON || (BABYLON = {}));
  16313. //# sourceMappingURL=babylon.node.js.map
  16314. "use strict";
  16315. var BABYLON;
  16316. (function (BABYLON) {
  16317. var BoundingSphere = /** @class */ (function () {
  16318. function BoundingSphere(minimum, maximum) {
  16319. this.minimum = minimum;
  16320. this.maximum = maximum;
  16321. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16322. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16323. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16324. this.radius = distance * 0.5;
  16325. this.centerWorld = BABYLON.Vector3.Zero();
  16326. this._update(BABYLON.Matrix.Identity());
  16327. }
  16328. // Methods
  16329. BoundingSphere.prototype._update = function (world) {
  16330. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16331. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16332. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16333. };
  16334. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16335. for (var i = 0; i < 6; i++) {
  16336. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16337. return false;
  16338. }
  16339. return true;
  16340. };
  16341. BoundingSphere.prototype.intersectsPoint = function (point) {
  16342. var x = this.centerWorld.x - point.x;
  16343. var y = this.centerWorld.y - point.y;
  16344. var z = this.centerWorld.z - point.z;
  16345. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16346. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16347. return false;
  16348. return true;
  16349. };
  16350. // Statics
  16351. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16352. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16353. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16354. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16355. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16356. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16357. return false;
  16358. return true;
  16359. };
  16360. return BoundingSphere;
  16361. }());
  16362. BABYLON.BoundingSphere = BoundingSphere;
  16363. })(BABYLON || (BABYLON = {}));
  16364. //# sourceMappingURL=babylon.boundingSphere.js.map
  16365. "use strict";
  16366. var BABYLON;
  16367. (function (BABYLON) {
  16368. var BoundingBox = /** @class */ (function () {
  16369. function BoundingBox(minimum, maximum) {
  16370. this.minimum = minimum;
  16371. this.maximum = maximum;
  16372. this.vectors = new Array();
  16373. this.vectorsWorld = new Array();
  16374. // Bounding vectors
  16375. this.vectors.push(this.minimum.clone());
  16376. this.vectors.push(this.maximum.clone());
  16377. this.vectors.push(this.minimum.clone());
  16378. this.vectors[2].x = this.maximum.x;
  16379. this.vectors.push(this.minimum.clone());
  16380. this.vectors[3].y = this.maximum.y;
  16381. this.vectors.push(this.minimum.clone());
  16382. this.vectors[4].z = this.maximum.z;
  16383. this.vectors.push(this.maximum.clone());
  16384. this.vectors[5].z = this.minimum.z;
  16385. this.vectors.push(this.maximum.clone());
  16386. this.vectors[6].x = this.minimum.x;
  16387. this.vectors.push(this.maximum.clone());
  16388. this.vectors[7].y = this.minimum.y;
  16389. // OBB
  16390. this.center = this.maximum.add(this.minimum).scale(0.5);
  16391. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16392. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16393. // World
  16394. for (var index = 0; index < this.vectors.length; index++) {
  16395. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16396. }
  16397. this.minimumWorld = BABYLON.Vector3.Zero();
  16398. this.maximumWorld = BABYLON.Vector3.Zero();
  16399. this.centerWorld = BABYLON.Vector3.Zero();
  16400. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16401. this._update(BABYLON.Matrix.Identity());
  16402. }
  16403. // Methods
  16404. BoundingBox.prototype.getWorldMatrix = function () {
  16405. return this._worldMatrix;
  16406. };
  16407. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16408. this._worldMatrix.copyFrom(matrix);
  16409. return this;
  16410. };
  16411. BoundingBox.prototype._update = function (world) {
  16412. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16413. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16414. for (var index = 0; index < this.vectors.length; index++) {
  16415. var v = this.vectorsWorld[index];
  16416. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16417. if (v.x < this.minimumWorld.x)
  16418. this.minimumWorld.x = v.x;
  16419. if (v.y < this.minimumWorld.y)
  16420. this.minimumWorld.y = v.y;
  16421. if (v.z < this.minimumWorld.z)
  16422. this.minimumWorld.z = v.z;
  16423. if (v.x > this.maximumWorld.x)
  16424. this.maximumWorld.x = v.x;
  16425. if (v.y > this.maximumWorld.y)
  16426. this.maximumWorld.y = v.y;
  16427. if (v.z > this.maximumWorld.z)
  16428. this.maximumWorld.z = v.z;
  16429. }
  16430. // Extend
  16431. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16432. this.extendSizeWorld.scaleInPlace(0.5);
  16433. // OBB
  16434. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16435. this.centerWorld.scaleInPlace(0.5);
  16436. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16437. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16438. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16439. this._worldMatrix = world;
  16440. };
  16441. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16442. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16443. };
  16444. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16445. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16446. };
  16447. BoundingBox.prototype.intersectsPoint = function (point) {
  16448. var delta = -BABYLON.Epsilon;
  16449. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16450. return false;
  16451. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16452. return false;
  16453. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16454. return false;
  16455. return true;
  16456. };
  16457. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16458. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16459. };
  16460. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16461. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16462. return false;
  16463. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16464. return false;
  16465. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16466. return false;
  16467. return true;
  16468. };
  16469. // Statics
  16470. BoundingBox.Intersects = function (box0, box1) {
  16471. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16472. return false;
  16473. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16474. return false;
  16475. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16476. return false;
  16477. return true;
  16478. };
  16479. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16480. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16481. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16482. return (num <= (sphereRadius * sphereRadius));
  16483. };
  16484. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16485. for (var p = 0; p < 6; p++) {
  16486. for (var i = 0; i < 8; i++) {
  16487. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16488. return false;
  16489. }
  16490. }
  16491. }
  16492. return true;
  16493. };
  16494. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16495. for (var p = 0; p < 6; p++) {
  16496. var inCount = 8;
  16497. for (var i = 0; i < 8; i++) {
  16498. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16499. --inCount;
  16500. }
  16501. else {
  16502. break;
  16503. }
  16504. }
  16505. if (inCount === 0)
  16506. return false;
  16507. }
  16508. return true;
  16509. };
  16510. return BoundingBox;
  16511. }());
  16512. BABYLON.BoundingBox = BoundingBox;
  16513. })(BABYLON || (BABYLON = {}));
  16514. //# sourceMappingURL=babylon.boundingBox.js.map
  16515. "use strict";
  16516. var BABYLON;
  16517. (function (BABYLON) {
  16518. var computeBoxExtents = function (axis, box) {
  16519. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16520. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16521. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16522. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16523. var r = r0 + r1 + r2;
  16524. return {
  16525. min: p - r,
  16526. max: p + r
  16527. };
  16528. };
  16529. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16530. var axisOverlap = function (axis, box0, box1) {
  16531. var result0 = computeBoxExtents(axis, box0);
  16532. var result1 = computeBoxExtents(axis, box1);
  16533. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16534. };
  16535. var BoundingInfo = /** @class */ (function () {
  16536. function BoundingInfo(minimum, maximum) {
  16537. this.minimum = minimum;
  16538. this.maximum = maximum;
  16539. this._isLocked = false;
  16540. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16541. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16542. }
  16543. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16544. get: function () {
  16545. return this._isLocked;
  16546. },
  16547. set: function (value) {
  16548. this._isLocked = value;
  16549. },
  16550. enumerable: true,
  16551. configurable: true
  16552. });
  16553. // Methods
  16554. BoundingInfo.prototype.update = function (world) {
  16555. if (this._isLocked) {
  16556. return;
  16557. }
  16558. this.boundingBox._update(world);
  16559. this.boundingSphere._update(world);
  16560. };
  16561. /**
  16562. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16563. * @param center New center of the bounding info
  16564. * @param extend New extend of the bounding info
  16565. */
  16566. BoundingInfo.prototype.centerOn = function (center, extend) {
  16567. this.minimum = center.subtract(extend);
  16568. this.maximum = center.add(extend);
  16569. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16570. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16571. return this;
  16572. };
  16573. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16574. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16575. return false;
  16576. return this.boundingBox.isInFrustum(frustumPlanes);
  16577. };
  16578. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16579. /**
  16580. * Gets the world distance between the min and max points of the bounding box
  16581. */
  16582. get: function () {
  16583. var boundingBox = this.boundingBox;
  16584. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16585. return size.length();
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16591. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16592. };
  16593. BoundingInfo.prototype._checkCollision = function (collider) {
  16594. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16595. };
  16596. BoundingInfo.prototype.intersectsPoint = function (point) {
  16597. if (!this.boundingSphere.centerWorld) {
  16598. return false;
  16599. }
  16600. if (!this.boundingSphere.intersectsPoint(point)) {
  16601. return false;
  16602. }
  16603. if (!this.boundingBox.intersectsPoint(point)) {
  16604. return false;
  16605. }
  16606. return true;
  16607. };
  16608. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16609. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16610. return false;
  16611. }
  16612. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16613. return false;
  16614. }
  16615. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16616. return false;
  16617. }
  16618. if (!precise) {
  16619. return true;
  16620. }
  16621. var box0 = this.boundingBox;
  16622. var box1 = boundingInfo.boundingBox;
  16623. if (!axisOverlap(box0.directions[0], box0, box1))
  16624. return false;
  16625. if (!axisOverlap(box0.directions[1], box0, box1))
  16626. return false;
  16627. if (!axisOverlap(box0.directions[2], box0, box1))
  16628. return false;
  16629. if (!axisOverlap(box1.directions[0], box0, box1))
  16630. return false;
  16631. if (!axisOverlap(box1.directions[1], box0, box1))
  16632. return false;
  16633. if (!axisOverlap(box1.directions[2], box0, box1))
  16634. return false;
  16635. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16636. return false;
  16637. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16638. return false;
  16639. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16640. return false;
  16641. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16642. return false;
  16643. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16644. return false;
  16645. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16646. return false;
  16647. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16648. return false;
  16649. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16650. return false;
  16651. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16652. return false;
  16653. return true;
  16654. };
  16655. return BoundingInfo;
  16656. }());
  16657. BABYLON.BoundingInfo = BoundingInfo;
  16658. })(BABYLON || (BABYLON = {}));
  16659. //# sourceMappingURL=babylon.boundingInfo.js.map
  16660. "use strict";
  16661. var BABYLON;
  16662. (function (BABYLON) {
  16663. var TransformNode = /** @class */ (function (_super) {
  16664. __extends(TransformNode, _super);
  16665. function TransformNode(name, scene, isPure) {
  16666. if (scene === void 0) { scene = null; }
  16667. if (isPure === void 0) { isPure = true; }
  16668. var _this = _super.call(this, name, scene) || this;
  16669. // Properties
  16670. _this._rotation = BABYLON.Vector3.Zero();
  16671. _this._scaling = BABYLON.Vector3.One();
  16672. _this._isDirty = false;
  16673. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16674. _this.scalingDeterminant = 1;
  16675. _this.infiniteDistance = false;
  16676. _this.position = BABYLON.Vector3.Zero();
  16677. _this._localWorld = BABYLON.Matrix.Zero();
  16678. _this._worldMatrix = BABYLON.Matrix.Zero();
  16679. _this._worldMatrixDeterminant = 0;
  16680. _this._absolutePosition = BABYLON.Vector3.Zero();
  16681. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16682. _this._postMultiplyPivotMatrix = false;
  16683. _this._isWorldMatrixFrozen = false;
  16684. /**
  16685. * An event triggered after the world matrix is updated
  16686. * @type {BABYLON.Observable}
  16687. */
  16688. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16689. _this._nonUniformScaling = false;
  16690. if (isPure) {
  16691. _this.getScene().addTransformNode(_this);
  16692. }
  16693. return _this;
  16694. }
  16695. /**
  16696. * Gets a string idenfifying the name of the class
  16697. * @returns "TransformNode" string
  16698. */
  16699. TransformNode.prototype.getClassName = function () {
  16700. return "TransformNode";
  16701. };
  16702. Object.defineProperty(TransformNode.prototype, "rotation", {
  16703. /**
  16704. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16705. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16706. * Default : (0.0, 0.0, 0.0)
  16707. */
  16708. get: function () {
  16709. return this._rotation;
  16710. },
  16711. set: function (newRotation) {
  16712. this._rotation = newRotation;
  16713. },
  16714. enumerable: true,
  16715. configurable: true
  16716. });
  16717. Object.defineProperty(TransformNode.prototype, "scaling", {
  16718. /**
  16719. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16720. * Default : (1.0, 1.0, 1.0)
  16721. */
  16722. get: function () {
  16723. return this._scaling;
  16724. },
  16725. /**
  16726. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16727. * Default : (1.0, 1.0, 1.0)
  16728. */
  16729. set: function (newScaling) {
  16730. this._scaling = newScaling;
  16731. },
  16732. enumerable: true,
  16733. configurable: true
  16734. });
  16735. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16736. /**
  16737. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16738. * It's null by default.
  16739. * 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)
  16740. */
  16741. get: function () {
  16742. return this._rotationQuaternion;
  16743. },
  16744. set: function (quaternion) {
  16745. this._rotationQuaternion = quaternion;
  16746. //reset the rotation vector.
  16747. if (quaternion && this.rotation.length()) {
  16748. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16749. }
  16750. },
  16751. enumerable: true,
  16752. configurable: true
  16753. });
  16754. /**
  16755. * Returns the latest update of the World matrix
  16756. * Returns a Matrix.
  16757. */
  16758. TransformNode.prototype.getWorldMatrix = function () {
  16759. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16760. this.computeWorldMatrix();
  16761. }
  16762. return this._worldMatrix;
  16763. };
  16764. /**
  16765. * Returns the latest update of the World matrix determinant.
  16766. */
  16767. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16768. return this._worldMatrixDeterminant;
  16769. };
  16770. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16771. /**
  16772. * Returns directly the latest state of the mesh World matrix.
  16773. * A Matrix is returned.
  16774. */
  16775. get: function () {
  16776. return this._worldMatrix;
  16777. },
  16778. enumerable: true,
  16779. configurable: true
  16780. });
  16781. /**
  16782. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16783. * Returns the AbstractMesh.
  16784. */
  16785. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16786. this._poseMatrix.copyFrom(matrix);
  16787. return this;
  16788. };
  16789. /**
  16790. * Returns the mesh Pose matrix.
  16791. * Returned object : Matrix
  16792. */
  16793. TransformNode.prototype.getPoseMatrix = function () {
  16794. return this._poseMatrix;
  16795. };
  16796. TransformNode.prototype._isSynchronized = function () {
  16797. if (this._isDirty) {
  16798. return false;
  16799. }
  16800. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16801. return false;
  16802. if (this._cache.pivotMatrixUpdated) {
  16803. return false;
  16804. }
  16805. if (this.infiniteDistance) {
  16806. return false;
  16807. }
  16808. if (!this._cache.position.equals(this.position))
  16809. return false;
  16810. if (this.rotationQuaternion) {
  16811. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16812. return false;
  16813. }
  16814. if (!this._cache.rotation.equals(this.rotation))
  16815. return false;
  16816. if (!this._cache.scaling.equals(this.scaling))
  16817. return false;
  16818. return true;
  16819. };
  16820. TransformNode.prototype._initCache = function () {
  16821. _super.prototype._initCache.call(this);
  16822. this._cache.localMatrixUpdated = false;
  16823. this._cache.position = BABYLON.Vector3.Zero();
  16824. this._cache.scaling = BABYLON.Vector3.Zero();
  16825. this._cache.rotation = BABYLON.Vector3.Zero();
  16826. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16827. this._cache.billboardMode = -1;
  16828. };
  16829. TransformNode.prototype.markAsDirty = function (property) {
  16830. if (property === "rotation") {
  16831. this.rotationQuaternion = null;
  16832. }
  16833. this._currentRenderId = Number.MAX_VALUE;
  16834. this._isDirty = true;
  16835. return this;
  16836. };
  16837. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16838. /**
  16839. * Returns the current mesh absolute position.
  16840. * Retuns a Vector3.
  16841. */
  16842. get: function () {
  16843. return this._absolutePosition;
  16844. },
  16845. enumerable: true,
  16846. configurable: true
  16847. });
  16848. /**
  16849. * Sets a new matrix to apply before all other transformation
  16850. * @param matrix defines the transform matrix
  16851. * @returns the current TransformNode
  16852. */
  16853. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16854. return this.setPivotMatrix(matrix, false);
  16855. };
  16856. /**
  16857. * Sets a new pivot matrix to the current node
  16858. * @param matrix defines the new pivot matrix to use
  16859. * @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
  16860. * @returns the current TransformNode
  16861. */
  16862. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16863. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16864. this._pivotMatrix = matrix.clone();
  16865. this._cache.pivotMatrixUpdated = true;
  16866. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16867. if (this._postMultiplyPivotMatrix) {
  16868. if (!this._pivotMatrixInverse) {
  16869. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16870. }
  16871. else {
  16872. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16873. }
  16874. }
  16875. return this;
  16876. };
  16877. /**
  16878. * Returns the mesh pivot matrix.
  16879. * Default : Identity.
  16880. * A Matrix is returned.
  16881. */
  16882. TransformNode.prototype.getPivotMatrix = function () {
  16883. return this._pivotMatrix;
  16884. };
  16885. /**
  16886. * Prevents the World matrix to be computed any longer.
  16887. * Returns the AbstractMesh.
  16888. */
  16889. TransformNode.prototype.freezeWorldMatrix = function () {
  16890. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16891. this.computeWorldMatrix(true);
  16892. this._isWorldMatrixFrozen = true;
  16893. return this;
  16894. };
  16895. /**
  16896. * Allows back the World matrix computation.
  16897. * Returns the AbstractMesh.
  16898. */
  16899. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16900. this._isWorldMatrixFrozen = false;
  16901. this.computeWorldMatrix(true);
  16902. return this;
  16903. };
  16904. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16905. /**
  16906. * True if the World matrix has been frozen.
  16907. * Returns a boolean.
  16908. */
  16909. get: function () {
  16910. return this._isWorldMatrixFrozen;
  16911. },
  16912. enumerable: true,
  16913. configurable: true
  16914. });
  16915. /**
  16916. * Retuns the mesh absolute position in the World.
  16917. * Returns a Vector3.
  16918. */
  16919. TransformNode.prototype.getAbsolutePosition = function () {
  16920. this.computeWorldMatrix();
  16921. return this._absolutePosition;
  16922. };
  16923. /**
  16924. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16925. * Returns the AbstractMesh.
  16926. */
  16927. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16928. if (!absolutePosition) {
  16929. return this;
  16930. }
  16931. var absolutePositionX;
  16932. var absolutePositionY;
  16933. var absolutePositionZ;
  16934. if (absolutePosition.x === undefined) {
  16935. if (arguments.length < 3) {
  16936. return this;
  16937. }
  16938. absolutePositionX = arguments[0];
  16939. absolutePositionY = arguments[1];
  16940. absolutePositionZ = arguments[2];
  16941. }
  16942. else {
  16943. absolutePositionX = absolutePosition.x;
  16944. absolutePositionY = absolutePosition.y;
  16945. absolutePositionZ = absolutePosition.z;
  16946. }
  16947. if (this.parent) {
  16948. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16949. invertParentWorldMatrix.invert();
  16950. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16951. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16952. }
  16953. else {
  16954. this.position.x = absolutePositionX;
  16955. this.position.y = absolutePositionY;
  16956. this.position.z = absolutePositionZ;
  16957. }
  16958. return this;
  16959. };
  16960. /**
  16961. * Sets the mesh position in its local space.
  16962. * Returns the AbstractMesh.
  16963. */
  16964. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16965. this.computeWorldMatrix();
  16966. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16967. return this;
  16968. };
  16969. /**
  16970. * Returns the mesh position in the local space from the current World matrix values.
  16971. * Returns a new Vector3.
  16972. */
  16973. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16974. this.computeWorldMatrix();
  16975. var invLocalWorldMatrix = this._localWorld.clone();
  16976. invLocalWorldMatrix.invert();
  16977. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16978. };
  16979. /**
  16980. * Translates the mesh along the passed Vector3 in its local space.
  16981. * Returns the AbstractMesh.
  16982. */
  16983. TransformNode.prototype.locallyTranslate = function (vector3) {
  16984. this.computeWorldMatrix(true);
  16985. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16986. return this;
  16987. };
  16988. /**
  16989. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16990. * @param targetPoint the position (must be in same space as current mesh) to look at
  16991. * @param yawCor optional yaw (y-axis) correction in radians
  16992. * @param pitchCor optional pitch (x-axis) correction in radians
  16993. * @param rollCor optional roll (z-axis) correction in radians
  16994. * @param space the choosen space of the target
  16995. * @returns the TransformNode.
  16996. */
  16997. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16998. if (yawCor === void 0) { yawCor = 0; }
  16999. if (pitchCor === void 0) { pitchCor = 0; }
  17000. if (rollCor === void 0) { rollCor = 0; }
  17001. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  17002. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  17003. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  17004. targetPoint.subtractToRef(pos, dv);
  17005. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  17006. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  17007. var pitch = Math.atan2(dv.y, len);
  17008. if (this.rotationQuaternion) {
  17009. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  17010. }
  17011. else {
  17012. this.rotation.x = pitch + pitchCor;
  17013. this.rotation.y = yaw + yawCor;
  17014. this.rotation.z = rollCor;
  17015. }
  17016. return this;
  17017. };
  17018. /**
  17019. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  17020. * This Vector3 is expressed in the World space.
  17021. */
  17022. TransformNode.prototype.getDirection = function (localAxis) {
  17023. var result = BABYLON.Vector3.Zero();
  17024. this.getDirectionToRef(localAxis, result);
  17025. return result;
  17026. };
  17027. /**
  17028. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  17029. * localAxis is expressed in the mesh local space.
  17030. * result is computed in the Wordl space from the mesh World matrix.
  17031. * Returns the AbstractMesh.
  17032. */
  17033. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  17034. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17035. return this;
  17036. };
  17037. /**
  17038. * Sets a new pivot point to the current node
  17039. * @param point defines the new pivot point to use
  17040. * @param space defines if the point is in world or local space (local by default)
  17041. * @returns the current TransformNode
  17042. */
  17043. TransformNode.prototype.setPivotPoint = function (point, space) {
  17044. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  17045. if (this.getScene().getRenderId() == 0) {
  17046. this.computeWorldMatrix(true);
  17047. }
  17048. var wm = this.getWorldMatrix();
  17049. if (space == BABYLON.Space.WORLD) {
  17050. var tmat = BABYLON.Tmp.Matrix[0];
  17051. wm.invertToRef(tmat);
  17052. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  17053. }
  17054. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  17055. };
  17056. /**
  17057. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  17058. */
  17059. TransformNode.prototype.getPivotPoint = function () {
  17060. var point = BABYLON.Vector3.Zero();
  17061. this.getPivotPointToRef(point);
  17062. return point;
  17063. };
  17064. /**
  17065. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  17066. * Returns the AbstractMesh.
  17067. */
  17068. TransformNode.prototype.getPivotPointToRef = function (result) {
  17069. result.x = -this._pivotMatrix.m[12];
  17070. result.y = -this._pivotMatrix.m[13];
  17071. result.z = -this._pivotMatrix.m[14];
  17072. return this;
  17073. };
  17074. /**
  17075. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  17076. */
  17077. TransformNode.prototype.getAbsolutePivotPoint = function () {
  17078. var point = BABYLON.Vector3.Zero();
  17079. this.getAbsolutePivotPointToRef(point);
  17080. return point;
  17081. };
  17082. /**
  17083. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  17084. * Returns the AbstractMesh.
  17085. */
  17086. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  17087. result.x = this._pivotMatrix.m[12];
  17088. result.y = this._pivotMatrix.m[13];
  17089. result.z = this._pivotMatrix.m[14];
  17090. this.getPivotPointToRef(result);
  17091. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  17092. return this;
  17093. };
  17094. /**
  17095. * Defines the passed node as the parent of the current node.
  17096. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  17097. * Returns the TransformNode.
  17098. */
  17099. TransformNode.prototype.setParent = function (node) {
  17100. if (node === null) {
  17101. var rotation = BABYLON.Tmp.Quaternion[0];
  17102. var position = BABYLON.Tmp.Vector3[0];
  17103. var scale = BABYLON.Tmp.Vector3[1];
  17104. if (this.parent && this.parent.computeWorldMatrix) {
  17105. this.parent.computeWorldMatrix(true);
  17106. }
  17107. this.computeWorldMatrix(true);
  17108. this.getWorldMatrix().decompose(scale, rotation, position);
  17109. if (this.rotationQuaternion) {
  17110. this.rotationQuaternion.copyFrom(rotation);
  17111. }
  17112. else {
  17113. rotation.toEulerAnglesToRef(this.rotation);
  17114. }
  17115. this.scaling.x = scale.x;
  17116. this.scaling.y = scale.y;
  17117. this.scaling.z = scale.z;
  17118. this.position.x = position.x;
  17119. this.position.y = position.y;
  17120. this.position.z = position.z;
  17121. }
  17122. else {
  17123. var rotation = BABYLON.Tmp.Quaternion[0];
  17124. var position = BABYLON.Tmp.Vector3[0];
  17125. var scale = BABYLON.Tmp.Vector3[1];
  17126. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17127. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17128. this.computeWorldMatrix(true);
  17129. node.computeWorldMatrix(true);
  17130. node.getWorldMatrix().invertToRef(invParentMatrix);
  17131. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17132. diffMatrix.decompose(scale, rotation, position);
  17133. if (this.rotationQuaternion) {
  17134. this.rotationQuaternion.copyFrom(rotation);
  17135. }
  17136. else {
  17137. rotation.toEulerAnglesToRef(this.rotation);
  17138. }
  17139. this.position.x = position.x;
  17140. this.position.y = position.y;
  17141. this.position.z = position.z;
  17142. this.scaling.x = scale.x;
  17143. this.scaling.y = scale.y;
  17144. this.scaling.z = scale.z;
  17145. }
  17146. this.parent = node;
  17147. return this;
  17148. };
  17149. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17150. get: function () {
  17151. return this._nonUniformScaling;
  17152. },
  17153. enumerable: true,
  17154. configurable: true
  17155. });
  17156. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17157. if (this._nonUniformScaling === value) {
  17158. return false;
  17159. }
  17160. this._nonUniformScaling = true;
  17161. return true;
  17162. };
  17163. /**
  17164. * Attach the current TransformNode to another TransformNode associated with a bone
  17165. * @param bone Bone affecting the TransformNode
  17166. * @param affectedTransformNode TransformNode associated with the bone
  17167. */
  17168. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17169. this._transformToBoneReferal = affectedTransformNode;
  17170. this.parent = bone;
  17171. if (bone.getWorldMatrix().determinant() < 0) {
  17172. this.scalingDeterminant *= -1;
  17173. }
  17174. return this;
  17175. };
  17176. TransformNode.prototype.detachFromBone = function () {
  17177. if (!this.parent) {
  17178. return this;
  17179. }
  17180. if (this.parent.getWorldMatrix().determinant() < 0) {
  17181. this.scalingDeterminant *= -1;
  17182. }
  17183. this._transformToBoneReferal = null;
  17184. this.parent = null;
  17185. return this;
  17186. };
  17187. /**
  17188. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17189. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17190. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17191. * The passed axis is also normalized.
  17192. * Returns the AbstractMesh.
  17193. */
  17194. TransformNode.prototype.rotate = function (axis, amount, space) {
  17195. axis.normalize();
  17196. if (!this.rotationQuaternion) {
  17197. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17198. this.rotation = BABYLON.Vector3.Zero();
  17199. }
  17200. var rotationQuaternion;
  17201. if (!space || space === BABYLON.Space.LOCAL) {
  17202. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17203. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17204. }
  17205. else {
  17206. if (this.parent) {
  17207. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17208. invertParentWorldMatrix.invert();
  17209. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17210. }
  17211. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17212. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17213. }
  17214. return this;
  17215. };
  17216. /**
  17217. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17218. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17219. * The passed axis is also normalized.
  17220. * Returns the AbstractMesh.
  17221. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17222. */
  17223. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17224. axis.normalize();
  17225. if (!this.rotationQuaternion) {
  17226. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17227. this.rotation.copyFromFloats(0, 0, 0);
  17228. }
  17229. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17230. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17231. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17232. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17233. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17234. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17235. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17236. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17237. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17238. return this;
  17239. };
  17240. /**
  17241. * Translates the mesh along the axis vector for the passed distance in the given space.
  17242. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17243. * Returns the AbstractMesh.
  17244. */
  17245. TransformNode.prototype.translate = function (axis, distance, space) {
  17246. var displacementVector = axis.scale(distance);
  17247. if (!space || space === BABYLON.Space.LOCAL) {
  17248. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17249. this.setPositionWithLocalVector(tempV3);
  17250. }
  17251. else {
  17252. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17253. }
  17254. return this;
  17255. };
  17256. /**
  17257. * Adds a rotation step to the mesh current rotation.
  17258. * x, y, z are Euler angles expressed in radians.
  17259. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17260. * This means this rotation is made in the mesh local space only.
  17261. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17262. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17263. * ```javascript
  17264. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17265. * ```
  17266. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17267. * 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.
  17268. * Returns the AbstractMesh.
  17269. */
  17270. TransformNode.prototype.addRotation = function (x, y, z) {
  17271. var rotationQuaternion;
  17272. if (this.rotationQuaternion) {
  17273. rotationQuaternion = this.rotationQuaternion;
  17274. }
  17275. else {
  17276. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17277. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17278. }
  17279. var accumulation = BABYLON.Tmp.Quaternion[0];
  17280. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17281. rotationQuaternion.multiplyInPlace(accumulation);
  17282. if (!this.rotationQuaternion) {
  17283. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17284. }
  17285. return this;
  17286. };
  17287. /**
  17288. * Computes the mesh World matrix and returns it.
  17289. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17290. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17291. * If the parameter `force`is set to `true`, the actual computation is done.
  17292. * Returns the mesh World Matrix.
  17293. */
  17294. TransformNode.prototype.computeWorldMatrix = function (force) {
  17295. if (this._isWorldMatrixFrozen) {
  17296. return this._worldMatrix;
  17297. }
  17298. if (!force && this.isSynchronized(true)) {
  17299. return this._worldMatrix;
  17300. }
  17301. this._cache.position.copyFrom(this.position);
  17302. this._cache.scaling.copyFrom(this.scaling);
  17303. this._cache.pivotMatrixUpdated = false;
  17304. this._cache.billboardMode = this.billboardMode;
  17305. this._currentRenderId = this.getScene().getRenderId();
  17306. this._isDirty = false;
  17307. // Scaling
  17308. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17309. // Rotation
  17310. //rotate, if quaternion is set and rotation was used
  17311. if (this.rotationQuaternion) {
  17312. var len = this.rotation.length();
  17313. if (len) {
  17314. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17315. this.rotation.copyFromFloats(0, 0, 0);
  17316. }
  17317. }
  17318. if (this.rotationQuaternion) {
  17319. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17320. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17321. }
  17322. else {
  17323. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17324. this._cache.rotation.copyFrom(this.rotation);
  17325. }
  17326. // Translation
  17327. var camera = this.getScene().activeCamera;
  17328. if (this.infiniteDistance && !this.parent && camera) {
  17329. var cameraWorldMatrix = camera.getWorldMatrix();
  17330. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17331. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17332. }
  17333. else {
  17334. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17335. }
  17336. // Composing transformations
  17337. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17338. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17339. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17340. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17341. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17342. // Need to decompose each rotation here
  17343. var currentPosition = BABYLON.Tmp.Vector3[3];
  17344. if (this.parent && this.parent.getWorldMatrix) {
  17345. if (this._transformToBoneReferal) {
  17346. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17347. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17348. }
  17349. else {
  17350. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17351. }
  17352. }
  17353. else {
  17354. currentPosition.copyFrom(this.position);
  17355. }
  17356. currentPosition.subtractInPlace(camera.globalPosition);
  17357. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17358. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17359. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17360. }
  17361. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17362. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17363. }
  17364. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17365. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17366. }
  17367. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17368. }
  17369. else {
  17370. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17371. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17372. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17373. }
  17374. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17375. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17376. }
  17377. // Local world
  17378. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17379. // Parent
  17380. if (this.parent && this.parent.getWorldMatrix) {
  17381. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17382. if (this._transformToBoneReferal) {
  17383. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17384. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17385. }
  17386. else {
  17387. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17388. }
  17389. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17390. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17391. this._worldMatrix.copyFrom(this._localWorld);
  17392. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17393. }
  17394. else {
  17395. if (this._transformToBoneReferal) {
  17396. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17397. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17398. }
  17399. else {
  17400. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17401. }
  17402. }
  17403. this._markSyncedWithParent();
  17404. }
  17405. else {
  17406. this._worldMatrix.copyFrom(this._localWorld);
  17407. }
  17408. // Post multiply inverse of pivotMatrix
  17409. if (this._postMultiplyPivotMatrix) {
  17410. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17411. }
  17412. // Normal matrix
  17413. if (this.scaling.isNonUniform) {
  17414. this._updateNonUniformScalingState(true);
  17415. }
  17416. else if (this.parent && this.parent._nonUniformScaling) {
  17417. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17418. }
  17419. else {
  17420. this._updateNonUniformScalingState(false);
  17421. }
  17422. this._afterComputeWorldMatrix();
  17423. // Absolute position
  17424. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17425. // Callbacks
  17426. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17427. if (!this._poseMatrix) {
  17428. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17429. }
  17430. // Cache the determinant
  17431. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17432. return this._worldMatrix;
  17433. };
  17434. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17435. };
  17436. /**
  17437. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17438. * @param func: callback function to add
  17439. *
  17440. * Returns the TransformNode.
  17441. */
  17442. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17443. this.onAfterWorldMatrixUpdateObservable.add(func);
  17444. return this;
  17445. };
  17446. /**
  17447. * Removes a registered callback function.
  17448. * Returns the TransformNode.
  17449. */
  17450. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17451. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17452. return this;
  17453. };
  17454. /**
  17455. * Clone the current transform node
  17456. * Returns the new transform node
  17457. * @param name Name of the new clone
  17458. * @param newParent New parent for the clone
  17459. * @param doNotCloneChildren Do not clone children hierarchy
  17460. */
  17461. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17462. var _this = this;
  17463. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17464. result.name = name;
  17465. result.id = name;
  17466. if (newParent) {
  17467. result.parent = newParent;
  17468. }
  17469. if (!doNotCloneChildren) {
  17470. // Children
  17471. var directDescendants = this.getDescendants(true);
  17472. for (var index = 0; index < directDescendants.length; index++) {
  17473. var child = directDescendants[index];
  17474. if (child.clone) {
  17475. child.clone(name + "." + child.name, result);
  17476. }
  17477. }
  17478. }
  17479. return result;
  17480. };
  17481. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17482. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17483. serializationObject.type = this.getClassName();
  17484. // Parent
  17485. if (this.parent) {
  17486. serializationObject.parentId = this.parent.id;
  17487. }
  17488. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17489. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17490. }
  17491. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17492. serializationObject.isEnabled = this.isEnabled();
  17493. // Parent
  17494. if (this.parent) {
  17495. serializationObject.parentId = this.parent.id;
  17496. }
  17497. return serializationObject;
  17498. };
  17499. // Statics
  17500. /**
  17501. * Returns a new TransformNode object parsed from the source provided.
  17502. * The parameter `parsedMesh` is the source.
  17503. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17504. */
  17505. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17506. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17507. if (BABYLON.Tags) {
  17508. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17509. }
  17510. if (parsedTransformNode.localMatrix) {
  17511. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17512. }
  17513. else if (parsedTransformNode.pivotMatrix) {
  17514. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17515. }
  17516. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17517. // Parent
  17518. if (parsedTransformNode.parentId) {
  17519. transformNode._waitingParentId = parsedTransformNode.parentId;
  17520. }
  17521. return transformNode;
  17522. };
  17523. /**
  17524. * Releases resources associated with this transform node.
  17525. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17526. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17527. */
  17528. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17529. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17530. // Animations
  17531. this.getScene().stopAnimation(this);
  17532. // Remove from scene
  17533. this.getScene().removeTransformNode(this);
  17534. this.onAfterWorldMatrixUpdateObservable.clear();
  17535. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17536. };
  17537. // Statics
  17538. TransformNode.BILLBOARDMODE_NONE = 0;
  17539. TransformNode.BILLBOARDMODE_X = 1;
  17540. TransformNode.BILLBOARDMODE_Y = 2;
  17541. TransformNode.BILLBOARDMODE_Z = 4;
  17542. TransformNode.BILLBOARDMODE_ALL = 7;
  17543. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17544. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17545. __decorate([
  17546. BABYLON.serializeAsVector3()
  17547. ], TransformNode.prototype, "_rotation", void 0);
  17548. __decorate([
  17549. BABYLON.serializeAsQuaternion()
  17550. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17551. __decorate([
  17552. BABYLON.serializeAsVector3()
  17553. ], TransformNode.prototype, "_scaling", void 0);
  17554. __decorate([
  17555. BABYLON.serialize()
  17556. ], TransformNode.prototype, "billboardMode", void 0);
  17557. __decorate([
  17558. BABYLON.serialize()
  17559. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17560. __decorate([
  17561. BABYLON.serialize()
  17562. ], TransformNode.prototype, "infiniteDistance", void 0);
  17563. __decorate([
  17564. BABYLON.serializeAsVector3()
  17565. ], TransformNode.prototype, "position", void 0);
  17566. return TransformNode;
  17567. }(BABYLON.Node));
  17568. BABYLON.TransformNode = TransformNode;
  17569. })(BABYLON || (BABYLON = {}));
  17570. //# sourceMappingURL=babylon.transformNode.js.map
  17571. "use strict";
  17572. var BABYLON;
  17573. (function (BABYLON) {
  17574. var AbstractMesh = /** @class */ (function (_super) {
  17575. __extends(AbstractMesh, _super);
  17576. // Constructor
  17577. function AbstractMesh(name, scene) {
  17578. if (scene === void 0) { scene = null; }
  17579. var _this = _super.call(this, name, scene, false) || this;
  17580. _this._facetNb = 0; // facet number
  17581. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17582. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17583. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17584. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17585. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17586. _this._subDiv = {
  17587. max: 1,
  17588. X: 1,
  17589. Y: 1,
  17590. Z: 1
  17591. };
  17592. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17593. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17594. // Events
  17595. /**
  17596. * An event triggered when this mesh collides with another one
  17597. * @type {BABYLON.Observable}
  17598. */
  17599. _this.onCollideObservable = new BABYLON.Observable();
  17600. /**
  17601. * An event triggered when the collision's position changes
  17602. * @type {BABYLON.Observable}
  17603. */
  17604. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17605. /**
  17606. * An event triggered when material is changed
  17607. * @type {BABYLON.Observable}
  17608. */
  17609. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17610. // Properties
  17611. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17612. /**
  17613. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17614. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17615. * or
  17616. * 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.
  17617. * for more info check WebGl documentations
  17618. */
  17619. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17620. /**
  17621. * 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:
  17622. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17623. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17624. * 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.
  17625. */
  17626. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17627. /**
  17628. * 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.
  17629. * The default value is -1 which means don't break the query and wait till the result.
  17630. */
  17631. _this.occlusionRetryCount = -1;
  17632. _this._occlusionInternalRetryCounter = 0;
  17633. _this._isOccluded = false;
  17634. _this._isOcclusionQueryInProgress = false;
  17635. _this._visibility = 1.0;
  17636. _this.alphaIndex = Number.MAX_VALUE;
  17637. _this.isVisible = true;
  17638. _this.isPickable = true;
  17639. _this.showBoundingBox = false;
  17640. _this.showSubMeshesBoundingBox = false;
  17641. _this.isBlocker = false;
  17642. _this.enablePointerMoveEvents = false;
  17643. _this.renderingGroupId = 0;
  17644. _this._receiveShadows = false;
  17645. _this.renderOutline = false;
  17646. _this.outlineColor = BABYLON.Color3.Red();
  17647. _this.outlineWidth = 0.02;
  17648. _this.renderOverlay = false;
  17649. _this.overlayColor = BABYLON.Color3.Red();
  17650. _this.overlayAlpha = 0.5;
  17651. _this._hasVertexAlpha = false;
  17652. _this._useVertexColors = true;
  17653. _this._computeBonesUsingShaders = true;
  17654. _this._numBoneInfluencers = 4;
  17655. _this._applyFog = true;
  17656. _this.useOctreeForRenderingSelection = true;
  17657. _this.useOctreeForPicking = true;
  17658. _this.useOctreeForCollisions = true;
  17659. _this._layerMask = 0x0FFFFFFF;
  17660. /**
  17661. * True if the mesh must be rendered in any case.
  17662. */
  17663. _this.alwaysSelectAsActiveMesh = false;
  17664. /**
  17665. * This scene's action manager
  17666. * @type {BABYLON.ActionManager}
  17667. */
  17668. _this.actionManager = null;
  17669. // Physics
  17670. _this.physicsImpostor = null;
  17671. // Collisions
  17672. _this._checkCollisions = false;
  17673. _this._collisionMask = -1;
  17674. _this._collisionGroup = -1;
  17675. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17676. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17677. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17678. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17679. // Edges
  17680. _this.edgesWidth = 1;
  17681. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17682. // Cache
  17683. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17684. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17685. _this._renderId = 0;
  17686. _this._intersectionsInProgress = new Array();
  17687. _this._unIndexed = false;
  17688. _this._lightSources = new Array();
  17689. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17690. if (collidedMesh === void 0) { collidedMesh = null; }
  17691. //TODO move this to the collision coordinator!
  17692. if (_this.getScene().workerCollisions)
  17693. newPosition.multiplyInPlace(_this._collider._radius);
  17694. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17695. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17696. _this.position.addInPlace(_this._diffPositionForCollisions);
  17697. }
  17698. if (collidedMesh) {
  17699. _this.onCollideObservable.notifyObservers(collidedMesh);
  17700. }
  17701. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17702. };
  17703. _this.getScene().addMesh(_this);
  17704. _this._resyncLightSources();
  17705. return _this;
  17706. }
  17707. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17708. get: function () {
  17709. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17710. },
  17711. enumerable: true,
  17712. configurable: true
  17713. });
  17714. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17715. get: function () {
  17716. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17717. },
  17718. enumerable: true,
  17719. configurable: true
  17720. });
  17721. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17722. get: function () {
  17723. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17724. },
  17725. enumerable: true,
  17726. configurable: true
  17727. });
  17728. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17729. get: function () {
  17730. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17731. },
  17732. enumerable: true,
  17733. configurable: true
  17734. });
  17735. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17736. get: function () {
  17737. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17738. },
  17739. enumerable: true,
  17740. configurable: true
  17741. });
  17742. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17743. /**
  17744. * Read-only : the number of facets in the mesh
  17745. */
  17746. get: function () {
  17747. return this._facetNb;
  17748. },
  17749. enumerable: true,
  17750. configurable: true
  17751. });
  17752. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17753. /**
  17754. * The number (integer) of subdivisions per axis in the partioning space
  17755. */
  17756. get: function () {
  17757. return this._partitioningSubdivisions;
  17758. },
  17759. set: function (nb) {
  17760. this._partitioningSubdivisions = nb;
  17761. },
  17762. enumerable: true,
  17763. configurable: true
  17764. });
  17765. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17766. /**
  17767. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17768. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17769. */
  17770. get: function () {
  17771. return this._partitioningBBoxRatio;
  17772. },
  17773. set: function (ratio) {
  17774. this._partitioningBBoxRatio = ratio;
  17775. },
  17776. enumerable: true,
  17777. configurable: true
  17778. });
  17779. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17780. /**
  17781. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17782. * Works only for updatable meshes.
  17783. * Doesn't work with multi-materials.
  17784. */
  17785. get: function () {
  17786. return this._facetDepthSort;
  17787. },
  17788. set: function (sort) {
  17789. this._facetDepthSort = sort;
  17790. },
  17791. enumerable: true,
  17792. configurable: true
  17793. });
  17794. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17795. /**
  17796. * The location (Vector3) where the facet depth sort must be computed from.
  17797. * By default, the active camera position.
  17798. * Used only when facet depth sort is enabled.
  17799. */
  17800. get: function () {
  17801. return this._facetDepthSortFrom;
  17802. },
  17803. set: function (location) {
  17804. this._facetDepthSortFrom = location;
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17810. /**
  17811. * Read-only boolean : is the feature facetData enabled ?
  17812. */
  17813. get: function () {
  17814. return this._facetDataEnabled;
  17815. },
  17816. enumerable: true,
  17817. configurable: true
  17818. });
  17819. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17820. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17821. return false;
  17822. }
  17823. this._markSubMeshesAsMiscDirty();
  17824. return true;
  17825. };
  17826. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17827. set: function (callback) {
  17828. if (this._onCollideObserver) {
  17829. this.onCollideObservable.remove(this._onCollideObserver);
  17830. }
  17831. this._onCollideObserver = this.onCollideObservable.add(callback);
  17832. },
  17833. enumerable: true,
  17834. configurable: true
  17835. });
  17836. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17837. set: function (callback) {
  17838. if (this._onCollisionPositionChangeObserver) {
  17839. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17840. }
  17841. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17847. /**
  17848. * 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.
  17849. */
  17850. get: function () {
  17851. return this._isOccluded;
  17852. },
  17853. set: function (value) {
  17854. this._isOccluded = value;
  17855. },
  17856. enumerable: true,
  17857. configurable: true
  17858. });
  17859. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17860. /**
  17861. * Flag to check the progress status of the query
  17862. */
  17863. get: function () {
  17864. return this._isOcclusionQueryInProgress;
  17865. },
  17866. enumerable: true,
  17867. configurable: true
  17868. });
  17869. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17870. /**
  17871. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17872. */
  17873. get: function () {
  17874. return this._visibility;
  17875. },
  17876. /**
  17877. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17878. */
  17879. set: function (value) {
  17880. if (this._visibility === value) {
  17881. return;
  17882. }
  17883. this._visibility = value;
  17884. this._markSubMeshesAsMiscDirty();
  17885. },
  17886. enumerable: true,
  17887. configurable: true
  17888. });
  17889. Object.defineProperty(AbstractMesh.prototype, "material", {
  17890. get: function () {
  17891. return this._material;
  17892. },
  17893. set: function (value) {
  17894. if (this._material === value) {
  17895. return;
  17896. }
  17897. this._material = value;
  17898. if (this.onMaterialChangedObservable.hasObservers) {
  17899. this.onMaterialChangedObservable.notifyObservers(this);
  17900. }
  17901. if (!this.subMeshes) {
  17902. return;
  17903. }
  17904. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17905. var subMesh = _a[_i];
  17906. subMesh.setEffect(null);
  17907. }
  17908. },
  17909. enumerable: true,
  17910. configurable: true
  17911. });
  17912. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17913. get: function () {
  17914. return this._receiveShadows;
  17915. },
  17916. set: function (value) {
  17917. if (this._receiveShadows === value) {
  17918. return;
  17919. }
  17920. this._receiveShadows = value;
  17921. this._markSubMeshesAsLightDirty();
  17922. },
  17923. enumerable: true,
  17924. configurable: true
  17925. });
  17926. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17927. get: function () {
  17928. return this._hasVertexAlpha;
  17929. },
  17930. set: function (value) {
  17931. if (this._hasVertexAlpha === value) {
  17932. return;
  17933. }
  17934. this._hasVertexAlpha = value;
  17935. this._markSubMeshesAsAttributesDirty();
  17936. this._markSubMeshesAsMiscDirty();
  17937. },
  17938. enumerable: true,
  17939. configurable: true
  17940. });
  17941. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17942. get: function () {
  17943. return this._useVertexColors;
  17944. },
  17945. set: function (value) {
  17946. if (this._useVertexColors === value) {
  17947. return;
  17948. }
  17949. this._useVertexColors = value;
  17950. this._markSubMeshesAsAttributesDirty();
  17951. },
  17952. enumerable: true,
  17953. configurable: true
  17954. });
  17955. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17956. get: function () {
  17957. return this._computeBonesUsingShaders;
  17958. },
  17959. set: function (value) {
  17960. if (this._computeBonesUsingShaders === value) {
  17961. return;
  17962. }
  17963. this._computeBonesUsingShaders = value;
  17964. this._markSubMeshesAsAttributesDirty();
  17965. },
  17966. enumerable: true,
  17967. configurable: true
  17968. });
  17969. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17970. get: function () {
  17971. return this._numBoneInfluencers;
  17972. },
  17973. set: function (value) {
  17974. if (this._numBoneInfluencers === value) {
  17975. return;
  17976. }
  17977. this._numBoneInfluencers = value;
  17978. this._markSubMeshesAsAttributesDirty();
  17979. },
  17980. enumerable: true,
  17981. configurable: true
  17982. });
  17983. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17984. get: function () {
  17985. return this._applyFog;
  17986. },
  17987. set: function (value) {
  17988. if (this._applyFog === value) {
  17989. return;
  17990. }
  17991. this._applyFog = value;
  17992. this._markSubMeshesAsMiscDirty();
  17993. },
  17994. enumerable: true,
  17995. configurable: true
  17996. });
  17997. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17998. get: function () {
  17999. return this._layerMask;
  18000. },
  18001. set: function (value) {
  18002. if (value === this._layerMask) {
  18003. return;
  18004. }
  18005. this._layerMask = value;
  18006. this._resyncLightSources();
  18007. },
  18008. enumerable: true,
  18009. configurable: true
  18010. });
  18011. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  18012. get: function () {
  18013. return this._collisionMask;
  18014. },
  18015. set: function (mask) {
  18016. this._collisionMask = !isNaN(mask) ? mask : -1;
  18017. },
  18018. enumerable: true,
  18019. configurable: true
  18020. });
  18021. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  18022. get: function () {
  18023. return this._collisionGroup;
  18024. },
  18025. set: function (mask) {
  18026. this._collisionGroup = !isNaN(mask) ? mask : -1;
  18027. },
  18028. enumerable: true,
  18029. configurable: true
  18030. });
  18031. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  18032. get: function () {
  18033. return null;
  18034. },
  18035. enumerable: true,
  18036. configurable: true
  18037. });
  18038. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  18039. get: function () {
  18040. return this._skeleton;
  18041. },
  18042. set: function (value) {
  18043. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  18044. this._skeleton._unregisterMeshWithPoseMatrix(this);
  18045. }
  18046. if (value && value.needInitialSkinMatrix) {
  18047. value._registerMeshWithPoseMatrix(this);
  18048. }
  18049. this._skeleton = value;
  18050. if (!this._skeleton) {
  18051. this._bonesTransformMatrices = null;
  18052. }
  18053. this._markSubMeshesAsAttributesDirty();
  18054. },
  18055. enumerable: true,
  18056. configurable: true
  18057. });
  18058. /**
  18059. * Returns the string "AbstractMesh"
  18060. */
  18061. AbstractMesh.prototype.getClassName = function () {
  18062. return "AbstractMesh";
  18063. };
  18064. /**
  18065. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18066. */
  18067. AbstractMesh.prototype.toString = function (fullDetails) {
  18068. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  18069. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  18070. if (this._skeleton) {
  18071. ret += ", skeleton: " + this._skeleton.name;
  18072. }
  18073. if (fullDetails) {
  18074. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  18075. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  18076. }
  18077. return ret;
  18078. };
  18079. AbstractMesh.prototype._rebuild = function () {
  18080. if (this._occlusionQuery) {
  18081. this._occlusionQuery = null;
  18082. }
  18083. if (this._edgesRenderer) {
  18084. this._edgesRenderer._rebuild();
  18085. }
  18086. if (!this.subMeshes) {
  18087. return;
  18088. }
  18089. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18090. var subMesh = _a[_i];
  18091. subMesh._rebuild();
  18092. }
  18093. };
  18094. AbstractMesh.prototype._resyncLightSources = function () {
  18095. this._lightSources.length = 0;
  18096. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  18097. var light = _a[_i];
  18098. if (!light.isEnabled()) {
  18099. continue;
  18100. }
  18101. if (light.canAffectMesh(this)) {
  18102. this._lightSources.push(light);
  18103. }
  18104. }
  18105. this._markSubMeshesAsLightDirty();
  18106. };
  18107. AbstractMesh.prototype._resyncLighSource = function (light) {
  18108. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18109. var index = this._lightSources.indexOf(light);
  18110. if (index === -1) {
  18111. if (!isIn) {
  18112. return;
  18113. }
  18114. this._lightSources.push(light);
  18115. }
  18116. else {
  18117. if (isIn) {
  18118. return;
  18119. }
  18120. this._lightSources.splice(index, 1);
  18121. }
  18122. this._markSubMeshesAsLightDirty();
  18123. };
  18124. AbstractMesh.prototype._removeLightSource = function (light) {
  18125. var index = this._lightSources.indexOf(light);
  18126. if (index === -1) {
  18127. return;
  18128. }
  18129. this._lightSources.splice(index, 1);
  18130. this._markSubMeshesAsLightDirty();
  18131. };
  18132. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18133. if (!this.subMeshes) {
  18134. return;
  18135. }
  18136. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18137. var subMesh = _a[_i];
  18138. if (subMesh._materialDefines) {
  18139. func(subMesh._materialDefines);
  18140. }
  18141. }
  18142. };
  18143. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18144. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18145. };
  18146. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18147. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18148. };
  18149. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18150. if (!this.subMeshes) {
  18151. return;
  18152. }
  18153. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18154. var subMesh = _a[_i];
  18155. var material = subMesh.getMaterial();
  18156. if (material) {
  18157. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18158. }
  18159. }
  18160. };
  18161. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18162. /**
  18163. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18164. * Default : (1.0, 1.0, 1.0)
  18165. */
  18166. get: function () {
  18167. return this._scaling;
  18168. },
  18169. /**
  18170. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18171. * Default : (1.0, 1.0, 1.0)
  18172. */
  18173. set: function (newScaling) {
  18174. this._scaling = newScaling;
  18175. if (this.physicsImpostor) {
  18176. this.physicsImpostor.forceUpdate();
  18177. }
  18178. },
  18179. enumerable: true,
  18180. configurable: true
  18181. });
  18182. // Methods
  18183. /**
  18184. * Disables the mesh edger rendering mode.
  18185. * Returns the AbstractMesh.
  18186. */
  18187. AbstractMesh.prototype.disableEdgesRendering = function () {
  18188. if (this._edgesRenderer) {
  18189. this._edgesRenderer.dispose();
  18190. this._edgesRenderer = null;
  18191. }
  18192. return this;
  18193. };
  18194. /**
  18195. * Enables the edge rendering mode on the mesh.
  18196. * This mode makes the mesh edges visible.
  18197. * Returns the AbstractMesh.
  18198. */
  18199. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18200. if (epsilon === void 0) { epsilon = 0.95; }
  18201. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18202. this.disableEdgesRendering();
  18203. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18204. return this;
  18205. };
  18206. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18207. /**
  18208. * Returns true if the mesh is blocked. Used by the class Mesh.
  18209. * Returns the boolean `false` by default.
  18210. */
  18211. get: function () {
  18212. return false;
  18213. },
  18214. enumerable: true,
  18215. configurable: true
  18216. });
  18217. /**
  18218. * Returns the mesh itself by default, used by the class Mesh.
  18219. * Returned type : AbstractMesh
  18220. */
  18221. AbstractMesh.prototype.getLOD = function (camera) {
  18222. return this;
  18223. };
  18224. /**
  18225. * Returns 0 by default, used by the class Mesh.
  18226. * Returns an integer.
  18227. */
  18228. AbstractMesh.prototype.getTotalVertices = function () {
  18229. return 0;
  18230. };
  18231. /**
  18232. * Returns null by default, used by the class Mesh.
  18233. * Returned type : integer array
  18234. */
  18235. AbstractMesh.prototype.getIndices = function () {
  18236. return null;
  18237. };
  18238. /**
  18239. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18240. * Returned type : float array or Float32Array
  18241. */
  18242. AbstractMesh.prototype.getVerticesData = function (kind) {
  18243. return null;
  18244. };
  18245. /**
  18246. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18247. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18248. * The `data` are either a numeric array either a Float32Array.
  18249. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18250. * 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).
  18251. * Note that a new underlying VertexBuffer object is created each call.
  18252. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18253. *
  18254. * Possible `kind` values :
  18255. * - BABYLON.VertexBuffer.PositionKind
  18256. * - BABYLON.VertexBuffer.UVKind
  18257. * - BABYLON.VertexBuffer.UV2Kind
  18258. * - BABYLON.VertexBuffer.UV3Kind
  18259. * - BABYLON.VertexBuffer.UV4Kind
  18260. * - BABYLON.VertexBuffer.UV5Kind
  18261. * - BABYLON.VertexBuffer.UV6Kind
  18262. * - BABYLON.VertexBuffer.ColorKind
  18263. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18264. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18265. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18266. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18267. *
  18268. * Returns the Mesh.
  18269. */
  18270. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18271. return this;
  18272. };
  18273. /**
  18274. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18275. * If the mesh has no geometry, it is simply returned as it is.
  18276. * The `data` are either a numeric array either a Float32Array.
  18277. * No new underlying VertexBuffer object is created.
  18278. * 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.
  18279. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18280. *
  18281. * Possible `kind` values :
  18282. * - BABYLON.VertexBuffer.PositionKind
  18283. * - BABYLON.VertexBuffer.UVKind
  18284. * - BABYLON.VertexBuffer.UV2Kind
  18285. * - BABYLON.VertexBuffer.UV3Kind
  18286. * - BABYLON.VertexBuffer.UV4Kind
  18287. * - BABYLON.VertexBuffer.UV5Kind
  18288. * - BABYLON.VertexBuffer.UV6Kind
  18289. * - BABYLON.VertexBuffer.ColorKind
  18290. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18291. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18292. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18293. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18294. *
  18295. * Returns the Mesh.
  18296. */
  18297. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18298. return this;
  18299. };
  18300. /**
  18301. * Sets the mesh indices.
  18302. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18303. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18304. * This method creates a new index buffer each call.
  18305. * Returns the Mesh.
  18306. */
  18307. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18308. return this;
  18309. };
  18310. /** Returns false by default, used by the class Mesh.
  18311. * Returns a boolean
  18312. */
  18313. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18314. return false;
  18315. };
  18316. /**
  18317. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18318. * Returns a BoundingInfo
  18319. */
  18320. AbstractMesh.prototype.getBoundingInfo = function () {
  18321. if (this._masterMesh) {
  18322. return this._masterMesh.getBoundingInfo();
  18323. }
  18324. if (!this._boundingInfo) {
  18325. // this._boundingInfo is being created here
  18326. this._updateBoundingInfo();
  18327. }
  18328. // cannot be null.
  18329. return this._boundingInfo;
  18330. };
  18331. /**
  18332. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18333. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18334. */
  18335. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18336. if (includeDescendants === void 0) { includeDescendants = true; }
  18337. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18338. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18339. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18340. if (maxDimension === 0) {
  18341. return this;
  18342. }
  18343. var scale = 1 / maxDimension;
  18344. this.scaling.scaleInPlace(scale);
  18345. return this;
  18346. };
  18347. /**
  18348. * Sets a mesh new object BoundingInfo.
  18349. * Returns the AbstractMesh.
  18350. */
  18351. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18352. this._boundingInfo = boundingInfo;
  18353. return this;
  18354. };
  18355. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18356. get: function () {
  18357. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18358. },
  18359. enumerable: true,
  18360. configurable: true
  18361. });
  18362. AbstractMesh.prototype._preActivate = function () {
  18363. };
  18364. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18365. };
  18366. AbstractMesh.prototype._activate = function (renderId) {
  18367. this._renderId = renderId;
  18368. };
  18369. /**
  18370. * Returns the latest update of the World matrix
  18371. * Returns a Matrix.
  18372. */
  18373. AbstractMesh.prototype.getWorldMatrix = function () {
  18374. if (this._masterMesh) {
  18375. return this._masterMesh.getWorldMatrix();
  18376. }
  18377. return _super.prototype.getWorldMatrix.call(this);
  18378. };
  18379. /**
  18380. * Returns the latest update of the World matrix determinant.
  18381. */
  18382. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18383. if (this._masterMesh) {
  18384. return this._masterMesh._getWorldMatrixDeterminant();
  18385. }
  18386. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18387. };
  18388. // ================================== Point of View Movement =================================
  18389. /**
  18390. * Perform relative position change from the point of view of behind the front of the mesh.
  18391. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18392. * Supports definition of mesh facing forward or backward.
  18393. * @param {number} amountRight
  18394. * @param {number} amountUp
  18395. * @param {number} amountForward
  18396. *
  18397. * Returns the AbstractMesh.
  18398. */
  18399. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18400. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18401. return this;
  18402. };
  18403. /**
  18404. * Calculate relative position change from the point of view of behind the front of the mesh.
  18405. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18406. * Supports definition of mesh facing forward or backward.
  18407. * @param {number} amountRight
  18408. * @param {number} amountUp
  18409. * @param {number} amountForward
  18410. *
  18411. * Returns a new Vector3.
  18412. */
  18413. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18414. var rotMatrix = new BABYLON.Matrix();
  18415. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18416. rotQuaternion.toRotationMatrix(rotMatrix);
  18417. var translationDelta = BABYLON.Vector3.Zero();
  18418. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18419. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18420. return translationDelta;
  18421. };
  18422. // ================================== Point of View Rotation =================================
  18423. /**
  18424. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18425. * Supports definition of mesh facing forward or backward.
  18426. * @param {number} flipBack
  18427. * @param {number} twirlClockwise
  18428. * @param {number} tiltRight
  18429. *
  18430. * Returns the AbstractMesh.
  18431. */
  18432. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18433. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18434. return this;
  18435. };
  18436. /**
  18437. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18438. * Supports definition of mesh facing forward or backward.
  18439. * @param {number} flipBack
  18440. * @param {number} twirlClockwise
  18441. * @param {number} tiltRight
  18442. *
  18443. * Returns a new Vector3.
  18444. */
  18445. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18446. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18447. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18448. };
  18449. /**
  18450. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18451. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18452. */
  18453. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18454. if (includeDescendants === void 0) { includeDescendants = true; }
  18455. this.computeWorldMatrix(true);
  18456. var min;
  18457. var max;
  18458. var boundingInfo = this.getBoundingInfo();
  18459. if (!this.subMeshes) {
  18460. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18461. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18462. }
  18463. else {
  18464. min = boundingInfo.boundingBox.minimumWorld;
  18465. max = boundingInfo.boundingBox.maximumWorld;
  18466. }
  18467. if (includeDescendants) {
  18468. var descendants = this.getDescendants(false);
  18469. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18470. var descendant = descendants_1[_i];
  18471. var childMesh = descendant;
  18472. childMesh.computeWorldMatrix(true);
  18473. //make sure we have the needed params to get mix and max
  18474. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18475. continue;
  18476. }
  18477. var childBoundingInfo = childMesh.getBoundingInfo();
  18478. var boundingBox = childBoundingInfo.boundingBox;
  18479. var minBox = boundingBox.minimumWorld;
  18480. var maxBox = boundingBox.maximumWorld;
  18481. BABYLON.Tools.CheckExtends(minBox, min, max);
  18482. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18483. }
  18484. }
  18485. return {
  18486. min: min,
  18487. max: max
  18488. };
  18489. };
  18490. /**
  18491. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18492. * Returns the AbstractMesh.
  18493. */
  18494. AbstractMesh.prototype._updateBoundingInfo = function () {
  18495. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18496. this._boundingInfo.update(this.worldMatrixFromCache);
  18497. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18498. return this;
  18499. };
  18500. /**
  18501. * Update a mesh's children BoundingInfo objects only.
  18502. * Returns the AbstractMesh.
  18503. */
  18504. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18505. if (!this.subMeshes) {
  18506. return this;
  18507. }
  18508. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18509. var subMesh = this.subMeshes[subIndex];
  18510. if (!subMesh.IsGlobal) {
  18511. subMesh.updateBoundingInfo(matrix);
  18512. }
  18513. }
  18514. return this;
  18515. };
  18516. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18517. // Bounding info
  18518. this._updateBoundingInfo();
  18519. };
  18520. /**
  18521. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18522. * A mesh is in the frustum if its bounding box intersects the frustum.
  18523. * Boolean returned.
  18524. */
  18525. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18526. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18527. };
  18528. /**
  18529. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18530. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18531. * Boolean returned.
  18532. */
  18533. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18534. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18535. ;
  18536. };
  18537. /**
  18538. * True if the mesh intersects another mesh or a SolidParticle object.
  18539. * 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)
  18540. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18541. * Returns a boolean.
  18542. */
  18543. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18544. if (precise === void 0) { precise = false; }
  18545. if (!this._boundingInfo || !mesh._boundingInfo) {
  18546. return false;
  18547. }
  18548. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18549. return true;
  18550. }
  18551. if (includeDescendants) {
  18552. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18553. var child = _a[_i];
  18554. if (child.intersectsMesh(mesh, precise, true)) {
  18555. return true;
  18556. }
  18557. }
  18558. }
  18559. return false;
  18560. };
  18561. /**
  18562. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18563. * Returns a boolean.
  18564. */
  18565. AbstractMesh.prototype.intersectsPoint = function (point) {
  18566. if (!this._boundingInfo) {
  18567. return false;
  18568. }
  18569. return this._boundingInfo.intersectsPoint(point);
  18570. };
  18571. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18572. return this.physicsImpostor;
  18573. };
  18574. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18575. if (camera === void 0) { camera = null; }
  18576. if (!camera) {
  18577. camera = this.getScene().activeCamera;
  18578. }
  18579. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18580. };
  18581. /**
  18582. * Returns the distance from the mesh to the active camera.
  18583. * Returns a float.
  18584. */
  18585. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18586. if (camera === void 0) { camera = null; }
  18587. if (!camera) {
  18588. camera = this.getScene().activeCamera;
  18589. }
  18590. return this.absolutePosition.subtract(camera.position).length();
  18591. };
  18592. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18593. if (!this.physicsImpostor) {
  18594. return this;
  18595. }
  18596. this.physicsImpostor.applyImpulse(force, contactPoint);
  18597. return this;
  18598. };
  18599. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18600. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18601. return this;
  18602. }
  18603. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18604. mainPivot: pivot1,
  18605. connectedPivot: pivot2,
  18606. nativeParams: options
  18607. });
  18608. return this;
  18609. };
  18610. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18611. // Collisions
  18612. /**
  18613. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18614. * Default `false`.
  18615. */
  18616. get: function () {
  18617. return this._checkCollisions;
  18618. },
  18619. set: function (collisionEnabled) {
  18620. this._checkCollisions = collisionEnabled;
  18621. if (this.getScene().workerCollisions) {
  18622. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18623. }
  18624. },
  18625. enumerable: true,
  18626. configurable: true
  18627. });
  18628. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18629. /**
  18630. * Gets Collider object used to compute collisions (not physics)
  18631. */
  18632. get: function () {
  18633. return this._collider;
  18634. },
  18635. enumerable: true,
  18636. configurable: true
  18637. });
  18638. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18639. var globalPosition = this.getAbsolutePosition();
  18640. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18641. if (!this._collider) {
  18642. this._collider = new BABYLON.Collider();
  18643. }
  18644. this._collider._radius = this.ellipsoid;
  18645. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18646. return this;
  18647. };
  18648. // Submeshes octree
  18649. /**
  18650. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18651. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18652. * Returns an Octree of submeshes.
  18653. */
  18654. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18655. if (maxCapacity === void 0) { maxCapacity = 64; }
  18656. if (maxDepth === void 0) { maxDepth = 2; }
  18657. if (!this._submeshesOctree) {
  18658. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18659. }
  18660. this.computeWorldMatrix(true);
  18661. var boundingInfo = this.getBoundingInfo();
  18662. // Update octree
  18663. var bbox = boundingInfo.boundingBox;
  18664. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18665. return this._submeshesOctree;
  18666. };
  18667. // Collisions
  18668. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18669. this._generatePointsArray();
  18670. if (!this._positions) {
  18671. return this;
  18672. }
  18673. // Transformation
  18674. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18675. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18676. subMesh._lastColliderWorldVertices = [];
  18677. subMesh._trianglePlanes = [];
  18678. var start = subMesh.verticesStart;
  18679. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18680. for (var i = start; i < end; i++) {
  18681. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18682. }
  18683. }
  18684. // Collide
  18685. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18686. if (collider.collisionFound) {
  18687. collider.collidedMesh = this;
  18688. }
  18689. return this;
  18690. };
  18691. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18692. var subMeshes;
  18693. var len;
  18694. // Octrees
  18695. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18696. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18697. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18698. len = intersections.length;
  18699. subMeshes = intersections.data;
  18700. }
  18701. else {
  18702. subMeshes = this.subMeshes;
  18703. len = subMeshes.length;
  18704. }
  18705. for (var index = 0; index < len; index++) {
  18706. var subMesh = subMeshes[index];
  18707. // Bounding test
  18708. if (len > 1 && !subMesh._checkCollision(collider))
  18709. continue;
  18710. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18711. }
  18712. return this;
  18713. };
  18714. AbstractMesh.prototype._checkCollision = function (collider) {
  18715. // Bounding box test
  18716. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18717. return this;
  18718. // Transformation matrix
  18719. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18720. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18721. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18722. return this;
  18723. };
  18724. // Picking
  18725. AbstractMesh.prototype._generatePointsArray = function () {
  18726. return false;
  18727. };
  18728. /**
  18729. * Checks if the passed Ray intersects with the mesh.
  18730. * Returns an object PickingInfo.
  18731. */
  18732. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18733. var pickingInfo = new BABYLON.PickingInfo();
  18734. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18735. return pickingInfo;
  18736. }
  18737. if (!this._generatePointsArray()) {
  18738. return pickingInfo;
  18739. }
  18740. var intersectInfo = null;
  18741. // Octrees
  18742. var subMeshes;
  18743. var len;
  18744. if (this._submeshesOctree && this.useOctreeForPicking) {
  18745. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18746. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18747. len = intersections.length;
  18748. subMeshes = intersections.data;
  18749. }
  18750. else {
  18751. subMeshes = this.subMeshes;
  18752. len = subMeshes.length;
  18753. }
  18754. for (var index = 0; index < len; index++) {
  18755. var subMesh = subMeshes[index];
  18756. // Bounding test
  18757. if (len > 1 && !subMesh.canIntersects(ray))
  18758. continue;
  18759. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18760. if (currentIntersectInfo) {
  18761. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18762. intersectInfo = currentIntersectInfo;
  18763. intersectInfo.subMeshId = index;
  18764. if (fastCheck) {
  18765. break;
  18766. }
  18767. }
  18768. }
  18769. }
  18770. if (intersectInfo) {
  18771. // Get picked point
  18772. var world = this.getWorldMatrix();
  18773. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18774. var direction = ray.direction.clone();
  18775. direction = direction.scale(intersectInfo.distance);
  18776. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18777. var pickedPoint = worldOrigin.add(worldDirection);
  18778. // Return result
  18779. pickingInfo.hit = true;
  18780. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18781. pickingInfo.pickedPoint = pickedPoint;
  18782. pickingInfo.pickedMesh = this;
  18783. pickingInfo.bu = intersectInfo.bu || 0;
  18784. pickingInfo.bv = intersectInfo.bv || 0;
  18785. pickingInfo.faceId = intersectInfo.faceId;
  18786. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18787. return pickingInfo;
  18788. }
  18789. return pickingInfo;
  18790. };
  18791. /**
  18792. * Clones the mesh, used by the class Mesh.
  18793. * Just returns `null` for an AbstractMesh.
  18794. */
  18795. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18796. return null;
  18797. };
  18798. /**
  18799. * Disposes all the mesh submeshes.
  18800. * Returns the AbstractMesh.
  18801. */
  18802. AbstractMesh.prototype.releaseSubMeshes = function () {
  18803. if (this.subMeshes) {
  18804. while (this.subMeshes.length) {
  18805. this.subMeshes[0].dispose();
  18806. }
  18807. }
  18808. else {
  18809. this.subMeshes = new Array();
  18810. }
  18811. return this;
  18812. };
  18813. /**
  18814. * Releases resources associated with this abstract mesh.
  18815. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18816. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18817. */
  18818. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18819. var _this = this;
  18820. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18821. var index;
  18822. // Smart Array Retainers.
  18823. this.getScene().freeActiveMeshes();
  18824. this.getScene().freeRenderingGroups();
  18825. // Action manager
  18826. if (this.actionManager !== undefined && this.actionManager !== null) {
  18827. this.actionManager.dispose();
  18828. this.actionManager = null;
  18829. }
  18830. // Skeleton
  18831. this.skeleton = null;
  18832. // Physics
  18833. if (this.physicsImpostor) {
  18834. this.physicsImpostor.dispose();
  18835. }
  18836. // Intersections in progress
  18837. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18838. var other = this._intersectionsInProgress[index];
  18839. var pos = other._intersectionsInProgress.indexOf(this);
  18840. other._intersectionsInProgress.splice(pos, 1);
  18841. }
  18842. this._intersectionsInProgress = [];
  18843. // Lights
  18844. var lights = this.getScene().lights;
  18845. lights.forEach(function (light) {
  18846. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18847. if (meshIndex !== -1) {
  18848. light.includedOnlyMeshes.splice(meshIndex, 1);
  18849. }
  18850. meshIndex = light.excludedMeshes.indexOf(_this);
  18851. if (meshIndex !== -1) {
  18852. light.excludedMeshes.splice(meshIndex, 1);
  18853. }
  18854. // Shadow generators
  18855. var generator = light.getShadowGenerator();
  18856. if (generator) {
  18857. var shadowMap = generator.getShadowMap();
  18858. if (shadowMap && shadowMap.renderList) {
  18859. meshIndex = shadowMap.renderList.indexOf(_this);
  18860. if (meshIndex !== -1) {
  18861. shadowMap.renderList.splice(meshIndex, 1);
  18862. }
  18863. }
  18864. }
  18865. });
  18866. // Edges
  18867. if (this._edgesRenderer) {
  18868. this._edgesRenderer.dispose();
  18869. this._edgesRenderer = null;
  18870. }
  18871. // SubMeshes
  18872. if (this.getClassName() !== "InstancedMesh") {
  18873. this.releaseSubMeshes();
  18874. }
  18875. // Octree
  18876. var sceneOctree = this.getScene().selectionOctree;
  18877. if (sceneOctree !== undefined && sceneOctree !== null) {
  18878. var index = sceneOctree.dynamicContent.indexOf(this);
  18879. if (index !== -1) {
  18880. sceneOctree.dynamicContent.splice(index, 1);
  18881. }
  18882. }
  18883. // Query
  18884. var engine = this.getScene().getEngine();
  18885. if (this._occlusionQuery) {
  18886. this._isOcclusionQueryInProgress = false;
  18887. engine.deleteQuery(this._occlusionQuery);
  18888. this._occlusionQuery = null;
  18889. }
  18890. // Engine
  18891. engine.wipeCaches();
  18892. // Remove from scene
  18893. this.getScene().removeMesh(this);
  18894. if (disposeMaterialAndTextures) {
  18895. if (this.material) {
  18896. this.material.dispose(false, true);
  18897. }
  18898. }
  18899. if (!doNotRecurse) {
  18900. // Particles
  18901. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18902. if (this.getScene().particleSystems[index].emitter === this) {
  18903. this.getScene().particleSystems[index].dispose();
  18904. index--;
  18905. }
  18906. }
  18907. }
  18908. // facet data
  18909. if (this._facetDataEnabled) {
  18910. this.disableFacetData();
  18911. }
  18912. this.onAfterWorldMatrixUpdateObservable.clear();
  18913. this.onCollideObservable.clear();
  18914. this.onCollisionPositionChangeObservable.clear();
  18915. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18916. };
  18917. /**
  18918. * Adds the passed mesh as a child to the current mesh.
  18919. * Returns the AbstractMesh.
  18920. */
  18921. AbstractMesh.prototype.addChild = function (mesh) {
  18922. mesh.setParent(this);
  18923. return this;
  18924. };
  18925. /**
  18926. * Removes the passed mesh from the current mesh children list.
  18927. * Returns the AbstractMesh.
  18928. */
  18929. AbstractMesh.prototype.removeChild = function (mesh) {
  18930. mesh.setParent(null);
  18931. return this;
  18932. };
  18933. // Facet data
  18934. /**
  18935. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18936. * Returns the AbstractMesh.
  18937. */
  18938. AbstractMesh.prototype._initFacetData = function () {
  18939. if (!this._facetNormals) {
  18940. this._facetNormals = new Array();
  18941. }
  18942. if (!this._facetPositions) {
  18943. this._facetPositions = new Array();
  18944. }
  18945. if (!this._facetPartitioning) {
  18946. this._facetPartitioning = new Array();
  18947. }
  18948. this._facetNb = (this.getIndices().length / 3) | 0;
  18949. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18950. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18951. for (var f = 0; f < this._facetNb; f++) {
  18952. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18953. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18954. }
  18955. this._facetDataEnabled = true;
  18956. return this;
  18957. };
  18958. /**
  18959. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18960. * This method can be called within the render loop.
  18961. * 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.
  18962. * Returns the AbstractMesh.
  18963. */
  18964. AbstractMesh.prototype.updateFacetData = function () {
  18965. if (!this._facetDataEnabled) {
  18966. this._initFacetData();
  18967. }
  18968. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18969. var indices = this.getIndices();
  18970. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18971. var bInfo = this.getBoundingInfo();
  18972. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18973. // init arrays, matrix and sort function on first call
  18974. this._facetDepthSortEnabled = true;
  18975. if (indices instanceof Uint16Array) {
  18976. this._depthSortedIndices = new Uint16Array(indices);
  18977. }
  18978. else if (indices instanceof Uint32Array) {
  18979. this._depthSortedIndices = new Uint32Array(indices);
  18980. }
  18981. else {
  18982. var needs32bits = false;
  18983. for (var i = 0; i < indices.length; i++) {
  18984. if (indices[i] > 65535) {
  18985. needs32bits = true;
  18986. break;
  18987. }
  18988. }
  18989. if (needs32bits) {
  18990. this._depthSortedIndices = new Uint32Array(indices);
  18991. }
  18992. else {
  18993. this._depthSortedIndices = new Uint16Array(indices);
  18994. }
  18995. }
  18996. this._facetDepthSortFunction = function (f1, f2) {
  18997. return (f2.sqDistance - f1.sqDistance);
  18998. };
  18999. if (!this._facetDepthSortFrom) {
  19000. var camera = this.getScene().activeCamera;
  19001. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  19002. }
  19003. this._depthSortedFacets = [];
  19004. for (var f = 0; f < this._facetNb; f++) {
  19005. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  19006. this._depthSortedFacets.push(depthSortedFacet);
  19007. }
  19008. this._invertedMatrix = BABYLON.Matrix.Identity();
  19009. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  19010. }
  19011. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  19012. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  19013. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  19014. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  19015. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  19016. this._subDiv.max = this._partitioningSubdivisions;
  19017. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  19018. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  19019. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  19020. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  19021. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  19022. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  19023. // set the parameters for ComputeNormals()
  19024. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  19025. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  19026. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  19027. this._facetParameters.bInfo = bInfo;
  19028. this._facetParameters.bbSize = this._bbSize;
  19029. this._facetParameters.subDiv = this._subDiv;
  19030. this._facetParameters.ratio = this.partitioningBBoxRatio;
  19031. this._facetParameters.depthSort = this._facetDepthSort;
  19032. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  19033. this.computeWorldMatrix(true);
  19034. this._worldMatrix.invertToRef(this._invertedMatrix);
  19035. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  19036. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  19037. }
  19038. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  19039. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  19040. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  19041. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  19042. var l = (this._depthSortedIndices.length / 3) | 0;
  19043. for (var f = 0; f < l; f++) {
  19044. var sind = this._depthSortedFacets[f].ind;
  19045. this._depthSortedIndices[f * 3] = indices[sind];
  19046. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  19047. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  19048. }
  19049. this.updateIndices(this._depthSortedIndices);
  19050. }
  19051. return this;
  19052. };
  19053. /**
  19054. * Returns the facetLocalNormals array.
  19055. * The normals are expressed in the mesh local space.
  19056. */
  19057. AbstractMesh.prototype.getFacetLocalNormals = function () {
  19058. if (!this._facetNormals) {
  19059. this.updateFacetData();
  19060. }
  19061. return this._facetNormals;
  19062. };
  19063. /**
  19064. * Returns the facetLocalPositions array.
  19065. * The facet positions are expressed in the mesh local space.
  19066. */
  19067. AbstractMesh.prototype.getFacetLocalPositions = function () {
  19068. if (!this._facetPositions) {
  19069. this.updateFacetData();
  19070. }
  19071. return this._facetPositions;
  19072. };
  19073. /**
  19074. * Returns the facetLocalPartioning array.
  19075. */
  19076. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  19077. if (!this._facetPartitioning) {
  19078. this.updateFacetData();
  19079. }
  19080. return this._facetPartitioning;
  19081. };
  19082. /**
  19083. * Returns the i-th facet position in the world system.
  19084. * This method allocates a new Vector3 per call.
  19085. */
  19086. AbstractMesh.prototype.getFacetPosition = function (i) {
  19087. var pos = BABYLON.Vector3.Zero();
  19088. this.getFacetPositionToRef(i, pos);
  19089. return pos;
  19090. };
  19091. /**
  19092. * Sets the reference Vector3 with the i-th facet position in the world system.
  19093. * Returns the AbstractMesh.
  19094. */
  19095. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  19096. var localPos = (this.getFacetLocalPositions())[i];
  19097. var world = this.getWorldMatrix();
  19098. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  19099. return this;
  19100. };
  19101. /**
  19102. * Returns the i-th facet normal in the world system.
  19103. * This method allocates a new Vector3 per call.
  19104. */
  19105. AbstractMesh.prototype.getFacetNormal = function (i) {
  19106. var norm = BABYLON.Vector3.Zero();
  19107. this.getFacetNormalToRef(i, norm);
  19108. return norm;
  19109. };
  19110. /**
  19111. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19112. * Returns the AbstractMesh.
  19113. */
  19114. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19115. var localNorm = (this.getFacetLocalNormals())[i];
  19116. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19117. return this;
  19118. };
  19119. /**
  19120. * 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).
  19121. */
  19122. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19123. var bInfo = this.getBoundingInfo();
  19124. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19125. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19126. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19127. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19128. return null;
  19129. }
  19130. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19131. };
  19132. /**
  19133. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19134. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19135. * 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.
  19136. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19137. * 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.
  19138. */
  19139. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19140. if (checkFace === void 0) { checkFace = false; }
  19141. if (facing === void 0) { facing = true; }
  19142. var world = this.getWorldMatrix();
  19143. var invMat = BABYLON.Tmp.Matrix[5];
  19144. world.invertToRef(invMat);
  19145. var invVect = BABYLON.Tmp.Vector3[8];
  19146. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19147. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19148. if (projected) {
  19149. // tranform the local computed projected vector to world coordinates
  19150. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19151. }
  19152. return closest;
  19153. };
  19154. /**
  19155. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19156. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19157. * 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.
  19158. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19159. * 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.
  19160. */
  19161. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19162. if (checkFace === void 0) { checkFace = false; }
  19163. if (facing === void 0) { facing = true; }
  19164. var closest = null;
  19165. var tmpx = 0.0;
  19166. var tmpy = 0.0;
  19167. var tmpz = 0.0;
  19168. var d = 0.0; // tmp dot facet normal * facet position
  19169. var t0 = 0.0;
  19170. var projx = 0.0;
  19171. var projy = 0.0;
  19172. var projz = 0.0;
  19173. // Get all the facets in the same partitioning block than (x, y, z)
  19174. var facetPositions = this.getFacetLocalPositions();
  19175. var facetNormals = this.getFacetLocalNormals();
  19176. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19177. if (!facetsInBlock) {
  19178. return null;
  19179. }
  19180. // Get the closest facet to (x, y, z)
  19181. var shortest = Number.MAX_VALUE; // init distance vars
  19182. var tmpDistance = shortest;
  19183. var fib; // current facet in the block
  19184. var norm; // current facet normal
  19185. var p0; // current facet barycenter position
  19186. // loop on all the facets in the current partitioning block
  19187. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19188. fib = facetsInBlock[idx];
  19189. norm = facetNormals[fib];
  19190. p0 = facetPositions[fib];
  19191. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19192. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19193. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19194. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19195. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19196. projx = x + norm.x * t0;
  19197. projy = y + norm.y * t0;
  19198. projz = z + norm.z * t0;
  19199. tmpx = projx - x;
  19200. tmpy = projy - y;
  19201. tmpz = projz - z;
  19202. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19203. if (tmpDistance < shortest) {
  19204. shortest = tmpDistance;
  19205. closest = fib;
  19206. if (projected) {
  19207. projected.x = projx;
  19208. projected.y = projy;
  19209. projected.z = projz;
  19210. }
  19211. }
  19212. }
  19213. }
  19214. return closest;
  19215. };
  19216. /**
  19217. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19218. */
  19219. AbstractMesh.prototype.getFacetDataParameters = function () {
  19220. return this._facetParameters;
  19221. };
  19222. /**
  19223. * Disables the feature FacetData and frees the related memory.
  19224. * Returns the AbstractMesh.
  19225. */
  19226. AbstractMesh.prototype.disableFacetData = function () {
  19227. if (this._facetDataEnabled) {
  19228. this._facetDataEnabled = false;
  19229. this._facetPositions = new Array();
  19230. this._facetNormals = new Array();
  19231. this._facetPartitioning = new Array();
  19232. this._facetParameters = null;
  19233. this._depthSortedIndices = new Uint32Array(0);
  19234. }
  19235. return this;
  19236. };
  19237. /**
  19238. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19239. * Returns the mesh.
  19240. */
  19241. AbstractMesh.prototype.updateIndices = function (indices) {
  19242. return this;
  19243. };
  19244. /**
  19245. * The mesh Geometry. Actually used by the Mesh object.
  19246. * Returns a blank geometry object.
  19247. */
  19248. /**
  19249. * Creates new normals data for the mesh.
  19250. * @param updatable.
  19251. */
  19252. AbstractMesh.prototype.createNormals = function (updatable) {
  19253. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19254. var indices = this.getIndices();
  19255. var normals;
  19256. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19257. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19258. }
  19259. else {
  19260. normals = [];
  19261. }
  19262. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19263. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19264. };
  19265. /**
  19266. * Align the mesh with a normal.
  19267. * Returns the mesh.
  19268. */
  19269. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19270. if (!upDirection) {
  19271. upDirection = BABYLON.Axis.Y;
  19272. }
  19273. var axisX = BABYLON.Tmp.Vector3[0];
  19274. var axisZ = BABYLON.Tmp.Vector3[1];
  19275. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19276. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19277. if (this.rotationQuaternion) {
  19278. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19279. }
  19280. else {
  19281. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19282. }
  19283. return this;
  19284. };
  19285. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19286. var engine = this.getEngine();
  19287. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19288. this._isOccluded = false;
  19289. return;
  19290. }
  19291. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19292. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19293. if (isOcclusionQueryAvailable) {
  19294. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19295. this._isOcclusionQueryInProgress = false;
  19296. this._occlusionInternalRetryCounter = 0;
  19297. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19298. }
  19299. else {
  19300. this._occlusionInternalRetryCounter++;
  19301. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19302. this._isOcclusionQueryInProgress = false;
  19303. this._occlusionInternalRetryCounter = 0;
  19304. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19305. // if strict continue the last state of the object.
  19306. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19307. }
  19308. else {
  19309. return;
  19310. }
  19311. }
  19312. }
  19313. var scene = this.getScene();
  19314. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19315. if (!this._occlusionQuery) {
  19316. this._occlusionQuery = engine.createQuery();
  19317. }
  19318. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19319. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19320. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19321. this._isOcclusionQueryInProgress = true;
  19322. };
  19323. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19324. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19325. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19326. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19327. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19328. return AbstractMesh;
  19329. }(BABYLON.TransformNode));
  19330. BABYLON.AbstractMesh = AbstractMesh;
  19331. })(BABYLON || (BABYLON = {}));
  19332. //# sourceMappingURL=babylon.abstractMesh.js.map
  19333. "use strict";
  19334. var BABYLON;
  19335. (function (BABYLON) {
  19336. /**
  19337. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19338. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19339. * 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.
  19340. */
  19341. var Light = /** @class */ (function (_super) {
  19342. __extends(Light, _super);
  19343. /**
  19344. * Creates a Light object in the scene.
  19345. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19346. * @param name The firendly name of the light
  19347. * @param scene The scene the light belongs too
  19348. */
  19349. function Light(name, scene) {
  19350. var _this = _super.call(this, name, scene) || this;
  19351. /**
  19352. * Diffuse gives the basic color to an object.
  19353. */
  19354. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19355. /**
  19356. * Specular produces a highlight color on an object.
  19357. * Note: This is note affecting PBR materials.
  19358. */
  19359. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19360. /**
  19361. * Strength of the light.
  19362. * Note: By default it is define in the framework own unit.
  19363. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19364. */
  19365. _this.intensity = 1.0;
  19366. /**
  19367. * Defines how far from the source the light is impacting in scene units.
  19368. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19369. */
  19370. _this.range = Number.MAX_VALUE;
  19371. /**
  19372. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19373. * of light.
  19374. */
  19375. _this._photometricScale = 1.0;
  19376. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19377. _this._radius = 0.00001;
  19378. /**
  19379. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19380. * exceeding the number allowed of the materials.
  19381. */
  19382. _this.renderPriority = 0;
  19383. /**
  19384. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19385. * the current shadow generator.
  19386. */
  19387. _this.shadowEnabled = true;
  19388. _this._excludeWithLayerMask = 0;
  19389. _this._includeOnlyWithLayerMask = 0;
  19390. _this._lightmapMode = 0;
  19391. /**
  19392. * @ignore Internal use only.
  19393. */
  19394. _this._excludedMeshesIds = new Array();
  19395. /**
  19396. * @ignore Internal use only.
  19397. */
  19398. _this._includedOnlyMeshesIds = new Array();
  19399. _this.getScene().addLight(_this);
  19400. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19401. _this._buildUniformLayout();
  19402. _this.includedOnlyMeshes = new Array();
  19403. _this.excludedMeshes = new Array();
  19404. _this._resyncMeshes();
  19405. return _this;
  19406. }
  19407. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19408. /**
  19409. * If every light affecting the material is in this lightmapMode,
  19410. * material.lightmapTexture adds or multiplies
  19411. * (depends on material.useLightmapAsShadowmap)
  19412. * after every other light calculations.
  19413. */
  19414. get: function () {
  19415. return Light._LIGHTMAP_DEFAULT;
  19416. },
  19417. enumerable: true,
  19418. configurable: true
  19419. });
  19420. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19421. /**
  19422. * material.lightmapTexture as only diffuse lighting from this light
  19423. * adds only specular lighting from this light
  19424. * adds dynamic shadows
  19425. */
  19426. get: function () {
  19427. return Light._LIGHTMAP_SPECULAR;
  19428. },
  19429. enumerable: true,
  19430. configurable: true
  19431. });
  19432. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19433. /**
  19434. * material.lightmapTexture as only lighting
  19435. * no light calculation from this light
  19436. * only adds dynamic shadows from this light
  19437. */
  19438. get: function () {
  19439. return Light._LIGHTMAP_SHADOWSONLY;
  19440. },
  19441. enumerable: true,
  19442. configurable: true
  19443. });
  19444. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19445. /**
  19446. * Each light type uses the default quantity according to its type:
  19447. * point/spot lights use luminous intensity
  19448. * directional lights use illuminance
  19449. */
  19450. get: function () {
  19451. return Light._INTENSITYMODE_AUTOMATIC;
  19452. },
  19453. enumerable: true,
  19454. configurable: true
  19455. });
  19456. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19457. /**
  19458. * lumen (lm)
  19459. */
  19460. get: function () {
  19461. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19467. /**
  19468. * candela (lm/sr)
  19469. */
  19470. get: function () {
  19471. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19472. },
  19473. enumerable: true,
  19474. configurable: true
  19475. });
  19476. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19477. /**
  19478. * lux (lm/m^2)
  19479. */
  19480. get: function () {
  19481. return Light._INTENSITYMODE_ILLUMINANCE;
  19482. },
  19483. enumerable: true,
  19484. configurable: true
  19485. });
  19486. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19487. /**
  19488. * nit (cd/m^2)
  19489. */
  19490. get: function () {
  19491. return Light._INTENSITYMODE_LUMINANCE;
  19492. },
  19493. enumerable: true,
  19494. configurable: true
  19495. });
  19496. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19497. /**
  19498. * Light type const id of the point light.
  19499. */
  19500. get: function () {
  19501. return Light._LIGHTTYPEID_POINTLIGHT;
  19502. },
  19503. enumerable: true,
  19504. configurable: true
  19505. });
  19506. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19507. /**
  19508. * Light type const id of the directional light.
  19509. */
  19510. get: function () {
  19511. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19512. },
  19513. enumerable: true,
  19514. configurable: true
  19515. });
  19516. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19517. /**
  19518. * Light type const id of the spot light.
  19519. */
  19520. get: function () {
  19521. return Light._LIGHTTYPEID_SPOTLIGHT;
  19522. },
  19523. enumerable: true,
  19524. configurable: true
  19525. });
  19526. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19527. /**
  19528. * Light type const id of the hemispheric light.
  19529. */
  19530. get: function () {
  19531. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19532. },
  19533. enumerable: true,
  19534. configurable: true
  19535. });
  19536. Object.defineProperty(Light.prototype, "intensityMode", {
  19537. /**
  19538. * Gets the photometric scale used to interpret the intensity.
  19539. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19540. */
  19541. get: function () {
  19542. return this._intensityMode;
  19543. },
  19544. /**
  19545. * Sets the photometric scale used to interpret the intensity.
  19546. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19547. */
  19548. set: function (value) {
  19549. this._intensityMode = value;
  19550. this._computePhotometricScale();
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. ;
  19556. ;
  19557. Object.defineProperty(Light.prototype, "radius", {
  19558. /**
  19559. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19560. */
  19561. get: function () {
  19562. return this._radius;
  19563. },
  19564. /**
  19565. * sets the light radius used by PBR Materials to simulate soft area lights.
  19566. */
  19567. set: function (value) {
  19568. this._radius = value;
  19569. this._computePhotometricScale();
  19570. },
  19571. enumerable: true,
  19572. configurable: true
  19573. });
  19574. ;
  19575. ;
  19576. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19577. /**
  19578. * Gets the only meshes impacted by this light.
  19579. */
  19580. get: function () {
  19581. return this._includedOnlyMeshes;
  19582. },
  19583. /**
  19584. * Sets the only meshes impacted by this light.
  19585. */
  19586. set: function (value) {
  19587. this._includedOnlyMeshes = value;
  19588. this._hookArrayForIncludedOnly(value);
  19589. },
  19590. enumerable: true,
  19591. configurable: true
  19592. });
  19593. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19594. /**
  19595. * Gets the meshes not impacted by this light.
  19596. */
  19597. get: function () {
  19598. return this._excludedMeshes;
  19599. },
  19600. /**
  19601. * Sets the meshes not impacted by this light.
  19602. */
  19603. set: function (value) {
  19604. this._excludedMeshes = value;
  19605. this._hookArrayForExcluded(value);
  19606. },
  19607. enumerable: true,
  19608. configurable: true
  19609. });
  19610. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19611. /**
  19612. * Gets the layer id use to find what meshes are not impacted by the light.
  19613. * Inactive if 0
  19614. */
  19615. get: function () {
  19616. return this._excludeWithLayerMask;
  19617. },
  19618. /**
  19619. * Sets the layer id use to find what meshes are not impacted by the light.
  19620. * Inactive if 0
  19621. */
  19622. set: function (value) {
  19623. this._excludeWithLayerMask = value;
  19624. this._resyncMeshes();
  19625. },
  19626. enumerable: true,
  19627. configurable: true
  19628. });
  19629. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19630. /**
  19631. * Gets the layer id use to find what meshes are impacted by the light.
  19632. * Inactive if 0
  19633. */
  19634. get: function () {
  19635. return this._includeOnlyWithLayerMask;
  19636. },
  19637. /**
  19638. * Sets the layer id use to find what meshes are impacted by the light.
  19639. * Inactive if 0
  19640. */
  19641. set: function (value) {
  19642. this._includeOnlyWithLayerMask = value;
  19643. this._resyncMeshes();
  19644. },
  19645. enumerable: true,
  19646. configurable: true
  19647. });
  19648. Object.defineProperty(Light.prototype, "lightmapMode", {
  19649. /**
  19650. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19651. */
  19652. get: function () {
  19653. return this._lightmapMode;
  19654. },
  19655. /**
  19656. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19657. */
  19658. set: function (value) {
  19659. if (this._lightmapMode === value) {
  19660. return;
  19661. }
  19662. this._lightmapMode = value;
  19663. this._markMeshesAsLightDirty();
  19664. },
  19665. enumerable: true,
  19666. configurable: true
  19667. });
  19668. /**
  19669. * Returns the string "Light".
  19670. * @returns the class name
  19671. */
  19672. Light.prototype.getClassName = function () {
  19673. return "Light";
  19674. };
  19675. /**
  19676. * Converts the light information to a readable string for debug purpose.
  19677. * @param fullDetails Supports for multiple levels of logging within scene loading
  19678. * @returns the human readable light info
  19679. */
  19680. Light.prototype.toString = function (fullDetails) {
  19681. var ret = "Name: " + this.name;
  19682. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19683. if (this.animations) {
  19684. for (var i = 0; i < this.animations.length; i++) {
  19685. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19686. }
  19687. }
  19688. if (fullDetails) {
  19689. }
  19690. return ret;
  19691. };
  19692. /**
  19693. * Set the enabled state of this node.
  19694. * @param value - the new enabled state
  19695. * @see isEnabled
  19696. */
  19697. Light.prototype.setEnabled = function (value) {
  19698. _super.prototype.setEnabled.call(this, value);
  19699. this._resyncMeshes();
  19700. };
  19701. /**
  19702. * Returns the Light associated shadow generator if any.
  19703. * @return the associated shadow generator.
  19704. */
  19705. Light.prototype.getShadowGenerator = function () {
  19706. return this._shadowGenerator;
  19707. };
  19708. /**
  19709. * Returns a Vector3, the absolute light position in the World.
  19710. * @returns the world space position of the light
  19711. */
  19712. Light.prototype.getAbsolutePosition = function () {
  19713. return BABYLON.Vector3.Zero();
  19714. };
  19715. /**
  19716. * Specifies if the light will affect the passed mesh.
  19717. * @param mesh The mesh to test against the light
  19718. * @return true the mesh is affected otherwise, false.
  19719. */
  19720. Light.prototype.canAffectMesh = function (mesh) {
  19721. if (!mesh) {
  19722. return true;
  19723. }
  19724. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19725. return false;
  19726. }
  19727. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19728. return false;
  19729. }
  19730. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19731. return false;
  19732. }
  19733. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19734. return false;
  19735. }
  19736. return true;
  19737. };
  19738. /**
  19739. * Computes and Returns the light World matrix.
  19740. * @returns the world matrix
  19741. */
  19742. Light.prototype.getWorldMatrix = function () {
  19743. this._currentRenderId = this.getScene().getRenderId();
  19744. var worldMatrix = this._getWorldMatrix();
  19745. if (this.parent && this.parent.getWorldMatrix) {
  19746. if (!this._parentedWorldMatrix) {
  19747. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19748. }
  19749. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19750. this._markSyncedWithParent();
  19751. return this._parentedWorldMatrix;
  19752. }
  19753. return worldMatrix;
  19754. };
  19755. /**
  19756. * Sort function to order lights for rendering.
  19757. * @param a First Light object to compare to second.
  19758. * @param b Second Light object to compare first.
  19759. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19760. */
  19761. Light.CompareLightsPriority = function (a, b) {
  19762. //shadow-casting lights have priority over non-shadow-casting lights
  19763. //the renderPrioirty is a secondary sort criterion
  19764. if (a.shadowEnabled !== b.shadowEnabled) {
  19765. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19766. }
  19767. return b.renderPriority - a.renderPriority;
  19768. };
  19769. /**
  19770. * Releases resources associated with this node.
  19771. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19772. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19773. */
  19774. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19775. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19776. if (this._shadowGenerator) {
  19777. this._shadowGenerator.dispose();
  19778. this._shadowGenerator = null;
  19779. }
  19780. // Animations
  19781. this.getScene().stopAnimation(this);
  19782. // Remove from meshes
  19783. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19784. var mesh = _a[_i];
  19785. mesh._removeLightSource(this);
  19786. }
  19787. this._uniformBuffer.dispose();
  19788. // Remove from scene
  19789. this.getScene().removeLight(this);
  19790. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19791. };
  19792. /**
  19793. * Returns the light type ID (integer).
  19794. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19795. */
  19796. Light.prototype.getTypeID = function () {
  19797. return 0;
  19798. };
  19799. /**
  19800. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19801. * @returns the scaled intensity in intensity mode unit
  19802. */
  19803. Light.prototype.getScaledIntensity = function () {
  19804. return this._photometricScale * this.intensity;
  19805. };
  19806. /**
  19807. * Returns a new Light object, named "name", from the current one.
  19808. * @param name The name of the cloned light
  19809. * @returns the new created light
  19810. */
  19811. Light.prototype.clone = function (name) {
  19812. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19813. if (!constructor) {
  19814. return null;
  19815. }
  19816. return BABYLON.SerializationHelper.Clone(constructor, this);
  19817. };
  19818. /**
  19819. * Serializes the current light into a Serialization object.
  19820. * @returns the serialized object.
  19821. */
  19822. Light.prototype.serialize = function () {
  19823. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19824. // Type
  19825. serializationObject.type = this.getTypeID();
  19826. // Parent
  19827. if (this.parent) {
  19828. serializationObject.parentId = this.parent.id;
  19829. }
  19830. // Inclusion / exclusions
  19831. if (this.excludedMeshes.length > 0) {
  19832. serializationObject.excludedMeshesIds = [];
  19833. this.excludedMeshes.forEach(function (mesh) {
  19834. serializationObject.excludedMeshesIds.push(mesh.id);
  19835. });
  19836. }
  19837. if (this.includedOnlyMeshes.length > 0) {
  19838. serializationObject.includedOnlyMeshesIds = [];
  19839. this.includedOnlyMeshes.forEach(function (mesh) {
  19840. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19841. });
  19842. }
  19843. // Animations
  19844. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19845. serializationObject.ranges = this.serializeAnimationRanges();
  19846. return serializationObject;
  19847. };
  19848. /**
  19849. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19850. * This new light is named "name" and added to the passed scene.
  19851. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19852. * @param name The friendly name of the light
  19853. * @param scene The scene the new light will belong to
  19854. * @returns the constructor function
  19855. */
  19856. Light.GetConstructorFromName = function (type, name, scene) {
  19857. switch (type) {
  19858. case 0:
  19859. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19860. case 1:
  19861. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19862. case 2:
  19863. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19864. case 3:
  19865. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19866. }
  19867. return null;
  19868. };
  19869. /**
  19870. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19871. * @param parsedLight The JSON representation of the light
  19872. * @param scene The scene to create the parsed light in
  19873. * @returns the created light after parsing
  19874. */
  19875. Light.Parse = function (parsedLight, scene) {
  19876. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19877. if (!constructor) {
  19878. return null;
  19879. }
  19880. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19881. // Inclusion / exclusions
  19882. if (parsedLight.excludedMeshesIds) {
  19883. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19884. }
  19885. if (parsedLight.includedOnlyMeshesIds) {
  19886. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19887. }
  19888. // Parent
  19889. if (parsedLight.parentId) {
  19890. light._waitingParentId = parsedLight.parentId;
  19891. }
  19892. // Animations
  19893. if (parsedLight.animations) {
  19894. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19895. var parsedAnimation = parsedLight.animations[animationIndex];
  19896. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19897. }
  19898. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19899. }
  19900. if (parsedLight.autoAnimate) {
  19901. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19902. }
  19903. return light;
  19904. };
  19905. Light.prototype._hookArrayForExcluded = function (array) {
  19906. var _this = this;
  19907. var oldPush = array.push;
  19908. array.push = function () {
  19909. var items = [];
  19910. for (var _i = 0; _i < arguments.length; _i++) {
  19911. items[_i] = arguments[_i];
  19912. }
  19913. var result = oldPush.apply(array, items);
  19914. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19915. var item = items_1[_a];
  19916. item._resyncLighSource(_this);
  19917. }
  19918. return result;
  19919. };
  19920. var oldSplice = array.splice;
  19921. array.splice = function (index, deleteCount) {
  19922. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19923. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19924. var item = deleted_1[_i];
  19925. item._resyncLighSource(_this);
  19926. }
  19927. return deleted;
  19928. };
  19929. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19930. var item = array_1[_i];
  19931. item._resyncLighSource(this);
  19932. }
  19933. };
  19934. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19935. var _this = this;
  19936. var oldPush = array.push;
  19937. array.push = function () {
  19938. var items = [];
  19939. for (var _i = 0; _i < arguments.length; _i++) {
  19940. items[_i] = arguments[_i];
  19941. }
  19942. var result = oldPush.apply(array, items);
  19943. _this._resyncMeshes();
  19944. return result;
  19945. };
  19946. var oldSplice = array.splice;
  19947. array.splice = function (index, deleteCount) {
  19948. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19949. _this._resyncMeshes();
  19950. return deleted;
  19951. };
  19952. this._resyncMeshes();
  19953. };
  19954. Light.prototype._resyncMeshes = function () {
  19955. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19956. var mesh = _a[_i];
  19957. mesh._resyncLighSource(this);
  19958. }
  19959. };
  19960. /**
  19961. * Forces the meshes to update their light related information in their rendering used effects
  19962. * @ignore Internal Use Only
  19963. */
  19964. Light.prototype._markMeshesAsLightDirty = function () {
  19965. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19966. var mesh = _a[_i];
  19967. if (mesh._lightSources.indexOf(this) !== -1) {
  19968. mesh._markSubMeshesAsLightDirty();
  19969. }
  19970. }
  19971. };
  19972. /**
  19973. * Recomputes the cached photometric scale if needed.
  19974. */
  19975. Light.prototype._computePhotometricScale = function () {
  19976. this._photometricScale = this._getPhotometricScale();
  19977. this.getScene().resetCachedMaterial();
  19978. };
  19979. /**
  19980. * Returns the Photometric Scale according to the light type and intensity mode.
  19981. */
  19982. Light.prototype._getPhotometricScale = function () {
  19983. var photometricScale = 0.0;
  19984. var lightTypeID = this.getTypeID();
  19985. //get photometric mode
  19986. var photometricMode = this.intensityMode;
  19987. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19988. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19989. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19990. }
  19991. else {
  19992. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19993. }
  19994. }
  19995. //compute photometric scale
  19996. switch (lightTypeID) {
  19997. case Light.LIGHTTYPEID_POINTLIGHT:
  19998. case Light.LIGHTTYPEID_SPOTLIGHT:
  19999. switch (photometricMode) {
  20000. case Light.INTENSITYMODE_LUMINOUSPOWER:
  20001. photometricScale = 1.0 / (4.0 * Math.PI);
  20002. break;
  20003. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  20004. photometricScale = 1.0;
  20005. break;
  20006. case Light.INTENSITYMODE_LUMINANCE:
  20007. photometricScale = this.radius * this.radius;
  20008. break;
  20009. }
  20010. break;
  20011. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  20012. switch (photometricMode) {
  20013. case Light.INTENSITYMODE_ILLUMINANCE:
  20014. photometricScale = 1.0;
  20015. break;
  20016. case Light.INTENSITYMODE_LUMINANCE:
  20017. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  20018. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  20019. var apexAngleRadians = this.radius;
  20020. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  20021. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  20022. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  20023. photometricScale = solidAngle;
  20024. break;
  20025. }
  20026. break;
  20027. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  20028. // No fall off in hemisperic light.
  20029. photometricScale = 1.0;
  20030. break;
  20031. }
  20032. return photometricScale;
  20033. };
  20034. /**
  20035. * Reorder the light in the scene according to their defined priority.
  20036. * @ignore Internal Use Only
  20037. */
  20038. Light.prototype._reorderLightsInScene = function () {
  20039. var scene = this.getScene();
  20040. if (this._renderPriority != 0) {
  20041. scene.requireLightSorting = true;
  20042. }
  20043. this.getScene().sortLightsByPriority();
  20044. };
  20045. //lightmapMode Consts
  20046. Light._LIGHTMAP_DEFAULT = 0;
  20047. Light._LIGHTMAP_SPECULAR = 1;
  20048. Light._LIGHTMAP_SHADOWSONLY = 2;
  20049. // Intensity Mode Consts
  20050. Light._INTENSITYMODE_AUTOMATIC = 0;
  20051. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  20052. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  20053. Light._INTENSITYMODE_ILLUMINANCE = 3;
  20054. Light._INTENSITYMODE_LUMINANCE = 4;
  20055. // Light types ids const.
  20056. Light._LIGHTTYPEID_POINTLIGHT = 0;
  20057. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  20058. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  20059. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  20060. __decorate([
  20061. BABYLON.serializeAsColor3()
  20062. ], Light.prototype, "diffuse", void 0);
  20063. __decorate([
  20064. BABYLON.serializeAsColor3()
  20065. ], Light.prototype, "specular", void 0);
  20066. __decorate([
  20067. BABYLON.serialize()
  20068. ], Light.prototype, "intensity", void 0);
  20069. __decorate([
  20070. BABYLON.serialize()
  20071. ], Light.prototype, "range", void 0);
  20072. __decorate([
  20073. BABYLON.serialize()
  20074. ], Light.prototype, "intensityMode", null);
  20075. __decorate([
  20076. BABYLON.serialize()
  20077. ], Light.prototype, "radius", null);
  20078. __decorate([
  20079. BABYLON.serialize()
  20080. ], Light.prototype, "_renderPriority", void 0);
  20081. __decorate([
  20082. BABYLON.expandToProperty("_reorderLightsInScene")
  20083. ], Light.prototype, "renderPriority", void 0);
  20084. __decorate([
  20085. BABYLON.serialize()
  20086. ], Light.prototype, "shadowEnabled", void 0);
  20087. __decorate([
  20088. BABYLON.serialize("excludeWithLayerMask")
  20089. ], Light.prototype, "_excludeWithLayerMask", void 0);
  20090. __decorate([
  20091. BABYLON.serialize("includeOnlyWithLayerMask")
  20092. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  20093. __decorate([
  20094. BABYLON.serialize("lightmapMode")
  20095. ], Light.prototype, "_lightmapMode", void 0);
  20096. return Light;
  20097. }(BABYLON.Node));
  20098. BABYLON.Light = Light;
  20099. })(BABYLON || (BABYLON = {}));
  20100. //# sourceMappingURL=babylon.light.js.map
  20101. "use strict";
  20102. var BABYLON;
  20103. (function (BABYLON) {
  20104. var Camera = /** @class */ (function (_super) {
  20105. __extends(Camera, _super);
  20106. function Camera(name, position, scene) {
  20107. var _this = _super.call(this, name, scene) || this;
  20108. /**
  20109. * The vector the camera should consider as up.
  20110. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20111. */
  20112. _this.upVector = BABYLON.Vector3.Up();
  20113. _this.orthoLeft = null;
  20114. _this.orthoRight = null;
  20115. _this.orthoBottom = null;
  20116. _this.orthoTop = null;
  20117. /**
  20118. * FOV is set in Radians. (default is 0.8)
  20119. */
  20120. _this.fov = 0.8;
  20121. _this.minZ = 1;
  20122. _this.maxZ = 10000.0;
  20123. _this.inertia = 0.9;
  20124. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20125. _this.isIntermediate = false;
  20126. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20127. /**
  20128. * Restricts the camera to viewing objects with the same layerMask.
  20129. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20130. */
  20131. _this.layerMask = 0x0FFFFFFF;
  20132. /**
  20133. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20134. */
  20135. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20136. // Camera rig members
  20137. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20138. _this._rigCameras = new Array();
  20139. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20140. _this._skipRendering = false;
  20141. _this.customRenderTargets = new Array();
  20142. // Observables
  20143. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20144. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20145. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20146. _this.onRestoreStateObservable = new BABYLON.Observable();
  20147. // Cache
  20148. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20149. _this._projectionMatrix = new BABYLON.Matrix();
  20150. _this._doNotComputeProjectionMatrix = false;
  20151. _this._postProcesses = new Array();
  20152. _this._transformMatrix = BABYLON.Matrix.Zero();
  20153. _this._activeMeshes = new BABYLON.SmartArray(256);
  20154. _this._globalPosition = BABYLON.Vector3.Zero();
  20155. _this._refreshFrustumPlanes = true;
  20156. _this.getScene().addCamera(_this);
  20157. if (!_this.getScene().activeCamera) {
  20158. _this.getScene().activeCamera = _this;
  20159. }
  20160. _this.position = position;
  20161. return _this;
  20162. }
  20163. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20164. get: function () {
  20165. return Camera._PERSPECTIVE_CAMERA;
  20166. },
  20167. enumerable: true,
  20168. configurable: true
  20169. });
  20170. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20171. get: function () {
  20172. return Camera._ORTHOGRAPHIC_CAMERA;
  20173. },
  20174. enumerable: true,
  20175. configurable: true
  20176. });
  20177. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20178. /**
  20179. * This is the default FOV mode for perspective cameras.
  20180. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20181. *
  20182. */
  20183. get: function () {
  20184. return Camera._FOVMODE_VERTICAL_FIXED;
  20185. },
  20186. enumerable: true,
  20187. configurable: true
  20188. });
  20189. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20190. /**
  20191. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20192. *
  20193. */
  20194. get: function () {
  20195. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20196. },
  20197. enumerable: true,
  20198. configurable: true
  20199. });
  20200. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20201. get: function () {
  20202. return Camera._RIG_MODE_NONE;
  20203. },
  20204. enumerable: true,
  20205. configurable: true
  20206. });
  20207. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20208. get: function () {
  20209. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20210. },
  20211. enumerable: true,
  20212. configurable: true
  20213. });
  20214. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20215. get: function () {
  20216. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20217. },
  20218. enumerable: true,
  20219. configurable: true
  20220. });
  20221. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20222. get: function () {
  20223. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20224. },
  20225. enumerable: true,
  20226. configurable: true
  20227. });
  20228. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20229. get: function () {
  20230. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20231. },
  20232. enumerable: true,
  20233. configurable: true
  20234. });
  20235. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20236. get: function () {
  20237. return Camera._RIG_MODE_VR;
  20238. },
  20239. enumerable: true,
  20240. configurable: true
  20241. });
  20242. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20243. get: function () {
  20244. return Camera._RIG_MODE_WEBVR;
  20245. },
  20246. enumerable: true,
  20247. configurable: true
  20248. });
  20249. /**
  20250. * Store current camera state (fov, position, etc..)
  20251. */
  20252. Camera.prototype.storeState = function () {
  20253. this._stateStored = true;
  20254. this._storedFov = this.fov;
  20255. return this;
  20256. };
  20257. /**
  20258. * Restores the camera state values if it has been stored. You must call storeState() first
  20259. */
  20260. Camera.prototype._restoreStateValues = function () {
  20261. if (!this._stateStored) {
  20262. return false;
  20263. }
  20264. this.fov = this._storedFov;
  20265. return true;
  20266. };
  20267. /**
  20268. * Restored camera state. You must call storeState() first
  20269. */
  20270. Camera.prototype.restoreState = function () {
  20271. if (this._restoreStateValues()) {
  20272. this.onRestoreStateObservable.notifyObservers(this);
  20273. return true;
  20274. }
  20275. return false;
  20276. };
  20277. Camera.prototype.getClassName = function () {
  20278. return "Camera";
  20279. };
  20280. /**
  20281. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20282. */
  20283. Camera.prototype.toString = function (fullDetails) {
  20284. var ret = "Name: " + this.name;
  20285. ret += ", type: " + this.getClassName();
  20286. if (this.animations) {
  20287. for (var i = 0; i < this.animations.length; i++) {
  20288. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20289. }
  20290. }
  20291. if (fullDetails) {
  20292. }
  20293. return ret;
  20294. };
  20295. Object.defineProperty(Camera.prototype, "globalPosition", {
  20296. get: function () {
  20297. return this._globalPosition;
  20298. },
  20299. enumerable: true,
  20300. configurable: true
  20301. });
  20302. Camera.prototype.getActiveMeshes = function () {
  20303. return this._activeMeshes;
  20304. };
  20305. Camera.prototype.isActiveMesh = function (mesh) {
  20306. return (this._activeMeshes.indexOf(mesh) !== -1);
  20307. };
  20308. //Cache
  20309. Camera.prototype._initCache = function () {
  20310. _super.prototype._initCache.call(this);
  20311. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20312. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20313. this._cache.mode = undefined;
  20314. this._cache.minZ = undefined;
  20315. this._cache.maxZ = undefined;
  20316. this._cache.fov = undefined;
  20317. this._cache.fovMode = undefined;
  20318. this._cache.aspectRatio = undefined;
  20319. this._cache.orthoLeft = undefined;
  20320. this._cache.orthoRight = undefined;
  20321. this._cache.orthoBottom = undefined;
  20322. this._cache.orthoTop = undefined;
  20323. this._cache.renderWidth = undefined;
  20324. this._cache.renderHeight = undefined;
  20325. };
  20326. Camera.prototype._updateCache = function (ignoreParentClass) {
  20327. if (!ignoreParentClass) {
  20328. _super.prototype._updateCache.call(this);
  20329. }
  20330. this._cache.position.copyFrom(this.position);
  20331. this._cache.upVector.copyFrom(this.upVector);
  20332. };
  20333. // Synchronized
  20334. Camera.prototype._isSynchronized = function () {
  20335. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20336. };
  20337. Camera.prototype._isSynchronizedViewMatrix = function () {
  20338. if (!_super.prototype._isSynchronized.call(this))
  20339. return false;
  20340. return this._cache.position.equals(this.position)
  20341. && this._cache.upVector.equals(this.upVector)
  20342. && this.isSynchronizedWithParent();
  20343. };
  20344. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20345. var check = this._cache.mode === this.mode
  20346. && this._cache.minZ === this.minZ
  20347. && this._cache.maxZ === this.maxZ;
  20348. if (!check) {
  20349. return false;
  20350. }
  20351. var engine = this.getEngine();
  20352. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20353. check = this._cache.fov === this.fov
  20354. && this._cache.fovMode === this.fovMode
  20355. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20356. }
  20357. else {
  20358. check = this._cache.orthoLeft === this.orthoLeft
  20359. && this._cache.orthoRight === this.orthoRight
  20360. && this._cache.orthoBottom === this.orthoBottom
  20361. && this._cache.orthoTop === this.orthoTop
  20362. && this._cache.renderWidth === engine.getRenderWidth()
  20363. && this._cache.renderHeight === engine.getRenderHeight();
  20364. }
  20365. return check;
  20366. };
  20367. // Controls
  20368. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20369. };
  20370. Camera.prototype.detachControl = function (element) {
  20371. };
  20372. Camera.prototype.update = function () {
  20373. this._checkInputs();
  20374. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20375. this._updateRigCameras();
  20376. }
  20377. };
  20378. Camera.prototype._checkInputs = function () {
  20379. this.onAfterCheckInputsObservable.notifyObservers(this);
  20380. };
  20381. Object.defineProperty(Camera.prototype, "rigCameras", {
  20382. get: function () {
  20383. return this._rigCameras;
  20384. },
  20385. enumerable: true,
  20386. configurable: true
  20387. });
  20388. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20389. get: function () {
  20390. return this._rigPostProcess;
  20391. },
  20392. enumerable: true,
  20393. configurable: true
  20394. });
  20395. /**
  20396. * Internal, gets the first post proces.
  20397. * @returns the first post process to be run on this camera.
  20398. */
  20399. Camera.prototype._getFirstPostProcess = function () {
  20400. for (var pp in this._postProcesses) {
  20401. if (this._postProcesses[pp] !== null) {
  20402. return this._postProcesses[pp];
  20403. }
  20404. }
  20405. return null;
  20406. };
  20407. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20408. // invalidate framebuffer
  20409. var firstPostProcess = this._getFirstPostProcess();
  20410. if (firstPostProcess) {
  20411. firstPostProcess.markTextureDirty();
  20412. }
  20413. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20414. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20415. var cam = this._rigCameras[i];
  20416. var rigPostProcess = cam._rigPostProcess;
  20417. // for VR rig, there does not have to be a post process
  20418. if (rigPostProcess) {
  20419. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20420. if (isPass) {
  20421. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20422. cam.isIntermediate = this._postProcesses.length === 0;
  20423. }
  20424. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20425. rigPostProcess.markTextureDirty();
  20426. }
  20427. else {
  20428. cam._postProcesses = this._postProcesses.slice(0);
  20429. }
  20430. }
  20431. };
  20432. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20433. if (insertAt === void 0) { insertAt = null; }
  20434. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20435. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20436. return 0;
  20437. }
  20438. if (insertAt == null || insertAt < 0) {
  20439. this._postProcesses.push(postProcess);
  20440. }
  20441. else if (this._postProcesses[insertAt] === null) {
  20442. this._postProcesses[insertAt] = postProcess;
  20443. }
  20444. else {
  20445. this._postProcesses.splice(insertAt, 0, postProcess);
  20446. }
  20447. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20448. return this._postProcesses.indexOf(postProcess);
  20449. };
  20450. Camera.prototype.detachPostProcess = function (postProcess) {
  20451. var idx = this._postProcesses.indexOf(postProcess);
  20452. if (idx !== -1) {
  20453. this._postProcesses[idx] = null;
  20454. }
  20455. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20456. };
  20457. Camera.prototype.getWorldMatrix = function () {
  20458. if (!this._worldMatrix) {
  20459. this._worldMatrix = BABYLON.Matrix.Identity();
  20460. }
  20461. var viewMatrix = this.getViewMatrix();
  20462. viewMatrix.invertToRef(this._worldMatrix);
  20463. return this._worldMatrix;
  20464. };
  20465. Camera.prototype._getViewMatrix = function () {
  20466. return BABYLON.Matrix.Identity();
  20467. };
  20468. Camera.prototype.getViewMatrix = function (force) {
  20469. if (!force && this._isSynchronizedViewMatrix()) {
  20470. return this._computedViewMatrix;
  20471. }
  20472. this.updateCache();
  20473. this._computedViewMatrix = this._getViewMatrix();
  20474. this._currentRenderId = this.getScene().getRenderId();
  20475. this._refreshFrustumPlanes = true;
  20476. if (!this.parent || !this.parent.getWorldMatrix) {
  20477. this._globalPosition.copyFrom(this.position);
  20478. }
  20479. else {
  20480. if (!this._worldMatrix) {
  20481. this._worldMatrix = BABYLON.Matrix.Identity();
  20482. }
  20483. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20484. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20485. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20486. this._computedViewMatrix.invert();
  20487. this._markSyncedWithParent();
  20488. }
  20489. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20490. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20491. }
  20492. this.onViewMatrixChangedObservable.notifyObservers(this);
  20493. return this._computedViewMatrix;
  20494. };
  20495. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20496. this._doNotComputeProjectionMatrix = true;
  20497. if (projection !== undefined) {
  20498. this._projectionMatrix = projection;
  20499. }
  20500. };
  20501. ;
  20502. Camera.prototype.unfreezeProjectionMatrix = function () {
  20503. this._doNotComputeProjectionMatrix = false;
  20504. };
  20505. ;
  20506. Camera.prototype.getProjectionMatrix = function (force) {
  20507. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20508. return this._projectionMatrix;
  20509. }
  20510. // Cache
  20511. this._cache.mode = this.mode;
  20512. this._cache.minZ = this.minZ;
  20513. this._cache.maxZ = this.maxZ;
  20514. // Matrix
  20515. this._refreshFrustumPlanes = true;
  20516. var engine = this.getEngine();
  20517. var scene = this.getScene();
  20518. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20519. this._cache.fov = this.fov;
  20520. this._cache.fovMode = this.fovMode;
  20521. this._cache.aspectRatio = engine.getAspectRatio(this);
  20522. if (this.minZ <= 0) {
  20523. this.minZ = 0.1;
  20524. }
  20525. if (scene.useRightHandedSystem) {
  20526. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20527. }
  20528. else {
  20529. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20530. }
  20531. }
  20532. else {
  20533. var halfWidth = engine.getRenderWidth() / 2.0;
  20534. var halfHeight = engine.getRenderHeight() / 2.0;
  20535. if (scene.useRightHandedSystem) {
  20536. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20537. }
  20538. else {
  20539. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20540. }
  20541. this._cache.orthoLeft = this.orthoLeft;
  20542. this._cache.orthoRight = this.orthoRight;
  20543. this._cache.orthoBottom = this.orthoBottom;
  20544. this._cache.orthoTop = this.orthoTop;
  20545. this._cache.renderWidth = engine.getRenderWidth();
  20546. this._cache.renderHeight = engine.getRenderHeight();
  20547. }
  20548. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20549. return this._projectionMatrix;
  20550. };
  20551. Camera.prototype.getTranformationMatrix = function () {
  20552. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20553. return this._transformMatrix;
  20554. };
  20555. Camera.prototype.updateFrustumPlanes = function () {
  20556. if (!this._refreshFrustumPlanes) {
  20557. return;
  20558. }
  20559. this.getTranformationMatrix();
  20560. if (!this._frustumPlanes) {
  20561. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20562. }
  20563. else {
  20564. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20565. }
  20566. this._refreshFrustumPlanes = false;
  20567. };
  20568. Camera.prototype.isInFrustum = function (target) {
  20569. this.updateFrustumPlanes();
  20570. return target.isInFrustum(this._frustumPlanes);
  20571. };
  20572. Camera.prototype.isCompletelyInFrustum = function (target) {
  20573. this.updateFrustumPlanes();
  20574. return target.isCompletelyInFrustum(this._frustumPlanes);
  20575. };
  20576. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20577. if (length === void 0) { length = 100; }
  20578. if (!transform) {
  20579. transform = this.getWorldMatrix();
  20580. }
  20581. if (!origin) {
  20582. origin = this.position;
  20583. }
  20584. var forward = new BABYLON.Vector3(0, 0, 1);
  20585. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20586. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20587. return new BABYLON.Ray(origin, direction, length);
  20588. };
  20589. /**
  20590. * Releases resources associated with this node.
  20591. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20592. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20593. */
  20594. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20595. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20596. // Observables
  20597. this.onViewMatrixChangedObservable.clear();
  20598. this.onProjectionMatrixChangedObservable.clear();
  20599. this.onAfterCheckInputsObservable.clear();
  20600. this.onRestoreStateObservable.clear();
  20601. // Inputs
  20602. if (this.inputs) {
  20603. this.inputs.clear();
  20604. }
  20605. // Animations
  20606. this.getScene().stopAnimation(this);
  20607. // Remove from scene
  20608. this.getScene().removeCamera(this);
  20609. while (this._rigCameras.length > 0) {
  20610. var camera = this._rigCameras.pop();
  20611. if (camera) {
  20612. camera.dispose();
  20613. }
  20614. }
  20615. // Postprocesses
  20616. if (this._rigPostProcess) {
  20617. this._rigPostProcess.dispose(this);
  20618. this._rigPostProcess = null;
  20619. this._postProcesses = [];
  20620. }
  20621. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20622. this._rigPostProcess = null;
  20623. this._postProcesses = [];
  20624. }
  20625. else {
  20626. var i = this._postProcesses.length;
  20627. while (--i >= 0) {
  20628. var postProcess = this._postProcesses[i];
  20629. if (postProcess) {
  20630. postProcess.dispose(this);
  20631. }
  20632. }
  20633. }
  20634. // Render targets
  20635. var i = this.customRenderTargets.length;
  20636. while (--i >= 0) {
  20637. this.customRenderTargets[i].dispose();
  20638. }
  20639. this.customRenderTargets = [];
  20640. // Active Meshes
  20641. this._activeMeshes.dispose();
  20642. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20643. };
  20644. Object.defineProperty(Camera.prototype, "leftCamera", {
  20645. // ---- Camera rigs section ----
  20646. get: function () {
  20647. if (this._rigCameras.length < 1) {
  20648. return null;
  20649. }
  20650. return this._rigCameras[0];
  20651. },
  20652. enumerable: true,
  20653. configurable: true
  20654. });
  20655. Object.defineProperty(Camera.prototype, "rightCamera", {
  20656. get: function () {
  20657. if (this._rigCameras.length < 2) {
  20658. return null;
  20659. }
  20660. return this._rigCameras[1];
  20661. },
  20662. enumerable: true,
  20663. configurable: true
  20664. });
  20665. Camera.prototype.getLeftTarget = function () {
  20666. if (this._rigCameras.length < 1) {
  20667. return null;
  20668. }
  20669. return this._rigCameras[0].getTarget();
  20670. };
  20671. Camera.prototype.getRightTarget = function () {
  20672. if (this._rigCameras.length < 2) {
  20673. return null;
  20674. }
  20675. return this._rigCameras[1].getTarget();
  20676. };
  20677. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20678. if (this.cameraRigMode === mode) {
  20679. return;
  20680. }
  20681. while (this._rigCameras.length > 0) {
  20682. var camera = this._rigCameras.pop();
  20683. if (camera) {
  20684. camera.dispose();
  20685. }
  20686. }
  20687. this.cameraRigMode = mode;
  20688. this._cameraRigParams = {};
  20689. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20690. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20691. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20692. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20693. // create the rig cameras, unless none
  20694. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20695. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20696. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20697. if (leftCamera && rightCamera) {
  20698. this._rigCameras.push(leftCamera);
  20699. this._rigCameras.push(rightCamera);
  20700. }
  20701. }
  20702. switch (this.cameraRigMode) {
  20703. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20704. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20705. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20706. break;
  20707. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20708. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20709. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20710. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20711. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20712. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20713. break;
  20714. case Camera.RIG_MODE_VR:
  20715. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20716. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20717. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20718. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20719. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20720. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20721. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20722. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20723. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20724. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20725. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20726. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20727. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20728. if (metrics.compensateDistortion) {
  20729. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20730. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20731. }
  20732. break;
  20733. case Camera.RIG_MODE_WEBVR:
  20734. if (rigParams.vrDisplay) {
  20735. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20736. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20737. //Left eye
  20738. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20739. this._rigCameras[0].setCameraRigParameter("left", true);
  20740. //leaving this for future reference
  20741. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20742. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20743. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20744. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20745. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20746. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20747. this._rigCameras[0].parent = this;
  20748. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20749. //Right eye
  20750. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20751. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20752. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20753. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20754. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20755. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20756. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20757. this._rigCameras[1].parent = this;
  20758. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20759. if (Camera.UseAlternateWebVRRendering) {
  20760. this._rigCameras[1]._skipRendering = true;
  20761. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20762. }
  20763. }
  20764. break;
  20765. }
  20766. this._cascadePostProcessesToRigCams();
  20767. this.update();
  20768. };
  20769. Camera.prototype._getVRProjectionMatrix = function () {
  20770. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20771. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20772. return this._projectionMatrix;
  20773. };
  20774. Camera.prototype._updateCameraRotationMatrix = function () {
  20775. //Here for WebVR
  20776. };
  20777. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20778. //Here for WebVR
  20779. };
  20780. /**
  20781. * This function MUST be overwritten by the different WebVR cameras available.
  20782. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20783. */
  20784. Camera.prototype._getWebVRProjectionMatrix = function () {
  20785. return BABYLON.Matrix.Identity();
  20786. };
  20787. /**
  20788. * This function MUST be overwritten by the different WebVR cameras available.
  20789. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20790. */
  20791. Camera.prototype._getWebVRViewMatrix = function () {
  20792. return BABYLON.Matrix.Identity();
  20793. };
  20794. Camera.prototype.setCameraRigParameter = function (name, value) {
  20795. if (!this._cameraRigParams) {
  20796. this._cameraRigParams = {};
  20797. }
  20798. this._cameraRigParams[name] = value;
  20799. //provisionnally:
  20800. if (name === "interaxialDistance") {
  20801. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20802. }
  20803. };
  20804. /**
  20805. * needs to be overridden by children so sub has required properties to be copied
  20806. */
  20807. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20808. return null;
  20809. };
  20810. /**
  20811. * May need to be overridden by children
  20812. */
  20813. Camera.prototype._updateRigCameras = function () {
  20814. for (var i = 0; i < this._rigCameras.length; i++) {
  20815. this._rigCameras[i].minZ = this.minZ;
  20816. this._rigCameras[i].maxZ = this.maxZ;
  20817. this._rigCameras[i].fov = this.fov;
  20818. }
  20819. // only update viewport when ANAGLYPH
  20820. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20821. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20822. }
  20823. };
  20824. Camera.prototype._setupInputs = function () {
  20825. };
  20826. Camera.prototype.serialize = function () {
  20827. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20828. // Type
  20829. serializationObject.type = this.getClassName();
  20830. // Parent
  20831. if (this.parent) {
  20832. serializationObject.parentId = this.parent.id;
  20833. }
  20834. if (this.inputs) {
  20835. this.inputs.serialize(serializationObject);
  20836. }
  20837. // Animations
  20838. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20839. serializationObject.ranges = this.serializeAnimationRanges();
  20840. return serializationObject;
  20841. };
  20842. Camera.prototype.clone = function (name) {
  20843. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20844. };
  20845. Camera.prototype.getDirection = function (localAxis) {
  20846. var result = BABYLON.Vector3.Zero();
  20847. this.getDirectionToRef(localAxis, result);
  20848. return result;
  20849. };
  20850. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20851. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20852. };
  20853. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20854. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20855. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20856. switch (type) {
  20857. case "ArcRotateCamera":
  20858. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20859. case "DeviceOrientationCamera":
  20860. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20861. case "FollowCamera":
  20862. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20863. case "ArcFollowCamera":
  20864. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20865. case "GamepadCamera":
  20866. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20867. case "TouchCamera":
  20868. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20869. case "VirtualJoysticksCamera":
  20870. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20871. case "WebVRFreeCamera":
  20872. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20873. case "WebVRGamepadCamera":
  20874. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20875. case "VRDeviceOrientationFreeCamera":
  20876. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20877. case "VRDeviceOrientationGamepadCamera":
  20878. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20879. case "AnaglyphArcRotateCamera":
  20880. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20881. case "AnaglyphFreeCamera":
  20882. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20883. case "AnaglyphGamepadCamera":
  20884. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20885. case "AnaglyphUniversalCamera":
  20886. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20887. case "StereoscopicArcRotateCamera":
  20888. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20889. case "StereoscopicFreeCamera":
  20890. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20891. case "StereoscopicGamepadCamera":
  20892. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20893. case "StereoscopicUniversalCamera":
  20894. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20895. case "FreeCamera":// Forcing Universal here
  20896. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20897. default:// Universal Camera is the default value
  20898. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20899. }
  20900. };
  20901. Camera.prototype.computeWorldMatrix = function () {
  20902. return this.getWorldMatrix();
  20903. };
  20904. Camera.Parse = function (parsedCamera, scene) {
  20905. var type = parsedCamera.type;
  20906. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20907. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20908. // Parent
  20909. if (parsedCamera.parentId) {
  20910. camera._waitingParentId = parsedCamera.parentId;
  20911. }
  20912. //If camera has an input manager, let it parse inputs settings
  20913. if (camera.inputs) {
  20914. camera.inputs.parse(parsedCamera);
  20915. camera._setupInputs();
  20916. }
  20917. if (camera.setPosition) {
  20918. camera.position.copyFromFloats(0, 0, 0);
  20919. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20920. }
  20921. // Target
  20922. if (parsedCamera.target) {
  20923. if (camera.setTarget) {
  20924. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20925. }
  20926. }
  20927. // Apply 3d rig, when found
  20928. if (parsedCamera.cameraRigMode) {
  20929. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20930. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20931. }
  20932. // Animations
  20933. if (parsedCamera.animations) {
  20934. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20935. var parsedAnimation = parsedCamera.animations[animationIndex];
  20936. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20937. }
  20938. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20939. }
  20940. if (parsedCamera.autoAnimate) {
  20941. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20942. }
  20943. return camera;
  20944. };
  20945. // Statics
  20946. Camera._PERSPECTIVE_CAMERA = 0;
  20947. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20948. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20949. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20950. Camera._RIG_MODE_NONE = 0;
  20951. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20952. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20953. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20954. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20955. Camera._RIG_MODE_VR = 20;
  20956. Camera._RIG_MODE_WEBVR = 21;
  20957. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20958. Camera.UseAlternateWebVRRendering = false;
  20959. __decorate([
  20960. BABYLON.serializeAsVector3()
  20961. ], Camera.prototype, "position", void 0);
  20962. __decorate([
  20963. BABYLON.serializeAsVector3()
  20964. ], Camera.prototype, "upVector", void 0);
  20965. __decorate([
  20966. BABYLON.serialize()
  20967. ], Camera.prototype, "orthoLeft", void 0);
  20968. __decorate([
  20969. BABYLON.serialize()
  20970. ], Camera.prototype, "orthoRight", void 0);
  20971. __decorate([
  20972. BABYLON.serialize()
  20973. ], Camera.prototype, "orthoBottom", void 0);
  20974. __decorate([
  20975. BABYLON.serialize()
  20976. ], Camera.prototype, "orthoTop", void 0);
  20977. __decorate([
  20978. BABYLON.serialize()
  20979. ], Camera.prototype, "fov", void 0);
  20980. __decorate([
  20981. BABYLON.serialize()
  20982. ], Camera.prototype, "minZ", void 0);
  20983. __decorate([
  20984. BABYLON.serialize()
  20985. ], Camera.prototype, "maxZ", void 0);
  20986. __decorate([
  20987. BABYLON.serialize()
  20988. ], Camera.prototype, "inertia", void 0);
  20989. __decorate([
  20990. BABYLON.serialize()
  20991. ], Camera.prototype, "mode", void 0);
  20992. __decorate([
  20993. BABYLON.serialize()
  20994. ], Camera.prototype, "layerMask", void 0);
  20995. __decorate([
  20996. BABYLON.serialize()
  20997. ], Camera.prototype, "fovMode", void 0);
  20998. __decorate([
  20999. BABYLON.serialize()
  21000. ], Camera.prototype, "cameraRigMode", void 0);
  21001. __decorate([
  21002. BABYLON.serialize()
  21003. ], Camera.prototype, "interaxialDistance", void 0);
  21004. __decorate([
  21005. BABYLON.serialize()
  21006. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  21007. return Camera;
  21008. }(BABYLON.Node));
  21009. BABYLON.Camera = Camera;
  21010. })(BABYLON || (BABYLON = {}));
  21011. //# sourceMappingURL=babylon.camera.js.map
  21012. "use strict";
  21013. var BABYLON;
  21014. (function (BABYLON) {
  21015. var RenderingManager = /** @class */ (function () {
  21016. function RenderingManager(scene) {
  21017. this._renderingGroups = new Array();
  21018. this._autoClearDepthStencil = {};
  21019. this._customOpaqueSortCompareFn = {};
  21020. this._customAlphaTestSortCompareFn = {};
  21021. this._customTransparentSortCompareFn = {};
  21022. this._renderinGroupInfo = null;
  21023. this._scene = scene;
  21024. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  21025. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  21026. }
  21027. }
  21028. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  21029. if (depth === void 0) { depth = true; }
  21030. if (stencil === void 0) { stencil = true; }
  21031. if (this._depthStencilBufferAlreadyCleaned) {
  21032. return;
  21033. }
  21034. this._scene.getEngine().clear(null, false, depth, stencil);
  21035. this._depthStencilBufferAlreadyCleaned = true;
  21036. };
  21037. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  21038. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  21039. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  21040. var info = null;
  21041. if (observable) {
  21042. if (!this._renderinGroupInfo) {
  21043. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  21044. }
  21045. info = this._renderinGroupInfo;
  21046. info.scene = this._scene;
  21047. info.camera = this._scene.activeCamera;
  21048. }
  21049. // Dispatch sprites
  21050. if (renderSprites) {
  21051. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  21052. var manager = this._scene.spriteManagers[index];
  21053. this.dispatchSprites(manager);
  21054. }
  21055. }
  21056. // Render
  21057. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21058. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  21059. var renderingGroup = this._renderingGroups[index];
  21060. if (!renderingGroup && !observable)
  21061. continue;
  21062. var renderingGroupMask = 0;
  21063. // Fire PRECLEAR stage
  21064. if (observable && info) {
  21065. renderingGroupMask = Math.pow(2, index);
  21066. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  21067. info.renderingGroupId = index;
  21068. observable.notifyObservers(info, renderingGroupMask);
  21069. }
  21070. // Clear depth/stencil if needed
  21071. if (RenderingManager.AUTOCLEAR) {
  21072. var autoClear = this._autoClearDepthStencil[index];
  21073. if (autoClear && autoClear.autoClear) {
  21074. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  21075. }
  21076. }
  21077. if (observable && info) {
  21078. // Fire PREOPAQUE stage
  21079. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  21080. observable.notifyObservers(info, renderingGroupMask);
  21081. // Fire PRETRANSPARENT stage
  21082. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  21083. observable.notifyObservers(info, renderingGroupMask);
  21084. }
  21085. if (renderingGroup)
  21086. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  21087. // Fire POSTTRANSPARENT stage
  21088. if (observable && info) {
  21089. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  21090. observable.notifyObservers(info, renderingGroupMask);
  21091. }
  21092. }
  21093. };
  21094. RenderingManager.prototype.reset = function () {
  21095. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21096. var renderingGroup = this._renderingGroups[index];
  21097. if (renderingGroup) {
  21098. renderingGroup.prepare();
  21099. }
  21100. }
  21101. };
  21102. RenderingManager.prototype.dispose = function () {
  21103. this.freeRenderingGroups();
  21104. this._renderingGroups.length = 0;
  21105. };
  21106. /**
  21107. * Clear the info related to rendering groups preventing retention points during dispose.
  21108. */
  21109. RenderingManager.prototype.freeRenderingGroups = function () {
  21110. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21111. var renderingGroup = this._renderingGroups[index];
  21112. if (renderingGroup) {
  21113. renderingGroup.dispose();
  21114. }
  21115. }
  21116. };
  21117. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21118. if (this._renderingGroups[renderingGroupId] === undefined) {
  21119. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21120. }
  21121. };
  21122. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21123. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21124. this._prepareRenderingGroup(renderingGroupId);
  21125. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21126. };
  21127. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21128. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21129. this._prepareRenderingGroup(renderingGroupId);
  21130. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21131. };
  21132. /**
  21133. * @param subMesh The submesh to dispatch
  21134. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21135. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21136. */
  21137. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21138. if (mesh === undefined) {
  21139. mesh = subMesh.getMesh();
  21140. }
  21141. var renderingGroupId = mesh.renderingGroupId || 0;
  21142. this._prepareRenderingGroup(renderingGroupId);
  21143. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21144. };
  21145. /**
  21146. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21147. * This allowed control for front to back rendering or reversly depending of the special needs.
  21148. *
  21149. * @param renderingGroupId The rendering group id corresponding to its index
  21150. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21151. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21152. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21153. */
  21154. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21155. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21156. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21157. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21158. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21159. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21160. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21161. if (this._renderingGroups[renderingGroupId]) {
  21162. var group = this._renderingGroups[renderingGroupId];
  21163. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21164. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21165. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21166. }
  21167. };
  21168. /**
  21169. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21170. *
  21171. * @param renderingGroupId The rendering group id corresponding to its index
  21172. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21173. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21174. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21175. */
  21176. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21177. if (depth === void 0) { depth = true; }
  21178. if (stencil === void 0) { stencil = true; }
  21179. this._autoClearDepthStencil[renderingGroupId] = {
  21180. autoClear: autoClearDepthStencil,
  21181. depth: depth,
  21182. stencil: stencil
  21183. };
  21184. };
  21185. /**
  21186. * The max id used for rendering groups (not included)
  21187. */
  21188. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21189. /**
  21190. * The min id used for rendering groups (included)
  21191. */
  21192. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21193. /**
  21194. * Used to globally prevent autoclearing scenes.
  21195. */
  21196. RenderingManager.AUTOCLEAR = true;
  21197. return RenderingManager;
  21198. }());
  21199. BABYLON.RenderingManager = RenderingManager;
  21200. })(BABYLON || (BABYLON = {}));
  21201. //# sourceMappingURL=babylon.renderingManager.js.map
  21202. "use strict";
  21203. var BABYLON;
  21204. (function (BABYLON) {
  21205. var RenderingGroup = /** @class */ (function () {
  21206. /**
  21207. * Creates a new rendering group.
  21208. * @param index The rendering group index
  21209. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21210. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21211. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21212. */
  21213. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21214. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21215. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21216. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21217. this.index = index;
  21218. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21219. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21220. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21221. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21222. this._particleSystems = new BABYLON.SmartArray(256);
  21223. this._spriteManagers = new BABYLON.SmartArray(256);
  21224. this._edgesRenderers = new BABYLON.SmartArray(16);
  21225. this._scene = scene;
  21226. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21227. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21228. this.transparentSortCompareFn = transparentSortCompareFn;
  21229. }
  21230. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21231. /**
  21232. * Set the opaque sort comparison function.
  21233. * If null the sub meshes will be render in the order they were created
  21234. */
  21235. set: function (value) {
  21236. this._opaqueSortCompareFn = value;
  21237. if (value) {
  21238. this._renderOpaque = this.renderOpaqueSorted;
  21239. }
  21240. else {
  21241. this._renderOpaque = RenderingGroup.renderUnsorted;
  21242. }
  21243. },
  21244. enumerable: true,
  21245. configurable: true
  21246. });
  21247. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21248. /**
  21249. * Set the alpha test sort comparison function.
  21250. * If null the sub meshes will be render in the order they were created
  21251. */
  21252. set: function (value) {
  21253. this._alphaTestSortCompareFn = value;
  21254. if (value) {
  21255. this._renderAlphaTest = this.renderAlphaTestSorted;
  21256. }
  21257. else {
  21258. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21259. }
  21260. },
  21261. enumerable: true,
  21262. configurable: true
  21263. });
  21264. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21265. /**
  21266. * Set the transparent sort comparison function.
  21267. * If null the sub meshes will be render in the order they were created
  21268. */
  21269. set: function (value) {
  21270. if (value) {
  21271. this._transparentSortCompareFn = value;
  21272. }
  21273. else {
  21274. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21275. }
  21276. this._renderTransparent = this.renderTransparentSorted;
  21277. },
  21278. enumerable: true,
  21279. configurable: true
  21280. });
  21281. /**
  21282. * Render all the sub meshes contained in the group.
  21283. * @param customRenderFunction Used to override the default render behaviour of the group.
  21284. * @returns true if rendered some submeshes.
  21285. */
  21286. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21287. if (customRenderFunction) {
  21288. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21289. return;
  21290. }
  21291. var engine = this._scene.getEngine();
  21292. // Depth only
  21293. if (this._depthOnlySubMeshes.length !== 0) {
  21294. engine.setColorWrite(false);
  21295. this._renderAlphaTest(this._depthOnlySubMeshes);
  21296. engine.setColorWrite(true);
  21297. }
  21298. // Opaque
  21299. if (this._opaqueSubMeshes.length !== 0) {
  21300. this._renderOpaque(this._opaqueSubMeshes);
  21301. }
  21302. // Alpha test
  21303. if (this._alphaTestSubMeshes.length !== 0) {
  21304. this._renderAlphaTest(this._alphaTestSubMeshes);
  21305. }
  21306. var stencilState = engine.getStencilBuffer();
  21307. engine.setStencilBuffer(false);
  21308. // Sprites
  21309. if (renderSprites) {
  21310. this._renderSprites();
  21311. }
  21312. // Particles
  21313. if (renderParticles) {
  21314. this._renderParticles(activeMeshes);
  21315. }
  21316. if (this.onBeforeTransparentRendering) {
  21317. this.onBeforeTransparentRendering();
  21318. }
  21319. // Transparent
  21320. if (this._transparentSubMeshes.length !== 0) {
  21321. this._renderTransparent(this._transparentSubMeshes);
  21322. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21323. }
  21324. // Set back stencil to false in case it changes before the edge renderer.
  21325. engine.setStencilBuffer(false);
  21326. // Edges
  21327. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21328. this._edgesRenderers.data[edgesRendererIndex].render();
  21329. }
  21330. // Restore Stencil state.
  21331. engine.setStencilBuffer(stencilState);
  21332. };
  21333. /**
  21334. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21335. * @param subMeshes The submeshes to render
  21336. */
  21337. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21338. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21339. };
  21340. /**
  21341. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21342. * @param subMeshes The submeshes to render
  21343. */
  21344. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21345. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21346. };
  21347. /**
  21348. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21349. * @param subMeshes The submeshes to render
  21350. */
  21351. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21352. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21353. };
  21354. /**
  21355. * Renders the submeshes in a specified order.
  21356. * @param subMeshes The submeshes to sort before render
  21357. * @param sortCompareFn The comparison function use to sort
  21358. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21359. * @param transparent Specifies to activate blending if true
  21360. */
  21361. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21362. var subIndex = 0;
  21363. var subMesh;
  21364. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21365. for (; subIndex < subMeshes.length; subIndex++) {
  21366. subMesh = subMeshes.data[subIndex];
  21367. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21368. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21369. }
  21370. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21371. if (sortCompareFn) {
  21372. sortedArray.sort(sortCompareFn);
  21373. }
  21374. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21375. subMesh = sortedArray[subIndex];
  21376. if (transparent) {
  21377. var material = subMesh.getMaterial();
  21378. if (material && material.needDepthPrePass) {
  21379. var engine = material.getScene().getEngine();
  21380. engine.setColorWrite(false);
  21381. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21382. subMesh.render(false);
  21383. engine.setColorWrite(true);
  21384. }
  21385. }
  21386. subMesh.render(transparent);
  21387. }
  21388. };
  21389. /**
  21390. * Renders the submeshes in the order they were dispatched (no sort applied).
  21391. * @param subMeshes The submeshes to render
  21392. */
  21393. RenderingGroup.renderUnsorted = function (subMeshes) {
  21394. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21395. var submesh = subMeshes.data[subIndex];
  21396. submesh.render(false);
  21397. }
  21398. };
  21399. /**
  21400. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21401. * are rendered back to front if in the same alpha index.
  21402. *
  21403. * @param a The first submesh
  21404. * @param b The second submesh
  21405. * @returns The result of the comparison
  21406. */
  21407. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21408. // Alpha index first
  21409. if (a._alphaIndex > b._alphaIndex) {
  21410. return 1;
  21411. }
  21412. if (a._alphaIndex < b._alphaIndex) {
  21413. return -1;
  21414. }
  21415. // Then distance to camera
  21416. return RenderingGroup.backToFrontSortCompare(a, b);
  21417. };
  21418. /**
  21419. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21420. * are rendered back to front.
  21421. *
  21422. * @param a The first submesh
  21423. * @param b The second submesh
  21424. * @returns The result of the comparison
  21425. */
  21426. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21427. // Then distance to camera
  21428. if (a._distanceToCamera < b._distanceToCamera) {
  21429. return 1;
  21430. }
  21431. if (a._distanceToCamera > b._distanceToCamera) {
  21432. return -1;
  21433. }
  21434. return 0;
  21435. };
  21436. /**
  21437. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21438. * are rendered front to back (prevent overdraw).
  21439. *
  21440. * @param a The first submesh
  21441. * @param b The second submesh
  21442. * @returns The result of the comparison
  21443. */
  21444. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21445. // Then distance to camera
  21446. if (a._distanceToCamera < b._distanceToCamera) {
  21447. return -1;
  21448. }
  21449. if (a._distanceToCamera > b._distanceToCamera) {
  21450. return 1;
  21451. }
  21452. return 0;
  21453. };
  21454. /**
  21455. * Resets the different lists of submeshes to prepare a new frame.
  21456. */
  21457. RenderingGroup.prototype.prepare = function () {
  21458. this._opaqueSubMeshes.reset();
  21459. this._transparentSubMeshes.reset();
  21460. this._alphaTestSubMeshes.reset();
  21461. this._depthOnlySubMeshes.reset();
  21462. this._particleSystems.reset();
  21463. this._spriteManagers.reset();
  21464. this._edgesRenderers.reset();
  21465. };
  21466. RenderingGroup.prototype.dispose = function () {
  21467. this._opaqueSubMeshes.dispose();
  21468. this._transparentSubMeshes.dispose();
  21469. this._alphaTestSubMeshes.dispose();
  21470. this._depthOnlySubMeshes.dispose();
  21471. this._particleSystems.dispose();
  21472. this._spriteManagers.dispose();
  21473. this._edgesRenderers.dispose();
  21474. };
  21475. /**
  21476. * Inserts the submesh in its correct queue depending on its material.
  21477. * @param subMesh The submesh to dispatch
  21478. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21479. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21480. */
  21481. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21482. // Get mesh and materials if not provided
  21483. if (mesh === undefined) {
  21484. mesh = subMesh.getMesh();
  21485. }
  21486. if (material === undefined) {
  21487. material = subMesh.getMaterial();
  21488. }
  21489. if (material === null || material === undefined) {
  21490. return;
  21491. }
  21492. if (material.needAlphaBlendingForMesh(mesh)) {
  21493. this._transparentSubMeshes.push(subMesh);
  21494. }
  21495. else if (material.needAlphaTesting()) {
  21496. if (material.needDepthPrePass) {
  21497. this._depthOnlySubMeshes.push(subMesh);
  21498. }
  21499. this._alphaTestSubMeshes.push(subMesh);
  21500. }
  21501. else {
  21502. if (material.needDepthPrePass) {
  21503. this._depthOnlySubMeshes.push(subMesh);
  21504. }
  21505. this._opaqueSubMeshes.push(subMesh); // Opaque
  21506. }
  21507. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21508. this._edgesRenderers.push(mesh._edgesRenderer);
  21509. }
  21510. };
  21511. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21512. this._spriteManagers.push(spriteManager);
  21513. };
  21514. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21515. this._particleSystems.push(particleSystem);
  21516. };
  21517. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21518. if (this._particleSystems.length === 0) {
  21519. return;
  21520. }
  21521. // Particles
  21522. var activeCamera = this._scene.activeCamera;
  21523. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21524. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21525. var particleSystem = this._particleSystems.data[particleIndex];
  21526. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21527. continue;
  21528. }
  21529. var emitter = particleSystem.emitter;
  21530. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21531. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21532. }
  21533. }
  21534. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21535. };
  21536. RenderingGroup.prototype._renderSprites = function () {
  21537. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21538. return;
  21539. }
  21540. // Sprites
  21541. var activeCamera = this._scene.activeCamera;
  21542. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21543. for (var id = 0; id < this._spriteManagers.length; id++) {
  21544. var spriteManager = this._spriteManagers.data[id];
  21545. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21546. spriteManager.render();
  21547. }
  21548. }
  21549. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21550. };
  21551. return RenderingGroup;
  21552. }());
  21553. BABYLON.RenderingGroup = RenderingGroup;
  21554. })(BABYLON || (BABYLON = {}));
  21555. //# sourceMappingURL=babylon.renderingGroup.js.map
  21556. "use strict";
  21557. var BABYLON;
  21558. (function (BABYLON) {
  21559. var ClickInfo = /** @class */ (function () {
  21560. function ClickInfo() {
  21561. this._singleClick = false;
  21562. this._doubleClick = false;
  21563. this._hasSwiped = false;
  21564. this._ignore = false;
  21565. }
  21566. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21567. get: function () {
  21568. return this._singleClick;
  21569. },
  21570. set: function (b) {
  21571. this._singleClick = b;
  21572. },
  21573. enumerable: true,
  21574. configurable: true
  21575. });
  21576. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21577. get: function () {
  21578. return this._doubleClick;
  21579. },
  21580. set: function (b) {
  21581. this._doubleClick = b;
  21582. },
  21583. enumerable: true,
  21584. configurable: true
  21585. });
  21586. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21587. get: function () {
  21588. return this._hasSwiped;
  21589. },
  21590. set: function (b) {
  21591. this._hasSwiped = b;
  21592. },
  21593. enumerable: true,
  21594. configurable: true
  21595. });
  21596. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21597. get: function () {
  21598. return this._ignore;
  21599. },
  21600. set: function (b) {
  21601. this._ignore = b;
  21602. },
  21603. enumerable: true,
  21604. configurable: true
  21605. });
  21606. return ClickInfo;
  21607. }());
  21608. /**
  21609. * This class is used by the onRenderingGroupObservable
  21610. */
  21611. var RenderingGroupInfo = /** @class */ (function () {
  21612. function RenderingGroupInfo() {
  21613. }
  21614. /**
  21615. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21616. * This stage will be fired no matter what
  21617. */
  21618. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21619. /**
  21620. * Called before opaque object are rendered.
  21621. * This stage will be fired only if there's 3D Opaque content to render
  21622. */
  21623. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21624. /**
  21625. * Called after the opaque objects are rendered and before the transparent ones
  21626. * This stage will be fired only if there's 3D transparent content to render
  21627. */
  21628. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21629. /**
  21630. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21631. * This stage will be fired no matter what
  21632. */
  21633. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21634. return RenderingGroupInfo;
  21635. }());
  21636. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21637. /**
  21638. * Represents a scene to be rendered by the engine.
  21639. * @see http://doc.babylonjs.com/page.php?p=21911
  21640. */
  21641. var Scene = /** @class */ (function () {
  21642. /**
  21643. * @constructor
  21644. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21645. */
  21646. function Scene(engine) {
  21647. // Members
  21648. this.autoClear = true;
  21649. this.autoClearDepthAndStencil = true;
  21650. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21651. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21652. this._forceWireframe = false;
  21653. this._forcePointsCloud = false;
  21654. this.forceShowBoundingBoxes = false;
  21655. this.animationsEnabled = true;
  21656. this.useConstantAnimationDeltaTime = false;
  21657. this.constantlyUpdateMeshUnderPointer = false;
  21658. this.hoverCursor = "pointer";
  21659. this.defaultCursor = "";
  21660. /**
  21661. * This is used to call preventDefault() on pointer down
  21662. * in order to block unwanted artifacts like system double clicks
  21663. */
  21664. this.preventDefaultOnPointerDown = true;
  21665. // Metadata
  21666. this.metadata = null;
  21667. /**
  21668. * An event triggered when the scene is disposed.
  21669. * @type {BABYLON.Observable}
  21670. */
  21671. this.onDisposeObservable = new BABYLON.Observable();
  21672. /**
  21673. * An event triggered before rendering the scene (right after animations and physics)
  21674. * @type {BABYLON.Observable}
  21675. */
  21676. this.onBeforeRenderObservable = new BABYLON.Observable();
  21677. /**
  21678. * An event triggered after rendering the scene
  21679. * @type {BABYLON.Observable}
  21680. */
  21681. this.onAfterRenderObservable = new BABYLON.Observable();
  21682. /**
  21683. * An event triggered before animating the scene
  21684. * @type {BABYLON.Observable}
  21685. */
  21686. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21687. /**
  21688. * An event triggered after animations processing
  21689. * @type {BABYLON.Observable}
  21690. */
  21691. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21692. /**
  21693. * An event triggered before draw calls are ready to be sent
  21694. * @type {BABYLON.Observable}
  21695. */
  21696. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21697. /**
  21698. * An event triggered after draw calls have been sent
  21699. * @type {BABYLON.Observable}
  21700. */
  21701. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21702. /**
  21703. * An event triggered when physic simulation is about to be run
  21704. * @type {BABYLON.Observable}
  21705. */
  21706. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21707. /**
  21708. * An event triggered when physic simulation has been done
  21709. * @type {BABYLON.Observable}
  21710. */
  21711. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21712. /**
  21713. * An event triggered when the scene is ready
  21714. * @type {BABYLON.Observable}
  21715. */
  21716. this.onReadyObservable = new BABYLON.Observable();
  21717. /**
  21718. * An event triggered before rendering a camera
  21719. * @type {BABYLON.Observable}
  21720. */
  21721. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21722. /**
  21723. * An event triggered after rendering a camera
  21724. * @type {BABYLON.Observable}
  21725. */
  21726. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21727. /**
  21728. * An event triggered when active meshes evaluation is about to start
  21729. * @type {BABYLON.Observable}
  21730. */
  21731. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21732. /**
  21733. * An event triggered when active meshes evaluation is done
  21734. * @type {BABYLON.Observable}
  21735. */
  21736. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21737. /**
  21738. * An event triggered when particles rendering is about to start
  21739. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21740. * @type {BABYLON.Observable}
  21741. */
  21742. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21743. /**
  21744. * An event triggered when particles rendering is done
  21745. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21746. * @type {BABYLON.Observable}
  21747. */
  21748. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21749. /**
  21750. * An event triggered when sprites rendering is about to start
  21751. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21752. * @type {BABYLON.Observable}
  21753. */
  21754. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21755. /**
  21756. * An event triggered when sprites rendering is done
  21757. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21758. * @type {BABYLON.Observable}
  21759. */
  21760. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21761. /**
  21762. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21763. * @type {BABYLON.Observable}
  21764. */
  21765. this.onDataLoadedObservable = new BABYLON.Observable();
  21766. /**
  21767. * An event triggered when a camera is created
  21768. * @type {BABYLON.Observable}
  21769. */
  21770. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21771. /**
  21772. * An event triggered when a camera is removed
  21773. * @type {BABYLON.Observable}
  21774. */
  21775. this.onCameraRemovedObservable = new BABYLON.Observable();
  21776. /**
  21777. * An event triggered when a light is created
  21778. * @type {BABYLON.Observable}
  21779. */
  21780. this.onNewLightAddedObservable = new BABYLON.Observable();
  21781. /**
  21782. * An event triggered when a light is removed
  21783. * @type {BABYLON.Observable}
  21784. */
  21785. this.onLightRemovedObservable = new BABYLON.Observable();
  21786. /**
  21787. * An event triggered when a geometry is created
  21788. * @type {BABYLON.Observable}
  21789. */
  21790. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21791. /**
  21792. * An event triggered when a geometry is removed
  21793. * @type {BABYLON.Observable}
  21794. */
  21795. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21796. /**
  21797. * An event triggered when a transform node is created
  21798. * @type {BABYLON.Observable}
  21799. */
  21800. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21801. /**
  21802. * An event triggered when a transform node is removed
  21803. * @type {BABYLON.Observable}
  21804. */
  21805. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21806. /**
  21807. * An event triggered when a mesh is created
  21808. * @type {BABYLON.Observable}
  21809. */
  21810. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21811. /**
  21812. * An event triggered when a mesh is removed
  21813. * @type {BABYLON.Observable}
  21814. */
  21815. this.onMeshRemovedObservable = new BABYLON.Observable();
  21816. /**
  21817. * An event triggered when render targets are about to be rendered
  21818. * Can happen multiple times per frame.
  21819. * @type {BABYLON.Observable}
  21820. */
  21821. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21822. /**
  21823. * An event triggered when render targets were rendered.
  21824. * Can happen multiple times per frame.
  21825. * @type {BABYLON.Observable}
  21826. */
  21827. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21828. /**
  21829. * An event triggered before calculating deterministic simulation step
  21830. * @type {BABYLON.Observable}
  21831. */
  21832. this.onBeforeStepObservable = new BABYLON.Observable();
  21833. /**
  21834. * An event triggered after calculating deterministic simulation step
  21835. * @type {BABYLON.Observable}
  21836. */
  21837. this.onAfterStepObservable = new BABYLON.Observable();
  21838. /**
  21839. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21840. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21841. * 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)
  21842. */
  21843. this.onRenderingGroupObservable = new BABYLON.Observable();
  21844. // Animations
  21845. this.animations = [];
  21846. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21847. /**
  21848. * 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).
  21849. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21850. */
  21851. this.onPrePointerObservable = new BABYLON.Observable();
  21852. /**
  21853. * Observable event triggered each time an input event is received from the rendering canvas
  21854. */
  21855. this.onPointerObservable = new BABYLON.Observable();
  21856. this._meshPickProceed = false;
  21857. this._currentPickResult = null;
  21858. this._previousPickResult = null;
  21859. this._totalPointersPressed = 0;
  21860. this._doubleClickOccured = false;
  21861. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21862. this.cameraToUseForPointers = null;
  21863. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21864. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21865. this._startingPointerTime = 0;
  21866. this._previousStartingPointerTime = 0;
  21867. // Deterministic lockstep
  21868. this._timeAccumulator = 0;
  21869. this._currentStepId = 0;
  21870. this._currentInternalStep = 0;
  21871. // Keyboard
  21872. /**
  21873. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21874. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21875. */
  21876. this.onPreKeyboardObservable = new BABYLON.Observable();
  21877. /**
  21878. * Observable event triggered each time an keyboard event is received from the hosting window
  21879. */
  21880. this.onKeyboardObservable = new BABYLON.Observable();
  21881. // Coordinate system
  21882. /**
  21883. * use right-handed coordinate system on this scene.
  21884. * @type {boolean}
  21885. */
  21886. this._useRightHandedSystem = false;
  21887. // Fog
  21888. this._fogEnabled = true;
  21889. this._fogMode = Scene.FOGMODE_NONE;
  21890. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21891. this.fogDensity = 0.1;
  21892. this.fogStart = 0;
  21893. this.fogEnd = 1000.0;
  21894. // Lights
  21895. /**
  21896. * is shadow enabled on this scene.
  21897. * @type {boolean}
  21898. */
  21899. this._shadowsEnabled = true;
  21900. /**
  21901. * is light enabled on this scene.
  21902. * @type {boolean}
  21903. */
  21904. this._lightsEnabled = true;
  21905. /**
  21906. * All of the lights added to this scene.
  21907. * @see BABYLON.Light
  21908. * @type {BABYLON.Light[]}
  21909. */
  21910. this.lights = new Array();
  21911. // Cameras
  21912. /** All of the cameras added to this scene. */
  21913. this.cameras = new Array();
  21914. /** All of the active cameras added to this scene. */
  21915. this.activeCameras = new Array();
  21916. // Meshes
  21917. /**
  21918. * All of the tranform nodes added to this scene.
  21919. * @see BABYLON.TransformNode
  21920. * @type {BABYLON.TransformNode[]}
  21921. */
  21922. this.transformNodes = new Array();
  21923. /**
  21924. * All of the (abstract) meshes added to this scene.
  21925. * @see BABYLON.AbstractMesh
  21926. * @type {BABYLON.AbstractMesh[]}
  21927. */
  21928. this.meshes = new Array();
  21929. /**
  21930. * All of the animation groups added to this scene.
  21931. * @see BABYLON.AnimationGroup
  21932. * @type {BABYLON.AnimationGroup[]}
  21933. */
  21934. this.animationGroups = new Array();
  21935. // Geometries
  21936. this._geometries = new Array();
  21937. this.materials = new Array();
  21938. this.multiMaterials = new Array();
  21939. // Textures
  21940. this._texturesEnabled = true;
  21941. this.textures = new Array();
  21942. // Particles
  21943. this.particlesEnabled = true;
  21944. this.particleSystems = new Array();
  21945. // Sprites
  21946. this.spritesEnabled = true;
  21947. this.spriteManagers = new Array();
  21948. /**
  21949. * The list of layers (background and foreground) of the scene.
  21950. */
  21951. this.layers = new Array();
  21952. /**
  21953. * The list of effect layers (highlights/glow) contained in the scene.
  21954. */
  21955. this.effectLayers = new Array();
  21956. // Skeletons
  21957. this._skeletonsEnabled = true;
  21958. this.skeletons = new Array();
  21959. // Morph targets
  21960. this.morphTargetManagers = new Array();
  21961. // Lens flares
  21962. this.lensFlaresEnabled = true;
  21963. this.lensFlareSystems = new Array();
  21964. // Collisions
  21965. this.collisionsEnabled = true;
  21966. /** Defines the gravity applied to this scene */
  21967. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21968. // Postprocesses
  21969. this.postProcesses = new Array();
  21970. this.postProcessesEnabled = true;
  21971. // Customs render targets
  21972. this.renderTargetsEnabled = true;
  21973. this.dumpNextRenderTargets = false;
  21974. this.customRenderTargets = new Array();
  21975. // Imported meshes
  21976. this.importedMeshesFiles = new Array();
  21977. // Probes
  21978. this.probesEnabled = true;
  21979. this.reflectionProbes = new Array();
  21980. this._actionManagers = new Array();
  21981. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21982. // Procedural textures
  21983. this.proceduralTexturesEnabled = true;
  21984. this._proceduralTextures = new Array();
  21985. this.soundTracks = new Array();
  21986. this._audioEnabled = true;
  21987. this._headphone = false;
  21988. // Performance counters
  21989. this._totalVertices = new BABYLON.PerfCounter();
  21990. this._activeIndices = new BABYLON.PerfCounter();
  21991. this._activeParticles = new BABYLON.PerfCounter();
  21992. this._activeBones = new BABYLON.PerfCounter();
  21993. this._animationTime = 0;
  21994. this.animationTimeScale = 1;
  21995. this._renderId = 0;
  21996. this._executeWhenReadyTimeoutId = -1;
  21997. this._intermediateRendering = false;
  21998. this._viewUpdateFlag = -1;
  21999. this._projectionUpdateFlag = -1;
  22000. this._alternateViewUpdateFlag = -1;
  22001. this._alternateProjectionUpdateFlag = -1;
  22002. this._toBeDisposed = new BABYLON.SmartArray(256);
  22003. this._activeRequests = new Array();
  22004. this._pendingData = new Array();
  22005. this._isDisposed = false;
  22006. this.dispatchAllSubMeshesOfActiveMeshes = false;
  22007. this._activeMeshes = new BABYLON.SmartArray(256);
  22008. this._processedMaterials = new BABYLON.SmartArray(256);
  22009. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  22010. this._activeParticleSystems = new BABYLON.SmartArray(256);
  22011. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  22012. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  22013. this._activeAnimatables = new Array();
  22014. this._transformMatrix = BABYLON.Matrix.Zero();
  22015. this._useAlternateCameraConfiguration = false;
  22016. this._alternateRendering = false;
  22017. this.requireLightSorting = false;
  22018. this._depthRenderer = {};
  22019. this._activeMeshesFrozen = false;
  22020. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  22021. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  22022. this._engine.scenes.push(this);
  22023. this._uid = null;
  22024. this._renderingManager = new BABYLON.RenderingManager(this);
  22025. this.postProcessManager = new BABYLON.PostProcessManager(this);
  22026. if (BABYLON.OutlineRenderer) {
  22027. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  22028. }
  22029. if (BABYLON.Tools.IsWindowObjectExist()) {
  22030. this.attachControl();
  22031. }
  22032. //simplification queue
  22033. if (BABYLON.SimplificationQueue) {
  22034. this.simplificationQueue = new BABYLON.SimplificationQueue();
  22035. }
  22036. //collision coordinator initialization. For now legacy per default.
  22037. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  22038. // Uniform Buffer
  22039. this._createUbo();
  22040. // Default Image processing definition.
  22041. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  22042. }
  22043. Object.defineProperty(Scene, "FOGMODE_NONE", {
  22044. /** The fog is deactivated */
  22045. get: function () {
  22046. return Scene._FOGMODE_NONE;
  22047. },
  22048. enumerable: true,
  22049. configurable: true
  22050. });
  22051. Object.defineProperty(Scene, "FOGMODE_EXP", {
  22052. /** The fog density is following an exponential function */
  22053. get: function () {
  22054. return Scene._FOGMODE_EXP;
  22055. },
  22056. enumerable: true,
  22057. configurable: true
  22058. });
  22059. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  22060. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  22061. get: function () {
  22062. return Scene._FOGMODE_EXP2;
  22063. },
  22064. enumerable: true,
  22065. configurable: true
  22066. });
  22067. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  22068. /** The fog density is following a linear function. */
  22069. get: function () {
  22070. return Scene._FOGMODE_LINEAR;
  22071. },
  22072. enumerable: true,
  22073. configurable: true
  22074. });
  22075. Object.defineProperty(Scene.prototype, "environmentTexture", {
  22076. /**
  22077. * Texture used in all pbr material as the reflection texture.
  22078. * As in the majority of the scene they are the same (exception for multi room and so on),
  22079. * this is easier to reference from here than from all the materials.
  22080. */
  22081. get: function () {
  22082. return this._environmentTexture;
  22083. },
  22084. /**
  22085. * Texture used in all pbr material as the reflection texture.
  22086. * As in the majority of the scene they are the same (exception for multi room and so on),
  22087. * this is easier to set here than in all the materials.
  22088. */
  22089. set: function (value) {
  22090. if (this._environmentTexture === value) {
  22091. return;
  22092. }
  22093. this._environmentTexture = value;
  22094. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22095. },
  22096. enumerable: true,
  22097. configurable: true
  22098. });
  22099. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22100. /**
  22101. * Default image processing configuration used either in the rendering
  22102. * Forward main pass or through the imageProcessingPostProcess if present.
  22103. * As in the majority of the scene they are the same (exception for multi camera),
  22104. * this is easier to reference from here than from all the materials and post process.
  22105. *
  22106. * No setter as we it is a shared configuration, you can set the values instead.
  22107. */
  22108. get: function () {
  22109. return this._imageProcessingConfiguration;
  22110. },
  22111. enumerable: true,
  22112. configurable: true
  22113. });
  22114. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22115. get: function () {
  22116. return this._forceWireframe;
  22117. },
  22118. set: function (value) {
  22119. if (this._forceWireframe === value) {
  22120. return;
  22121. }
  22122. this._forceWireframe = value;
  22123. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22124. },
  22125. enumerable: true,
  22126. configurable: true
  22127. });
  22128. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22129. get: function () {
  22130. return this._forcePointsCloud;
  22131. },
  22132. set: function (value) {
  22133. if (this._forcePointsCloud === value) {
  22134. return;
  22135. }
  22136. this._forcePointsCloud = value;
  22137. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22138. },
  22139. enumerable: true,
  22140. configurable: true
  22141. });
  22142. Object.defineProperty(Scene.prototype, "onDispose", {
  22143. /** A function to be executed when this scene is disposed. */
  22144. set: function (callback) {
  22145. if (this._onDisposeObserver) {
  22146. this.onDisposeObservable.remove(this._onDisposeObserver);
  22147. }
  22148. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22149. },
  22150. enumerable: true,
  22151. configurable: true
  22152. });
  22153. Object.defineProperty(Scene.prototype, "beforeRender", {
  22154. /** A function to be executed before rendering this scene */
  22155. set: function (callback) {
  22156. if (this._onBeforeRenderObserver) {
  22157. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22158. }
  22159. if (callback) {
  22160. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22161. }
  22162. },
  22163. enumerable: true,
  22164. configurable: true
  22165. });
  22166. Object.defineProperty(Scene.prototype, "afterRender", {
  22167. /** A function to be executed after rendering this scene */
  22168. set: function (callback) {
  22169. if (this._onAfterRenderObserver) {
  22170. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22171. }
  22172. if (callback) {
  22173. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22174. }
  22175. },
  22176. enumerable: true,
  22177. configurable: true
  22178. });
  22179. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22180. set: function (callback) {
  22181. if (this._onBeforeCameraRenderObserver) {
  22182. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22183. }
  22184. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22185. },
  22186. enumerable: true,
  22187. configurable: true
  22188. });
  22189. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22190. set: function (callback) {
  22191. if (this._onAfterCameraRenderObserver) {
  22192. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22193. }
  22194. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22195. },
  22196. enumerable: true,
  22197. configurable: true
  22198. });
  22199. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22200. get: function () {
  22201. if (!this._gamepadManager) {
  22202. this._gamepadManager = new BABYLON.GamepadManager(this);
  22203. }
  22204. return this._gamepadManager;
  22205. },
  22206. enumerable: true,
  22207. configurable: true
  22208. });
  22209. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22210. get: function () {
  22211. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22212. },
  22213. enumerable: true,
  22214. configurable: true
  22215. });
  22216. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22217. get: function () {
  22218. return this._useRightHandedSystem;
  22219. },
  22220. set: function (value) {
  22221. if (this._useRightHandedSystem === value) {
  22222. return;
  22223. }
  22224. this._useRightHandedSystem = value;
  22225. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22226. },
  22227. enumerable: true,
  22228. configurable: true
  22229. });
  22230. Scene.prototype.setStepId = function (newStepId) {
  22231. this._currentStepId = newStepId;
  22232. };
  22233. ;
  22234. Scene.prototype.getStepId = function () {
  22235. return this._currentStepId;
  22236. };
  22237. ;
  22238. Scene.prototype.getInternalStep = function () {
  22239. return this._currentInternalStep;
  22240. };
  22241. ;
  22242. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22243. get: function () {
  22244. return this._fogEnabled;
  22245. },
  22246. /**
  22247. * is fog enabled on this scene.
  22248. */
  22249. set: function (value) {
  22250. if (this._fogEnabled === value) {
  22251. return;
  22252. }
  22253. this._fogEnabled = value;
  22254. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22255. },
  22256. enumerable: true,
  22257. configurable: true
  22258. });
  22259. Object.defineProperty(Scene.prototype, "fogMode", {
  22260. get: function () {
  22261. return this._fogMode;
  22262. },
  22263. set: function (value) {
  22264. if (this._fogMode === value) {
  22265. return;
  22266. }
  22267. this._fogMode = value;
  22268. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22269. },
  22270. enumerable: true,
  22271. configurable: true
  22272. });
  22273. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22274. get: function () {
  22275. return this._shadowsEnabled;
  22276. },
  22277. set: function (value) {
  22278. if (this._shadowsEnabled === value) {
  22279. return;
  22280. }
  22281. this._shadowsEnabled = value;
  22282. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22283. },
  22284. enumerable: true,
  22285. configurable: true
  22286. });
  22287. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22288. get: function () {
  22289. return this._lightsEnabled;
  22290. },
  22291. set: function (value) {
  22292. if (this._lightsEnabled === value) {
  22293. return;
  22294. }
  22295. this._lightsEnabled = value;
  22296. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22297. },
  22298. enumerable: true,
  22299. configurable: true
  22300. });
  22301. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22302. /** The default material used on meshes when no material is affected */
  22303. get: function () {
  22304. if (!this._defaultMaterial) {
  22305. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22306. }
  22307. return this._defaultMaterial;
  22308. },
  22309. /** The default material used on meshes when no material is affected */
  22310. set: function (value) {
  22311. this._defaultMaterial = value;
  22312. },
  22313. enumerable: true,
  22314. configurable: true
  22315. });
  22316. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22317. get: function () {
  22318. return this._texturesEnabled;
  22319. },
  22320. set: function (value) {
  22321. if (this._texturesEnabled === value) {
  22322. return;
  22323. }
  22324. this._texturesEnabled = value;
  22325. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22326. },
  22327. enumerable: true,
  22328. configurable: true
  22329. });
  22330. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22331. get: function () {
  22332. return this._skeletonsEnabled;
  22333. },
  22334. set: function (value) {
  22335. if (this._skeletonsEnabled === value) {
  22336. return;
  22337. }
  22338. this._skeletonsEnabled = value;
  22339. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22340. },
  22341. enumerable: true,
  22342. configurable: true
  22343. });
  22344. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22345. get: function () {
  22346. if (!this._postProcessRenderPipelineManager) {
  22347. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22348. }
  22349. return this._postProcessRenderPipelineManager;
  22350. },
  22351. enumerable: true,
  22352. configurable: true
  22353. });
  22354. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22355. get: function () {
  22356. if (!this._mainSoundTrack) {
  22357. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22358. }
  22359. return this._mainSoundTrack;
  22360. },
  22361. enumerable: true,
  22362. configurable: true
  22363. });
  22364. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22365. get: function () {
  22366. return this._alternateRendering;
  22367. },
  22368. enumerable: true,
  22369. configurable: true
  22370. });
  22371. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22372. get: function () {
  22373. return this._frustumPlanes;
  22374. },
  22375. enumerable: true,
  22376. configurable: true
  22377. });
  22378. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22379. /**
  22380. * Gets the current geometry buffer associated to the scene.
  22381. */
  22382. get: function () {
  22383. return this._geometryBufferRenderer;
  22384. },
  22385. /**
  22386. * Sets the current geometry buffer for the scene.
  22387. */
  22388. set: function (geometryBufferRenderer) {
  22389. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22390. this._geometryBufferRenderer = geometryBufferRenderer;
  22391. }
  22392. },
  22393. enumerable: true,
  22394. configurable: true
  22395. });
  22396. Object.defineProperty(Scene.prototype, "debugLayer", {
  22397. // Properties
  22398. get: function () {
  22399. if (!this._debugLayer) {
  22400. this._debugLayer = new BABYLON.DebugLayer(this);
  22401. }
  22402. return this._debugLayer;
  22403. },
  22404. enumerable: true,
  22405. configurable: true
  22406. });
  22407. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22408. get: function () {
  22409. return this._workerCollisions;
  22410. },
  22411. set: function (enabled) {
  22412. if (!BABYLON.CollisionCoordinatorLegacy) {
  22413. return;
  22414. }
  22415. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22416. this._workerCollisions = enabled;
  22417. if (this.collisionCoordinator) {
  22418. this.collisionCoordinator.destroy();
  22419. }
  22420. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22421. this.collisionCoordinator.init(this);
  22422. },
  22423. enumerable: true,
  22424. configurable: true
  22425. });
  22426. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22427. get: function () {
  22428. return this._selectionOctree;
  22429. },
  22430. enumerable: true,
  22431. configurable: true
  22432. });
  22433. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22434. /**
  22435. * The mesh that is currently under the pointer.
  22436. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22437. */
  22438. get: function () {
  22439. return this._pointerOverMesh;
  22440. },
  22441. enumerable: true,
  22442. configurable: true
  22443. });
  22444. Object.defineProperty(Scene.prototype, "pointerX", {
  22445. /**
  22446. * Current on-screen X position of the pointer
  22447. * @return {number} X position of the pointer
  22448. */
  22449. get: function () {
  22450. return this._pointerX;
  22451. },
  22452. enumerable: true,
  22453. configurable: true
  22454. });
  22455. Object.defineProperty(Scene.prototype, "pointerY", {
  22456. /**
  22457. * Current on-screen Y position of the pointer
  22458. * @return {number} Y position of the pointer
  22459. */
  22460. get: function () {
  22461. return this._pointerY;
  22462. },
  22463. enumerable: true,
  22464. configurable: true
  22465. });
  22466. Scene.prototype.getCachedMaterial = function () {
  22467. return this._cachedMaterial;
  22468. };
  22469. Scene.prototype.getCachedEffect = function () {
  22470. return this._cachedEffect;
  22471. };
  22472. Scene.prototype.getCachedVisibility = function () {
  22473. return this._cachedVisibility;
  22474. };
  22475. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22476. if (visibility === void 0) { visibility = 1; }
  22477. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22478. };
  22479. Scene.prototype.getBoundingBoxRenderer = function () {
  22480. if (!this._boundingBoxRenderer) {
  22481. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22482. }
  22483. return this._boundingBoxRenderer;
  22484. };
  22485. Scene.prototype.getOutlineRenderer = function () {
  22486. return this._outlineRenderer;
  22487. };
  22488. Scene.prototype.getEngine = function () {
  22489. return this._engine;
  22490. };
  22491. Scene.prototype.getTotalVertices = function () {
  22492. return this._totalVertices.current;
  22493. };
  22494. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22495. get: function () {
  22496. return this._totalVertices;
  22497. },
  22498. enumerable: true,
  22499. configurable: true
  22500. });
  22501. Scene.prototype.getActiveIndices = function () {
  22502. return this._activeIndices.current;
  22503. };
  22504. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22505. get: function () {
  22506. return this._activeIndices;
  22507. },
  22508. enumerable: true,
  22509. configurable: true
  22510. });
  22511. Scene.prototype.getActiveParticles = function () {
  22512. return this._activeParticles.current;
  22513. };
  22514. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22515. get: function () {
  22516. return this._activeParticles;
  22517. },
  22518. enumerable: true,
  22519. configurable: true
  22520. });
  22521. Scene.prototype.getActiveBones = function () {
  22522. return this._activeBones.current;
  22523. };
  22524. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22525. get: function () {
  22526. return this._activeBones;
  22527. },
  22528. enumerable: true,
  22529. configurable: true
  22530. });
  22531. // Stats
  22532. Scene.prototype.getInterFramePerfCounter = function () {
  22533. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22534. return 0;
  22535. };
  22536. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22537. get: function () {
  22538. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22539. return null;
  22540. },
  22541. enumerable: true,
  22542. configurable: true
  22543. });
  22544. Scene.prototype.getLastFrameDuration = function () {
  22545. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22546. return 0;
  22547. };
  22548. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22549. get: function () {
  22550. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22551. return null;
  22552. },
  22553. enumerable: true,
  22554. configurable: true
  22555. });
  22556. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22557. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22558. return 0;
  22559. };
  22560. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22561. get: function () {
  22562. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22563. return null;
  22564. },
  22565. enumerable: true,
  22566. configurable: true
  22567. });
  22568. Scene.prototype.getActiveMeshes = function () {
  22569. return this._activeMeshes;
  22570. };
  22571. Scene.prototype.getRenderTargetsDuration = function () {
  22572. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22573. return 0;
  22574. };
  22575. Scene.prototype.getRenderDuration = function () {
  22576. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22577. return 0;
  22578. };
  22579. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22580. get: function () {
  22581. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22582. return null;
  22583. },
  22584. enumerable: true,
  22585. configurable: true
  22586. });
  22587. Scene.prototype.getParticlesDuration = function () {
  22588. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22589. return 0;
  22590. };
  22591. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22592. get: function () {
  22593. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22594. return null;
  22595. },
  22596. enumerable: true,
  22597. configurable: true
  22598. });
  22599. Scene.prototype.getSpritesDuration = function () {
  22600. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22601. return 0;
  22602. };
  22603. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22604. get: function () {
  22605. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22606. return null;
  22607. },
  22608. enumerable: true,
  22609. configurable: true
  22610. });
  22611. Scene.prototype.getAnimationRatio = function () {
  22612. return this._animationRatio;
  22613. };
  22614. Scene.prototype.getRenderId = function () {
  22615. return this._renderId;
  22616. };
  22617. Scene.prototype.incrementRenderId = function () {
  22618. this._renderId++;
  22619. };
  22620. Scene.prototype._updatePointerPosition = function (evt) {
  22621. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22622. if (!canvasRect) {
  22623. return;
  22624. }
  22625. this._pointerX = evt.clientX - canvasRect.left;
  22626. this._pointerY = evt.clientY - canvasRect.top;
  22627. this._unTranslatedPointerX = this._pointerX;
  22628. this._unTranslatedPointerY = this._pointerY;
  22629. };
  22630. Scene.prototype._createUbo = function () {
  22631. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22632. this._sceneUbo.addUniform("viewProjection", 16);
  22633. this._sceneUbo.addUniform("view", 16);
  22634. };
  22635. Scene.prototype._createAlternateUbo = function () {
  22636. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22637. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22638. this._alternateSceneUbo.addUniform("view", 16);
  22639. };
  22640. // Pointers handling
  22641. /**
  22642. * Use this method to simulate a pointer move on a mesh
  22643. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22644. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22645. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22646. */
  22647. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22648. var evt = new PointerEvent("pointermove", pointerEventInit);
  22649. return this._processPointerMove(pickResult, evt);
  22650. };
  22651. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22652. var canvas = this._engine.getRenderingCanvas();
  22653. if (!canvas) {
  22654. return this;
  22655. }
  22656. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22657. this.setPointerOverSprite(null);
  22658. this.setPointerOverMesh(pickResult.pickedMesh);
  22659. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22660. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22661. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22662. }
  22663. else {
  22664. canvas.style.cursor = this.hoverCursor;
  22665. }
  22666. }
  22667. else {
  22668. canvas.style.cursor = this.defaultCursor;
  22669. }
  22670. }
  22671. else {
  22672. this.setPointerOverMesh(null);
  22673. // Sprites
  22674. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22675. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22676. this.setPointerOverSprite(pickResult.pickedSprite);
  22677. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22678. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22679. }
  22680. else {
  22681. canvas.style.cursor = this.hoverCursor;
  22682. }
  22683. }
  22684. else {
  22685. this.setPointerOverSprite(null);
  22686. // Restore pointer
  22687. canvas.style.cursor = this.defaultCursor;
  22688. }
  22689. }
  22690. if (pickResult) {
  22691. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22692. if (this.onPointerMove) {
  22693. this.onPointerMove(evt, pickResult, type);
  22694. }
  22695. if (this.onPointerObservable.hasObservers()) {
  22696. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22697. this.onPointerObservable.notifyObservers(pi, type);
  22698. }
  22699. }
  22700. return this;
  22701. };
  22702. /**
  22703. * Use this method to simulate a pointer down on a mesh
  22704. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22705. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22706. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22707. */
  22708. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22709. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22710. return this._processPointerDown(pickResult, evt);
  22711. };
  22712. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22713. var _this = this;
  22714. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22715. this._pickedDownMesh = pickResult.pickedMesh;
  22716. var actionManager = pickResult.pickedMesh.actionManager;
  22717. if (actionManager) {
  22718. if (actionManager.hasPickTriggers) {
  22719. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22720. switch (evt.button) {
  22721. case 0:
  22722. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22723. break;
  22724. case 1:
  22725. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22726. break;
  22727. case 2:
  22728. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22729. break;
  22730. }
  22731. }
  22732. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22733. window.setTimeout(function () {
  22734. 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);
  22735. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22736. if (_this._totalPointersPressed !== 0 &&
  22737. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22738. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22739. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22740. _this._startingPointerTime = 0;
  22741. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22742. }
  22743. }
  22744. }, Scene.LongPressDelay);
  22745. }
  22746. }
  22747. }
  22748. if (pickResult) {
  22749. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22750. if (this.onPointerDown) {
  22751. this.onPointerDown(evt, pickResult, type);
  22752. }
  22753. if (this.onPointerObservable.hasObservers()) {
  22754. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22755. this.onPointerObservable.notifyObservers(pi, type);
  22756. }
  22757. }
  22758. return this;
  22759. };
  22760. /**
  22761. * Use this method to simulate a pointer up on a mesh
  22762. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22763. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22764. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22765. */
  22766. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22767. var evt = new PointerEvent("pointerup", pointerEventInit);
  22768. var clickInfo = new ClickInfo();
  22769. clickInfo.singleClick = true;
  22770. clickInfo.ignore = true;
  22771. return this._processPointerUp(pickResult, evt, clickInfo);
  22772. };
  22773. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22774. if (pickResult && pickResult && pickResult.pickedMesh) {
  22775. this._pickedUpMesh = pickResult.pickedMesh;
  22776. if (this._pickedDownMesh === this._pickedUpMesh) {
  22777. if (this.onPointerPick) {
  22778. this.onPointerPick(evt, pickResult);
  22779. }
  22780. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22781. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22782. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22783. this.onPointerObservable.notifyObservers(pi, type_1);
  22784. }
  22785. }
  22786. if (pickResult.pickedMesh.actionManager) {
  22787. if (clickInfo.ignore) {
  22788. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22789. }
  22790. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22791. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22792. }
  22793. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22794. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22795. }
  22796. }
  22797. }
  22798. if (this._pickedDownMesh &&
  22799. this._pickedDownMesh.actionManager &&
  22800. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22801. this._pickedDownMesh !== this._pickedUpMesh) {
  22802. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22803. }
  22804. var type = BABYLON.PointerEventTypes.POINTERUP;
  22805. if (this.onPointerObservable.hasObservers()) {
  22806. if (!clickInfo.ignore) {
  22807. if (!clickInfo.hasSwiped) {
  22808. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22809. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22810. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22811. this.onPointerObservable.notifyObservers(pi, type_2);
  22812. }
  22813. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22814. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22815. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22816. this.onPointerObservable.notifyObservers(pi, type_3);
  22817. }
  22818. }
  22819. }
  22820. else {
  22821. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22822. this.onPointerObservable.notifyObservers(pi, type);
  22823. }
  22824. }
  22825. if (this.onPointerUp) {
  22826. this.onPointerUp(evt, pickResult, type);
  22827. }
  22828. return this;
  22829. };
  22830. /**
  22831. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22832. * @param attachUp defines if you want to attach events to pointerup
  22833. * @param attachDown defines if you want to attach events to pointerdown
  22834. * @param attachMove defines if you want to attach events to pointermove
  22835. */
  22836. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22837. var _this = this;
  22838. if (attachUp === void 0) { attachUp = true; }
  22839. if (attachDown === void 0) { attachDown = true; }
  22840. if (attachMove === void 0) { attachMove = true; }
  22841. this._initActionManager = function (act, clickInfo) {
  22842. if (!_this._meshPickProceed) {
  22843. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22844. _this._currentPickResult = pickResult;
  22845. if (pickResult) {
  22846. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22847. }
  22848. _this._meshPickProceed = true;
  22849. }
  22850. return act;
  22851. };
  22852. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22853. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22854. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22855. btn !== _this._previousButtonPressed) {
  22856. _this._doubleClickOccured = false;
  22857. clickInfo.singleClick = true;
  22858. clickInfo.ignore = false;
  22859. cb(clickInfo, _this._currentPickResult);
  22860. }
  22861. };
  22862. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22863. var clickInfo = new ClickInfo();
  22864. _this._currentPickResult = null;
  22865. var act = null;
  22866. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22867. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22868. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22869. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22870. act = _this._initActionManager(act, clickInfo);
  22871. if (act)
  22872. checkPicking = act.hasPickTriggers;
  22873. }
  22874. if (checkPicking) {
  22875. var btn = evt.button;
  22876. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22877. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22878. if (!clickInfo.hasSwiped) {
  22879. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22880. if (!checkSingleClickImmediately) {
  22881. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22882. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22883. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22884. act = _this._initActionManager(act, clickInfo);
  22885. if (act)
  22886. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22887. }
  22888. }
  22889. if (checkSingleClickImmediately) {
  22890. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22891. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22892. btn !== _this._previousButtonPressed) {
  22893. clickInfo.singleClick = true;
  22894. cb(clickInfo, _this._currentPickResult);
  22895. }
  22896. }
  22897. else {
  22898. // wait that no double click has been raised during the double click delay
  22899. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22900. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22901. }
  22902. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22903. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22904. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22905. act = _this._initActionManager(act, clickInfo);
  22906. if (act)
  22907. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22908. }
  22909. if (checkDoubleClick) {
  22910. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22911. if (btn === _this._previousButtonPressed &&
  22912. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22913. !_this._doubleClickOccured) {
  22914. // pointer has not moved for 2 clicks, it's a double click
  22915. if (!clickInfo.hasSwiped &&
  22916. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22917. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22918. _this._previousStartingPointerTime = 0;
  22919. _this._doubleClickOccured = true;
  22920. clickInfo.doubleClick = true;
  22921. clickInfo.ignore = false;
  22922. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22923. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22924. }
  22925. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22926. cb(clickInfo, _this._currentPickResult);
  22927. }
  22928. else {
  22929. _this._doubleClickOccured = false;
  22930. _this._previousStartingPointerTime = _this._startingPointerTime;
  22931. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22932. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22933. _this._previousButtonPressed = btn;
  22934. if (Scene.ExclusiveDoubleClickMode) {
  22935. if (_this._previousDelayedSimpleClickTimeout) {
  22936. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22937. }
  22938. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22939. cb(clickInfo, _this._previousPickResult);
  22940. }
  22941. else {
  22942. cb(clickInfo, _this._currentPickResult);
  22943. }
  22944. }
  22945. }
  22946. else {
  22947. _this._doubleClickOccured = false;
  22948. _this._previousStartingPointerTime = _this._startingPointerTime;
  22949. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22950. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22951. _this._previousButtonPressed = btn;
  22952. }
  22953. }
  22954. }
  22955. }
  22956. clickInfo.ignore = true;
  22957. cb(clickInfo, _this._currentPickResult);
  22958. };
  22959. this._spritePredicate = function (sprite) {
  22960. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22961. };
  22962. this._onPointerMove = function (evt) {
  22963. _this._updatePointerPosition(evt);
  22964. // PreObservable support
  22965. if (_this.onPrePointerObservable.hasObservers()) {
  22966. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22967. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22968. _this.onPrePointerObservable.notifyObservers(pi, type);
  22969. if (pi.skipOnPointerObservable) {
  22970. return;
  22971. }
  22972. }
  22973. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22974. return;
  22975. }
  22976. if (!_this.pointerMovePredicate) {
  22977. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22978. }
  22979. // Meshes
  22980. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22981. _this._processPointerMove(pickResult, evt);
  22982. };
  22983. this._onPointerDown = function (evt) {
  22984. _this._totalPointersPressed++;
  22985. _this._pickedDownMesh = null;
  22986. _this._meshPickProceed = false;
  22987. _this._updatePointerPosition(evt);
  22988. if (_this.preventDefaultOnPointerDown && canvas) {
  22989. evt.preventDefault();
  22990. canvas.focus();
  22991. }
  22992. // PreObservable support
  22993. if (_this.onPrePointerObservable.hasObservers()) {
  22994. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22995. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22996. _this.onPrePointerObservable.notifyObservers(pi, type);
  22997. if (pi.skipOnPointerObservable) {
  22998. return;
  22999. }
  23000. }
  23001. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23002. return;
  23003. }
  23004. _this._startingPointerPosition.x = _this._pointerX;
  23005. _this._startingPointerPosition.y = _this._pointerY;
  23006. _this._startingPointerTime = new Date().getTime();
  23007. if (!_this.pointerDownPredicate) {
  23008. _this.pointerDownPredicate = function (mesh) {
  23009. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23010. };
  23011. }
  23012. // Meshes
  23013. _this._pickedDownMesh = null;
  23014. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  23015. _this._processPointerDown(pickResult, evt);
  23016. // Sprites
  23017. _this._pickedDownSprite = null;
  23018. if (_this.spriteManagers.length > 0) {
  23019. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23020. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  23021. if (pickResult.pickedSprite.actionManager) {
  23022. _this._pickedDownSprite = pickResult.pickedSprite;
  23023. switch (evt.button) {
  23024. case 0:
  23025. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23026. break;
  23027. case 1:
  23028. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23029. break;
  23030. case 2:
  23031. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23032. break;
  23033. }
  23034. if (pickResult.pickedSprite.actionManager) {
  23035. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23036. }
  23037. }
  23038. }
  23039. }
  23040. };
  23041. this._onPointerUp = function (evt) {
  23042. if (_this._totalPointersPressed === 0) {
  23043. return; // So we need to test it the pointer down was pressed before.
  23044. }
  23045. _this._totalPointersPressed--;
  23046. _this._pickedUpMesh = null;
  23047. _this._meshPickProceed = false;
  23048. _this._updatePointerPosition(evt);
  23049. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  23050. // PreObservable support
  23051. if (_this.onPrePointerObservable.hasObservers()) {
  23052. if (!clickInfo.ignore) {
  23053. if (!clickInfo.hasSwiped) {
  23054. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  23055. var type = BABYLON.PointerEventTypes.POINTERTAP;
  23056. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23057. _this.onPrePointerObservable.notifyObservers(pi, type);
  23058. if (pi.skipOnPointerObservable) {
  23059. return;
  23060. }
  23061. }
  23062. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  23063. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  23064. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23065. _this.onPrePointerObservable.notifyObservers(pi, type);
  23066. if (pi.skipOnPointerObservable) {
  23067. return;
  23068. }
  23069. }
  23070. }
  23071. }
  23072. else {
  23073. var type = BABYLON.PointerEventTypes.POINTERUP;
  23074. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23075. _this.onPrePointerObservable.notifyObservers(pi, type);
  23076. if (pi.skipOnPointerObservable) {
  23077. return;
  23078. }
  23079. }
  23080. }
  23081. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23082. return;
  23083. }
  23084. if (!_this.pointerUpPredicate) {
  23085. _this.pointerUpPredicate = function (mesh) {
  23086. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23087. };
  23088. }
  23089. // Meshes
  23090. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23091. _this._initActionManager(null, clickInfo);
  23092. }
  23093. if (!pickResult) {
  23094. pickResult = _this._currentPickResult;
  23095. }
  23096. _this._processPointerUp(pickResult, evt, clickInfo);
  23097. // Sprites
  23098. if (_this.spriteManagers.length > 0) {
  23099. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23100. if (spritePickResult) {
  23101. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23102. if (spritePickResult.pickedSprite.actionManager) {
  23103. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23104. if (spritePickResult.pickedSprite.actionManager) {
  23105. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23106. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23107. }
  23108. }
  23109. }
  23110. }
  23111. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23112. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23113. }
  23114. }
  23115. }
  23116. _this._previousPickResult = _this._currentPickResult;
  23117. });
  23118. };
  23119. this._onKeyDown = function (evt) {
  23120. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23121. if (_this.onPreKeyboardObservable.hasObservers()) {
  23122. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23123. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23124. if (pi.skipOnPointerObservable) {
  23125. return;
  23126. }
  23127. }
  23128. if (_this.onKeyboardObservable.hasObservers()) {
  23129. var pi = new BABYLON.KeyboardInfo(type, evt);
  23130. _this.onKeyboardObservable.notifyObservers(pi, type);
  23131. }
  23132. if (_this.actionManager) {
  23133. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23134. }
  23135. };
  23136. this._onKeyUp = function (evt) {
  23137. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23138. if (_this.onPreKeyboardObservable.hasObservers()) {
  23139. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23140. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23141. if (pi.skipOnPointerObservable) {
  23142. return;
  23143. }
  23144. }
  23145. if (_this.onKeyboardObservable.hasObservers()) {
  23146. var pi = new BABYLON.KeyboardInfo(type, evt);
  23147. _this.onKeyboardObservable.notifyObservers(pi, type);
  23148. }
  23149. if (_this.actionManager) {
  23150. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23151. }
  23152. };
  23153. var engine = this.getEngine();
  23154. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23155. if (!canvas) {
  23156. return;
  23157. }
  23158. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23159. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23160. });
  23161. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23162. if (!canvas) {
  23163. return;
  23164. }
  23165. canvas.removeEventListener("keydown", _this._onKeyDown);
  23166. canvas.removeEventListener("keyup", _this._onKeyUp);
  23167. });
  23168. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23169. var canvas = this._engine.getRenderingCanvas();
  23170. if (!canvas) {
  23171. return;
  23172. }
  23173. if (attachMove) {
  23174. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23175. // Wheel
  23176. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23177. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23178. }
  23179. if (attachDown) {
  23180. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23181. }
  23182. if (attachUp) {
  23183. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23184. }
  23185. canvas.tabIndex = 1;
  23186. };
  23187. Scene.prototype.detachControl = function () {
  23188. var engine = this.getEngine();
  23189. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23190. var canvas = engine.getRenderingCanvas();
  23191. if (!canvas) {
  23192. return;
  23193. }
  23194. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23195. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23196. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23197. if (this._onCanvasBlurObserver) {
  23198. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23199. }
  23200. if (this._onCanvasFocusObserver) {
  23201. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23202. }
  23203. // Wheel
  23204. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23205. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23206. // Keyboard
  23207. canvas.removeEventListener("keydown", this._onKeyDown);
  23208. canvas.removeEventListener("keyup", this._onKeyUp);
  23209. // Observables
  23210. this.onKeyboardObservable.clear();
  23211. this.onPreKeyboardObservable.clear();
  23212. this.onPointerObservable.clear();
  23213. this.onPrePointerObservable.clear();
  23214. };
  23215. /**
  23216. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23217. * Delay loaded resources are not taking in account
  23218. * @return true if all required resources are ready
  23219. */
  23220. Scene.prototype.isReady = function () {
  23221. if (this._isDisposed) {
  23222. return false;
  23223. }
  23224. if (this._pendingData.length > 0) {
  23225. return false;
  23226. }
  23227. var index;
  23228. var engine = this.getEngine();
  23229. // Geometries
  23230. for (index = 0; index < this._geometries.length; index++) {
  23231. var geometry = this._geometries[index];
  23232. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23233. return false;
  23234. }
  23235. }
  23236. // Meshes
  23237. for (index = 0; index < this.meshes.length; index++) {
  23238. var mesh = this.meshes[index];
  23239. if (!mesh.isEnabled()) {
  23240. continue;
  23241. }
  23242. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23243. continue;
  23244. }
  23245. if (!mesh.isReady(true)) {
  23246. return false;
  23247. }
  23248. // Effect layers
  23249. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23250. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23251. var layer = _a[_i];
  23252. if (!layer.hasMesh(mesh)) {
  23253. continue;
  23254. }
  23255. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23256. var subMesh = _c[_b];
  23257. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23258. return false;
  23259. }
  23260. }
  23261. }
  23262. }
  23263. // Particles
  23264. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23265. var particleSystem = _e[_d];
  23266. if (!particleSystem.isReady()) {
  23267. return false;
  23268. }
  23269. }
  23270. return true;
  23271. };
  23272. Scene.prototype.resetCachedMaterial = function () {
  23273. this._cachedMaterial = null;
  23274. this._cachedEffect = null;
  23275. this._cachedVisibility = null;
  23276. };
  23277. Scene.prototype.registerBeforeRender = function (func) {
  23278. this.onBeforeRenderObservable.add(func);
  23279. };
  23280. Scene.prototype.unregisterBeforeRender = function (func) {
  23281. this.onBeforeRenderObservable.removeCallback(func);
  23282. };
  23283. Scene.prototype.registerAfterRender = function (func) {
  23284. this.onAfterRenderObservable.add(func);
  23285. };
  23286. Scene.prototype.unregisterAfterRender = function (func) {
  23287. this.onAfterRenderObservable.removeCallback(func);
  23288. };
  23289. Scene.prototype._executeOnceBeforeRender = function (func) {
  23290. var _this = this;
  23291. var execFunc = function () {
  23292. func();
  23293. setTimeout(function () {
  23294. _this.unregisterBeforeRender(execFunc);
  23295. });
  23296. };
  23297. this.registerBeforeRender(execFunc);
  23298. };
  23299. /**
  23300. * The provided function will run before render once and will be disposed afterwards.
  23301. * A timeout delay can be provided so that the function will be executed in N ms.
  23302. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23303. * @param func The function to be executed.
  23304. * @param timeout optional delay in ms
  23305. */
  23306. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23307. var _this = this;
  23308. if (timeout !== undefined) {
  23309. setTimeout(function () {
  23310. _this._executeOnceBeforeRender(func);
  23311. }, timeout);
  23312. }
  23313. else {
  23314. this._executeOnceBeforeRender(func);
  23315. }
  23316. };
  23317. Scene.prototype._addPendingData = function (data) {
  23318. this._pendingData.push(data);
  23319. };
  23320. Scene.prototype._removePendingData = function (data) {
  23321. var wasLoading = this.isLoading;
  23322. var index = this._pendingData.indexOf(data);
  23323. if (index !== -1) {
  23324. this._pendingData.splice(index, 1);
  23325. }
  23326. if (wasLoading && !this.isLoading) {
  23327. this.onDataLoadedObservable.notifyObservers(this);
  23328. }
  23329. };
  23330. Scene.prototype.getWaitingItemsCount = function () {
  23331. return this._pendingData.length;
  23332. };
  23333. Object.defineProperty(Scene.prototype, "isLoading", {
  23334. get: function () {
  23335. return this._pendingData.length > 0;
  23336. },
  23337. enumerable: true,
  23338. configurable: true
  23339. });
  23340. /**
  23341. * Registers a function to be executed when the scene is ready.
  23342. * @param {Function} func - the function to be executed.
  23343. */
  23344. Scene.prototype.executeWhenReady = function (func) {
  23345. var _this = this;
  23346. this.onReadyObservable.add(func);
  23347. if (this._executeWhenReadyTimeoutId !== -1) {
  23348. return;
  23349. }
  23350. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23351. _this._checkIsReady();
  23352. }, 150);
  23353. };
  23354. /**
  23355. * Returns a promise that resolves when the scene is ready.
  23356. * @returns A promise that resolves when the scene is ready.
  23357. */
  23358. Scene.prototype.whenReadyAsync = function () {
  23359. var _this = this;
  23360. return new Promise(function (resolve) {
  23361. _this.executeWhenReady(function () {
  23362. resolve();
  23363. });
  23364. });
  23365. };
  23366. Scene.prototype._checkIsReady = function () {
  23367. var _this = this;
  23368. if (this.isReady()) {
  23369. this.onReadyObservable.notifyObservers(this);
  23370. this.onReadyObservable.clear();
  23371. this._executeWhenReadyTimeoutId = -1;
  23372. return;
  23373. }
  23374. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23375. _this._checkIsReady();
  23376. }, 150);
  23377. };
  23378. // Animations
  23379. /**
  23380. * Will start the animation sequence of a given target
  23381. * @param target defines the target
  23382. * @param from defines from which frame should animation start
  23383. * @param to defines until which frame should animation run.
  23384. * @param weight defines the weight to apply to the animation (1.0 by default)
  23385. * @param loop defines if the animation loops
  23386. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23387. * @param onAnimationEnd defines the function to be executed when the animation ends
  23388. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23389. * @returns the animatable object created for this animation
  23390. * @see BABYLON.Animatable
  23391. */
  23392. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23393. if (weight === void 0) { weight = 1.0; }
  23394. if (speedRatio === void 0) { speedRatio = 1.0; }
  23395. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23396. returnedAnimatable.weight = weight;
  23397. return returnedAnimatable;
  23398. };
  23399. /**
  23400. * Will start the animation sequence of a given target
  23401. * @param target defines the target
  23402. * @param from defines from which frame should animation start
  23403. * @param to defines until which frame should animation run.
  23404. * @param loop defines if the animation loops
  23405. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23406. * @param onAnimationEnd defines the function to be executed when the animation ends
  23407. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23408. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23409. * @returns the animatable object created for this animation
  23410. * @see BABYLON.Animatable
  23411. */
  23412. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23413. if (speedRatio === void 0) { speedRatio = 1.0; }
  23414. if (stopCurrent === void 0) { stopCurrent = true; }
  23415. if (from > to && speedRatio > 0) {
  23416. speedRatio *= -1;
  23417. }
  23418. if (stopCurrent) {
  23419. this.stopAnimation(target);
  23420. }
  23421. if (!animatable) {
  23422. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23423. }
  23424. // Local animations
  23425. if (target.animations) {
  23426. animatable.appendAnimations(target, target.animations);
  23427. }
  23428. // Children animations
  23429. if (target.getAnimatables) {
  23430. var animatables = target.getAnimatables();
  23431. for (var index = 0; index < animatables.length; index++) {
  23432. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23433. }
  23434. }
  23435. if (stopCurrent) {
  23436. animatable.reset();
  23437. }
  23438. return animatable;
  23439. };
  23440. /**
  23441. * Begin a new animation on a given node
  23442. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23443. * @param {BABYLON.Animation[]} defines the list of animations to start
  23444. * @param {number} from defines the initial value
  23445. * @param {number} to defines the final value
  23446. * @param {boolean} loop defines if you want animation to loop (off by default)
  23447. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23448. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23449. * @returns the list of created animatables
  23450. */
  23451. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23452. if (speedRatio === undefined) {
  23453. speedRatio = 1.0;
  23454. }
  23455. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23456. return animatable;
  23457. };
  23458. /**
  23459. * Begin a new animation on a given node and its hierarchy
  23460. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23461. * @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.
  23462. * @param {BABYLON.Animation[]} defines the list of animations to start
  23463. * @param {number} from defines the initial value
  23464. * @param {number} to defines the final value
  23465. * @param {boolean} loop defines if you want animation to loop (off by default)
  23466. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23467. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23468. * @returns the list of animatables created for all nodes
  23469. */
  23470. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23471. var children = target.getDescendants(directDescendantsOnly);
  23472. var result = [];
  23473. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23474. var child = children_1[_i];
  23475. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23476. }
  23477. return result;
  23478. };
  23479. Scene.prototype.getAnimatableByTarget = function (target) {
  23480. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23481. if (this._activeAnimatables[index].target === target) {
  23482. return this._activeAnimatables[index];
  23483. }
  23484. }
  23485. return null;
  23486. };
  23487. Object.defineProperty(Scene.prototype, "animatables", {
  23488. get: function () {
  23489. return this._activeAnimatables;
  23490. },
  23491. enumerable: true,
  23492. configurable: true
  23493. });
  23494. /**
  23495. * Will stop the animation of the given target
  23496. * @param target - the target
  23497. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23498. * @see beginAnimation
  23499. */
  23500. Scene.prototype.stopAnimation = function (target, animationName) {
  23501. var animatable = this.getAnimatableByTarget(target);
  23502. if (animatable) {
  23503. animatable.stop(animationName);
  23504. }
  23505. };
  23506. /**
  23507. * Stops and removes all animations that have been applied to the scene
  23508. */
  23509. Scene.prototype.stopAllAnimations = function () {
  23510. if (this._activeAnimatables) {
  23511. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23512. this._activeAnimatables[i].stop();
  23513. }
  23514. this._activeAnimatables = [];
  23515. }
  23516. };
  23517. Scene.prototype._animate = function () {
  23518. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23519. return;
  23520. }
  23521. // Getting time
  23522. var now = BABYLON.Tools.Now;
  23523. if (!this._animationTimeLast) {
  23524. if (this._pendingData.length > 0) {
  23525. return;
  23526. }
  23527. this._animationTimeLast = now;
  23528. }
  23529. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23530. this._animationTime += deltaTime;
  23531. this._animationTimeLast = now;
  23532. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23533. this._activeAnimatables[index]._animate(this._animationTime);
  23534. }
  23535. // Late animation bindings
  23536. this._processLateAnimationBindings();
  23537. };
  23538. /** @ignore */
  23539. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23540. var target = runtimeAnimation.target;
  23541. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23542. if (!target._lateAnimationHolders) {
  23543. target._lateAnimationHolders = {};
  23544. }
  23545. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23546. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23547. totalWeight: 0,
  23548. animations: []
  23549. };
  23550. }
  23551. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23552. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23553. };
  23554. Scene.prototype._processLateAnimationBindings = function () {
  23555. if (!this._registeredForLateAnimationBindings.length) {
  23556. return;
  23557. }
  23558. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23559. var target = this._registeredForLateAnimationBindings.data[index];
  23560. for (var path in target._lateAnimationHolders) {
  23561. var holder = target._lateAnimationHolders[path];
  23562. // Sanity check
  23563. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23564. continue;
  23565. }
  23566. var normalizer = 1.0;
  23567. var finalValue = void 0;
  23568. if (holder.totalWeight < 1.0) {
  23569. // We need to mix the original value in
  23570. var originalValue = holder.animations[0].originalValue;
  23571. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23572. }
  23573. else {
  23574. // We need to normalize the weights
  23575. normalizer = holder.totalWeight;
  23576. }
  23577. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23578. var runtimeAnimation = holder.animations[animIndex];
  23579. if (finalValue) {
  23580. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23581. }
  23582. else {
  23583. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23584. }
  23585. }
  23586. runtimeAnimation.target[path] = finalValue;
  23587. }
  23588. target._lateAnimationHolders = {};
  23589. }
  23590. this._registeredForLateAnimationBindings.reset();
  23591. };
  23592. // Matrix
  23593. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23594. this._useAlternateCameraConfiguration = active;
  23595. };
  23596. Scene.prototype.getViewMatrix = function () {
  23597. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23598. };
  23599. Scene.prototype.getProjectionMatrix = function () {
  23600. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23601. };
  23602. Scene.prototype.getTransformMatrix = function () {
  23603. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23604. };
  23605. Scene.prototype.setTransformMatrix = function (view, projection) {
  23606. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23607. return;
  23608. }
  23609. this._viewUpdateFlag = view.updateFlag;
  23610. this._projectionUpdateFlag = projection.updateFlag;
  23611. this._viewMatrix = view;
  23612. this._projectionMatrix = projection;
  23613. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23614. // Update frustum
  23615. if (!this._frustumPlanes) {
  23616. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23617. }
  23618. else {
  23619. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23620. }
  23621. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23622. var otherCamera = this.activeCamera._alternateCamera;
  23623. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23624. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23625. }
  23626. if (this._sceneUbo.useUbo) {
  23627. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23628. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23629. this._sceneUbo.update();
  23630. }
  23631. };
  23632. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23633. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23634. return;
  23635. }
  23636. this._alternateViewUpdateFlag = view.updateFlag;
  23637. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23638. this._alternateViewMatrix = view;
  23639. this._alternateProjectionMatrix = projection;
  23640. if (!this._alternateTransformMatrix) {
  23641. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23642. }
  23643. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23644. if (!this._alternateSceneUbo) {
  23645. this._createAlternateUbo();
  23646. }
  23647. if (this._alternateSceneUbo.useUbo) {
  23648. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23649. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23650. this._alternateSceneUbo.update();
  23651. }
  23652. };
  23653. Scene.prototype.getSceneUniformBuffer = function () {
  23654. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23655. };
  23656. // Methods
  23657. Scene.prototype.getUniqueId = function () {
  23658. var result = Scene._uniqueIdCounter;
  23659. Scene._uniqueIdCounter++;
  23660. return result;
  23661. };
  23662. Scene.prototype.addMesh = function (newMesh) {
  23663. this.meshes.push(newMesh);
  23664. //notify the collision coordinator
  23665. if (this.collisionCoordinator) {
  23666. this.collisionCoordinator.onMeshAdded(newMesh);
  23667. }
  23668. newMesh._resyncLightSources();
  23669. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23670. };
  23671. Scene.prototype.removeMesh = function (toRemove) {
  23672. var index = this.meshes.indexOf(toRemove);
  23673. if (index !== -1) {
  23674. // Remove from the scene if mesh found
  23675. this.meshes.splice(index, 1);
  23676. }
  23677. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23678. return index;
  23679. };
  23680. Scene.prototype.addTransformNode = function (newTransformNode) {
  23681. this.transformNodes.push(newTransformNode);
  23682. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23683. };
  23684. Scene.prototype.removeTransformNode = function (toRemove) {
  23685. var index = this.transformNodes.indexOf(toRemove);
  23686. if (index !== -1) {
  23687. // Remove from the scene if found
  23688. this.transformNodes.splice(index, 1);
  23689. }
  23690. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23691. return index;
  23692. };
  23693. Scene.prototype.removeSkeleton = function (toRemove) {
  23694. var index = this.skeletons.indexOf(toRemove);
  23695. if (index !== -1) {
  23696. // Remove from the scene if found
  23697. this.skeletons.splice(index, 1);
  23698. }
  23699. return index;
  23700. };
  23701. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23702. var index = this.morphTargetManagers.indexOf(toRemove);
  23703. if (index !== -1) {
  23704. // Remove from the scene if found
  23705. this.morphTargetManagers.splice(index, 1);
  23706. }
  23707. return index;
  23708. };
  23709. Scene.prototype.removeLight = function (toRemove) {
  23710. var index = this.lights.indexOf(toRemove);
  23711. if (index !== -1) {
  23712. // Remove from meshes
  23713. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23714. var mesh = _a[_i];
  23715. mesh._removeLightSource(toRemove);
  23716. }
  23717. // Remove from the scene if mesh found
  23718. this.lights.splice(index, 1);
  23719. this.sortLightsByPriority();
  23720. }
  23721. this.onLightRemovedObservable.notifyObservers(toRemove);
  23722. return index;
  23723. };
  23724. Scene.prototype.removeCamera = function (toRemove) {
  23725. var index = this.cameras.indexOf(toRemove);
  23726. if (index !== -1) {
  23727. // Remove from the scene if mesh found
  23728. this.cameras.splice(index, 1);
  23729. }
  23730. // Remove from activeCameras
  23731. var index2 = this.activeCameras.indexOf(toRemove);
  23732. if (index2 !== -1) {
  23733. // Remove from the scene if mesh found
  23734. this.activeCameras.splice(index2, 1);
  23735. }
  23736. // Reset the activeCamera
  23737. if (this.activeCamera === toRemove) {
  23738. if (this.cameras.length > 0) {
  23739. this.activeCamera = this.cameras[0];
  23740. }
  23741. else {
  23742. this.activeCamera = null;
  23743. }
  23744. }
  23745. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23746. return index;
  23747. };
  23748. Scene.prototype.removeParticleSystem = function (toRemove) {
  23749. var index = this.particleSystems.indexOf(toRemove);
  23750. if (index !== -1) {
  23751. this.particleSystems.splice(index, 1);
  23752. }
  23753. return index;
  23754. };
  23755. ;
  23756. Scene.prototype.removeAnimation = function (toRemove) {
  23757. var index = this.animations.indexOf(toRemove);
  23758. if (index !== -1) {
  23759. this.animations.splice(index, 1);
  23760. }
  23761. return index;
  23762. };
  23763. ;
  23764. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23765. var index = this.multiMaterials.indexOf(toRemove);
  23766. if (index !== -1) {
  23767. this.multiMaterials.splice(index, 1);
  23768. }
  23769. return index;
  23770. };
  23771. ;
  23772. Scene.prototype.removeMaterial = function (toRemove) {
  23773. var index = this.materials.indexOf(toRemove);
  23774. if (index !== -1) {
  23775. this.materials.splice(index, 1);
  23776. }
  23777. return index;
  23778. };
  23779. ;
  23780. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23781. var index = this.lensFlareSystems.indexOf(toRemove);
  23782. if (index !== -1) {
  23783. this.lensFlareSystems.splice(index, 1);
  23784. }
  23785. return index;
  23786. };
  23787. ;
  23788. Scene.prototype.removeActionManager = function (toRemove) {
  23789. var index = this._actionManagers.indexOf(toRemove);
  23790. if (index !== -1) {
  23791. this._actionManagers.splice(index, 1);
  23792. }
  23793. return index;
  23794. };
  23795. ;
  23796. Scene.prototype.addLight = function (newLight) {
  23797. this.lights.push(newLight);
  23798. this.sortLightsByPriority();
  23799. // Add light to all meshes (To support if the light is removed and then readded)
  23800. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23801. var mesh = _a[_i];
  23802. if (mesh._lightSources.indexOf(newLight) === -1) {
  23803. mesh._lightSources.push(newLight);
  23804. mesh._resyncLightSources();
  23805. }
  23806. }
  23807. this.onNewLightAddedObservable.notifyObservers(newLight);
  23808. };
  23809. Scene.prototype.sortLightsByPriority = function () {
  23810. if (this.requireLightSorting) {
  23811. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23812. }
  23813. };
  23814. Scene.prototype.addCamera = function (newCamera) {
  23815. this.cameras.push(newCamera);
  23816. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23817. };
  23818. Scene.prototype.addSkeleton = function (newSkeleton) {
  23819. this.skeletons.push(newSkeleton);
  23820. };
  23821. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23822. this.particleSystems.push(newParticleSystem);
  23823. };
  23824. Scene.prototype.addAnimation = function (newAnimation) {
  23825. this.animations.push(newAnimation);
  23826. };
  23827. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23828. this.multiMaterials.push(newMultiMaterial);
  23829. };
  23830. Scene.prototype.addMaterial = function (newMaterial) {
  23831. this.materials.push(newMaterial);
  23832. };
  23833. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23834. this.morphTargetManagers.push(newMorphTargetManager);
  23835. };
  23836. Scene.prototype.addGeometry = function (newGeometrie) {
  23837. this._geometries.push(newGeometrie);
  23838. };
  23839. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23840. this.lensFlareSystems.push(newLensFlareSystem);
  23841. };
  23842. Scene.prototype.addActionManager = function (newActionManager) {
  23843. this._actionManagers.push(newActionManager);
  23844. };
  23845. /**
  23846. * Switch active camera
  23847. * @param {Camera} newCamera - new active camera
  23848. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23849. */
  23850. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23851. if (attachControl === void 0) { attachControl = true; }
  23852. var canvas = this._engine.getRenderingCanvas();
  23853. if (!canvas) {
  23854. return;
  23855. }
  23856. if (this.activeCamera) {
  23857. this.activeCamera.detachControl(canvas);
  23858. }
  23859. this.activeCamera = newCamera;
  23860. if (attachControl) {
  23861. newCamera.attachControl(canvas);
  23862. }
  23863. };
  23864. /**
  23865. * sets the active camera of the scene using its ID
  23866. * @param {string} id - the camera's ID
  23867. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23868. * @see activeCamera
  23869. */
  23870. Scene.prototype.setActiveCameraByID = function (id) {
  23871. var camera = this.getCameraByID(id);
  23872. if (camera) {
  23873. this.activeCamera = camera;
  23874. return camera;
  23875. }
  23876. return null;
  23877. };
  23878. /**
  23879. * sets the active camera of the scene using its name
  23880. * @param {string} name - the camera's name
  23881. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23882. * @see activeCamera
  23883. */
  23884. Scene.prototype.setActiveCameraByName = function (name) {
  23885. var camera = this.getCameraByName(name);
  23886. if (camera) {
  23887. this.activeCamera = camera;
  23888. return camera;
  23889. }
  23890. return null;
  23891. };
  23892. /**
  23893. * get an animation group using its name
  23894. * @param {string} the material's name
  23895. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23896. */
  23897. Scene.prototype.getAnimationGroupByName = function (name) {
  23898. for (var index = 0; index < this.animationGroups.length; index++) {
  23899. if (this.animationGroups[index].name === name) {
  23900. return this.animationGroups[index];
  23901. }
  23902. }
  23903. return null;
  23904. };
  23905. /**
  23906. * get a material using its id
  23907. * @param {string} the material's ID
  23908. * @return {BABYLON.Material|null} the material or null if none found.
  23909. */
  23910. Scene.prototype.getMaterialByID = function (id) {
  23911. for (var index = 0; index < this.materials.length; index++) {
  23912. if (this.materials[index].id === id) {
  23913. return this.materials[index];
  23914. }
  23915. }
  23916. return null;
  23917. };
  23918. /**
  23919. * get a material using its name
  23920. * @param {string} the material's name
  23921. * @return {BABYLON.Material|null} the material or null if none found.
  23922. */
  23923. Scene.prototype.getMaterialByName = function (name) {
  23924. for (var index = 0; index < this.materials.length; index++) {
  23925. if (this.materials[index].name === name) {
  23926. return this.materials[index];
  23927. }
  23928. }
  23929. return null;
  23930. };
  23931. Scene.prototype.getLensFlareSystemByName = function (name) {
  23932. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23933. if (this.lensFlareSystems[index].name === name) {
  23934. return this.lensFlareSystems[index];
  23935. }
  23936. }
  23937. return null;
  23938. };
  23939. Scene.prototype.getLensFlareSystemByID = function (id) {
  23940. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23941. if (this.lensFlareSystems[index].id === id) {
  23942. return this.lensFlareSystems[index];
  23943. }
  23944. }
  23945. return null;
  23946. };
  23947. Scene.prototype.getCameraByID = function (id) {
  23948. for (var index = 0; index < this.cameras.length; index++) {
  23949. if (this.cameras[index].id === id) {
  23950. return this.cameras[index];
  23951. }
  23952. }
  23953. return null;
  23954. };
  23955. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23956. for (var index = 0; index < this.cameras.length; index++) {
  23957. if (this.cameras[index].uniqueId === uniqueId) {
  23958. return this.cameras[index];
  23959. }
  23960. }
  23961. return null;
  23962. };
  23963. /**
  23964. * get a camera using its name
  23965. * @param {string} the camera's name
  23966. * @return {BABYLON.Camera|null} the camera or null if none found.
  23967. */
  23968. Scene.prototype.getCameraByName = function (name) {
  23969. for (var index = 0; index < this.cameras.length; index++) {
  23970. if (this.cameras[index].name === name) {
  23971. return this.cameras[index];
  23972. }
  23973. }
  23974. return null;
  23975. };
  23976. /**
  23977. * get a bone using its id
  23978. * @param {string} the bone's id
  23979. * @return {BABYLON.Bone|null} the bone or null if not found
  23980. */
  23981. Scene.prototype.getBoneByID = function (id) {
  23982. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23983. var skeleton = this.skeletons[skeletonIndex];
  23984. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23985. if (skeleton.bones[boneIndex].id === id) {
  23986. return skeleton.bones[boneIndex];
  23987. }
  23988. }
  23989. }
  23990. return null;
  23991. };
  23992. /**
  23993. * get a bone using its id
  23994. * @param {string} the bone's name
  23995. * @return {BABYLON.Bone|null} the bone or null if not found
  23996. */
  23997. Scene.prototype.getBoneByName = function (name) {
  23998. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23999. var skeleton = this.skeletons[skeletonIndex];
  24000. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  24001. if (skeleton.bones[boneIndex].name === name) {
  24002. return skeleton.bones[boneIndex];
  24003. }
  24004. }
  24005. }
  24006. return null;
  24007. };
  24008. /**
  24009. * get a light node using its name
  24010. * @param {string} the light's name
  24011. * @return {BABYLON.Light|null} the light or null if none found.
  24012. */
  24013. Scene.prototype.getLightByName = function (name) {
  24014. for (var index = 0; index < this.lights.length; index++) {
  24015. if (this.lights[index].name === name) {
  24016. return this.lights[index];
  24017. }
  24018. }
  24019. return null;
  24020. };
  24021. /**
  24022. * get a light node using its ID
  24023. * @param {string} the light's id
  24024. * @return {BABYLON.Light|null} the light or null if none found.
  24025. */
  24026. Scene.prototype.getLightByID = function (id) {
  24027. for (var index = 0; index < this.lights.length; index++) {
  24028. if (this.lights[index].id === id) {
  24029. return this.lights[index];
  24030. }
  24031. }
  24032. return null;
  24033. };
  24034. /**
  24035. * get a light node using its scene-generated unique ID
  24036. * @param {number} the light's unique id
  24037. * @return {BABYLON.Light|null} the light or null if none found.
  24038. */
  24039. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  24040. for (var index = 0; index < this.lights.length; index++) {
  24041. if (this.lights[index].uniqueId === uniqueId) {
  24042. return this.lights[index];
  24043. }
  24044. }
  24045. return null;
  24046. };
  24047. /**
  24048. * get a particle system by id
  24049. * @param id {number} the particle system id
  24050. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  24051. */
  24052. Scene.prototype.getParticleSystemByID = function (id) {
  24053. for (var index = 0; index < this.particleSystems.length; index++) {
  24054. if (this.particleSystems[index].id === id) {
  24055. return this.particleSystems[index];
  24056. }
  24057. }
  24058. return null;
  24059. };
  24060. /**
  24061. * get a geometry using its ID
  24062. * @param {string} the geometry's id
  24063. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  24064. */
  24065. Scene.prototype.getGeometryByID = function (id) {
  24066. for (var index = 0; index < this._geometries.length; index++) {
  24067. if (this._geometries[index].id === id) {
  24068. return this._geometries[index];
  24069. }
  24070. }
  24071. return null;
  24072. };
  24073. /**
  24074. * add a new geometry to this scene.
  24075. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  24076. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  24077. * @return {boolean} was the geometry added or not
  24078. */
  24079. Scene.prototype.pushGeometry = function (geometry, force) {
  24080. if (!force && this.getGeometryByID(geometry.id)) {
  24081. return false;
  24082. }
  24083. this._geometries.push(geometry);
  24084. //notify the collision coordinator
  24085. if (this.collisionCoordinator) {
  24086. this.collisionCoordinator.onGeometryAdded(geometry);
  24087. }
  24088. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24089. return true;
  24090. };
  24091. /**
  24092. * Removes an existing geometry
  24093. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24094. * @return {boolean} was the geometry removed or not
  24095. */
  24096. Scene.prototype.removeGeometry = function (geometry) {
  24097. var index = this._geometries.indexOf(geometry);
  24098. if (index > -1) {
  24099. this._geometries.splice(index, 1);
  24100. //notify the collision coordinator
  24101. if (this.collisionCoordinator) {
  24102. this.collisionCoordinator.onGeometryDeleted(geometry);
  24103. }
  24104. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24105. return true;
  24106. }
  24107. return false;
  24108. };
  24109. Scene.prototype.getGeometries = function () {
  24110. return this._geometries;
  24111. };
  24112. /**
  24113. * Get the first added mesh found of a given ID
  24114. * @param {string} id - the id to search for
  24115. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24116. */
  24117. Scene.prototype.getMeshByID = function (id) {
  24118. for (var index = 0; index < this.meshes.length; index++) {
  24119. if (this.meshes[index].id === id) {
  24120. return this.meshes[index];
  24121. }
  24122. }
  24123. return null;
  24124. };
  24125. Scene.prototype.getMeshesByID = function (id) {
  24126. return this.meshes.filter(function (m) {
  24127. return m.id === id;
  24128. });
  24129. };
  24130. /**
  24131. * Get the first added transform node found of a given ID
  24132. * @param {string} id - the id to search for
  24133. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24134. */
  24135. Scene.prototype.getTransformNodeByID = function (id) {
  24136. for (var index = 0; index < this.transformNodes.length; index++) {
  24137. if (this.transformNodes[index].id === id) {
  24138. return this.transformNodes[index];
  24139. }
  24140. }
  24141. return null;
  24142. };
  24143. Scene.prototype.getTransformNodesByID = function (id) {
  24144. return this.transformNodes.filter(function (m) {
  24145. return m.id === id;
  24146. });
  24147. };
  24148. /**
  24149. * Get a mesh with its auto-generated unique id
  24150. * @param {number} uniqueId - the unique id to search for
  24151. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24152. */
  24153. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24154. for (var index = 0; index < this.meshes.length; index++) {
  24155. if (this.meshes[index].uniqueId === uniqueId) {
  24156. return this.meshes[index];
  24157. }
  24158. }
  24159. return null;
  24160. };
  24161. /**
  24162. * Get a the last added mesh found of a given ID
  24163. * @param {string} id - the id to search for
  24164. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24165. */
  24166. Scene.prototype.getLastMeshByID = function (id) {
  24167. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24168. if (this.meshes[index].id === id) {
  24169. return this.meshes[index];
  24170. }
  24171. }
  24172. return null;
  24173. };
  24174. /**
  24175. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24176. * @param {string} id - the id to search for
  24177. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24178. */
  24179. Scene.prototype.getLastEntryByID = function (id) {
  24180. var index;
  24181. for (index = this.meshes.length - 1; index >= 0; index--) {
  24182. if (this.meshes[index].id === id) {
  24183. return this.meshes[index];
  24184. }
  24185. }
  24186. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24187. if (this.transformNodes[index].id === id) {
  24188. return this.transformNodes[index];
  24189. }
  24190. }
  24191. for (index = this.cameras.length - 1; index >= 0; index--) {
  24192. if (this.cameras[index].id === id) {
  24193. return this.cameras[index];
  24194. }
  24195. }
  24196. for (index = this.lights.length - 1; index >= 0; index--) {
  24197. if (this.lights[index].id === id) {
  24198. return this.lights[index];
  24199. }
  24200. }
  24201. return null;
  24202. };
  24203. Scene.prototype.getNodeByID = function (id) {
  24204. var mesh = this.getMeshByID(id);
  24205. if (mesh) {
  24206. return mesh;
  24207. }
  24208. var light = this.getLightByID(id);
  24209. if (light) {
  24210. return light;
  24211. }
  24212. var camera = this.getCameraByID(id);
  24213. if (camera) {
  24214. return camera;
  24215. }
  24216. var bone = this.getBoneByID(id);
  24217. return bone;
  24218. };
  24219. Scene.prototype.getNodeByName = function (name) {
  24220. var mesh = this.getMeshByName(name);
  24221. if (mesh) {
  24222. return mesh;
  24223. }
  24224. var light = this.getLightByName(name);
  24225. if (light) {
  24226. return light;
  24227. }
  24228. var camera = this.getCameraByName(name);
  24229. if (camera) {
  24230. return camera;
  24231. }
  24232. var bone = this.getBoneByName(name);
  24233. return bone;
  24234. };
  24235. Scene.prototype.getMeshByName = function (name) {
  24236. for (var index = 0; index < this.meshes.length; index++) {
  24237. if (this.meshes[index].name === name) {
  24238. return this.meshes[index];
  24239. }
  24240. }
  24241. return null;
  24242. };
  24243. Scene.prototype.getTransformNodeByName = function (name) {
  24244. for (var index = 0; index < this.transformNodes.length; index++) {
  24245. if (this.transformNodes[index].name === name) {
  24246. return this.transformNodes[index];
  24247. }
  24248. }
  24249. return null;
  24250. };
  24251. Scene.prototype.getSoundByName = function (name) {
  24252. var index;
  24253. if (BABYLON.AudioEngine) {
  24254. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24255. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24256. return this.mainSoundTrack.soundCollection[index];
  24257. }
  24258. }
  24259. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24260. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24261. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24262. return this.soundTracks[sdIndex].soundCollection[index];
  24263. }
  24264. }
  24265. }
  24266. }
  24267. return null;
  24268. };
  24269. Scene.prototype.getLastSkeletonByID = function (id) {
  24270. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24271. if (this.skeletons[index].id === id) {
  24272. return this.skeletons[index];
  24273. }
  24274. }
  24275. return null;
  24276. };
  24277. Scene.prototype.getSkeletonById = function (id) {
  24278. for (var index = 0; index < this.skeletons.length; index++) {
  24279. if (this.skeletons[index].id === id) {
  24280. return this.skeletons[index];
  24281. }
  24282. }
  24283. return null;
  24284. };
  24285. Scene.prototype.getSkeletonByName = function (name) {
  24286. for (var index = 0; index < this.skeletons.length; index++) {
  24287. if (this.skeletons[index].name === name) {
  24288. return this.skeletons[index];
  24289. }
  24290. }
  24291. return null;
  24292. };
  24293. Scene.prototype.getMorphTargetManagerById = function (id) {
  24294. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24295. if (this.morphTargetManagers[index].uniqueId === id) {
  24296. return this.morphTargetManagers[index];
  24297. }
  24298. }
  24299. return null;
  24300. };
  24301. Scene.prototype.isActiveMesh = function (mesh) {
  24302. return (this._activeMeshes.indexOf(mesh) !== -1);
  24303. };
  24304. /**
  24305. * Return a the first highlight layer of the scene with a given name.
  24306. * @param name The name of the highlight layer to look for.
  24307. * @return The highlight layer if found otherwise null.
  24308. */
  24309. Scene.prototype.getHighlightLayerByName = function (name) {
  24310. for (var index = 0; index < this.effectLayers.length; index++) {
  24311. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24312. return this.effectLayers[index];
  24313. }
  24314. }
  24315. return null;
  24316. };
  24317. /**
  24318. * Return a the first highlight layer of the scene with a given name.
  24319. * @param name The name of the highlight layer to look for.
  24320. * @return The highlight layer if found otherwise null.
  24321. */
  24322. Scene.prototype.getGlowLayerByName = function (name) {
  24323. for (var index = 0; index < this.effectLayers.length; index++) {
  24324. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24325. return this.effectLayers[index];
  24326. }
  24327. }
  24328. return null;
  24329. };
  24330. Object.defineProperty(Scene.prototype, "uid", {
  24331. /**
  24332. * Return a unique id as a string which can serve as an identifier for the scene
  24333. */
  24334. get: function () {
  24335. if (!this._uid) {
  24336. this._uid = BABYLON.Tools.RandomId();
  24337. }
  24338. return this._uid;
  24339. },
  24340. enumerable: true,
  24341. configurable: true
  24342. });
  24343. /**
  24344. * Add an externaly attached data from its key.
  24345. * This method call will fail and return false, if such key already exists.
  24346. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24347. * @param key the unique key that identifies the data
  24348. * @param data the data object to associate to the key for this Engine instance
  24349. * @return true if no such key were already present and the data was added successfully, false otherwise
  24350. */
  24351. Scene.prototype.addExternalData = function (key, data) {
  24352. if (!this._externalData) {
  24353. this._externalData = new BABYLON.StringDictionary();
  24354. }
  24355. return this._externalData.add(key, data);
  24356. };
  24357. /**
  24358. * Get an externaly attached data from its key
  24359. * @param key the unique key that identifies the data
  24360. * @return the associated data, if present (can be null), or undefined if not present
  24361. */
  24362. Scene.prototype.getExternalData = function (key) {
  24363. if (!this._externalData) {
  24364. return null;
  24365. }
  24366. return this._externalData.get(key);
  24367. };
  24368. /**
  24369. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24370. * @param key the unique key that identifies the data
  24371. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24372. * @return the associated data, can be null if the factory returned null.
  24373. */
  24374. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24375. if (!this._externalData) {
  24376. this._externalData = new BABYLON.StringDictionary();
  24377. }
  24378. return this._externalData.getOrAddWithFactory(key, factory);
  24379. };
  24380. /**
  24381. * Remove an externaly attached data from the Engine instance
  24382. * @param key the unique key that identifies the data
  24383. * @return true if the data was successfully removed, false if it doesn't exist
  24384. */
  24385. Scene.prototype.removeExternalData = function (key) {
  24386. return this._externalData.remove(key);
  24387. };
  24388. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24389. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24390. if (mesh.showSubMeshesBoundingBox) {
  24391. var boundingInfo = subMesh.getBoundingInfo();
  24392. if (boundingInfo !== null && boundingInfo !== undefined) {
  24393. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24394. }
  24395. }
  24396. var material = subMesh.getMaterial();
  24397. if (material !== null && material !== undefined) {
  24398. // Render targets
  24399. if (material.getRenderTargetTextures !== undefined) {
  24400. if (this._processedMaterials.indexOf(material) === -1) {
  24401. this._processedMaterials.push(material);
  24402. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24403. }
  24404. }
  24405. // Dispatch
  24406. this._activeIndices.addCount(subMesh.indexCount, false);
  24407. this._renderingManager.dispatch(subMesh, mesh, material);
  24408. }
  24409. }
  24410. };
  24411. /**
  24412. * Clear the processed materials smart array preventing retention point in material dispose.
  24413. */
  24414. Scene.prototype.freeProcessedMaterials = function () {
  24415. this._processedMaterials.dispose();
  24416. };
  24417. /**
  24418. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24419. */
  24420. Scene.prototype.freeActiveMeshes = function () {
  24421. this._activeMeshes.dispose();
  24422. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24423. this.activeCamera._activeMeshes.dispose();
  24424. }
  24425. if (this.activeCameras) {
  24426. for (var i = 0; i < this.activeCameras.length; i++) {
  24427. var activeCamera = this.activeCameras[i];
  24428. if (activeCamera && activeCamera._activeMeshes) {
  24429. activeCamera._activeMeshes.dispose();
  24430. }
  24431. }
  24432. }
  24433. };
  24434. /**
  24435. * Clear the info related to rendering groups preventing retention points during dispose.
  24436. */
  24437. Scene.prototype.freeRenderingGroups = function () {
  24438. if (this._renderingManager) {
  24439. this._renderingManager.freeRenderingGroups();
  24440. }
  24441. if (this.textures) {
  24442. for (var i = 0; i < this.textures.length; i++) {
  24443. var texture = this.textures[i];
  24444. if (texture && texture.renderList) {
  24445. texture.freeRenderingGroups();
  24446. }
  24447. }
  24448. }
  24449. };
  24450. Scene.prototype._isInIntermediateRendering = function () {
  24451. return this._intermediateRendering;
  24452. };
  24453. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24454. this._activeMeshCandidateProvider = provider;
  24455. };
  24456. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24457. return this._activeMeshCandidateProvider;
  24458. };
  24459. /**
  24460. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24461. */
  24462. Scene.prototype.freezeActiveMeshes = function () {
  24463. if (!this.activeCamera) {
  24464. return this;
  24465. }
  24466. if (!this._frustumPlanes) {
  24467. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24468. }
  24469. this._evaluateActiveMeshes();
  24470. this._activeMeshesFrozen = true;
  24471. return this;
  24472. };
  24473. /**
  24474. * Use this function to restart evaluating active meshes on every frame
  24475. */
  24476. Scene.prototype.unfreezeActiveMeshes = function () {
  24477. this._activeMeshesFrozen = false;
  24478. return this;
  24479. };
  24480. Scene.prototype._evaluateActiveMeshes = function () {
  24481. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24482. return;
  24483. }
  24484. if (!this.activeCamera) {
  24485. return;
  24486. }
  24487. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24488. this.activeCamera._activeMeshes.reset();
  24489. this._activeMeshes.reset();
  24490. this._renderingManager.reset();
  24491. this._processedMaterials.reset();
  24492. this._activeParticleSystems.reset();
  24493. this._activeSkeletons.reset();
  24494. this._softwareSkinnedMeshes.reset();
  24495. if (this._boundingBoxRenderer) {
  24496. this._boundingBoxRenderer.reset();
  24497. }
  24498. // Meshes
  24499. var meshes;
  24500. var len;
  24501. var checkIsEnabled = true;
  24502. // Determine mesh candidates
  24503. if (this._activeMeshCandidateProvider !== undefined) {
  24504. // Use _activeMeshCandidateProvider
  24505. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24506. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24507. if (meshes !== undefined) {
  24508. len = meshes.length;
  24509. }
  24510. else {
  24511. len = 0;
  24512. }
  24513. }
  24514. else if (this._selectionOctree !== undefined) {
  24515. // Octree
  24516. var selection = this._selectionOctree.select(this._frustumPlanes);
  24517. meshes = selection.data;
  24518. len = selection.length;
  24519. }
  24520. else {
  24521. // Full scene traversal
  24522. len = this.meshes.length;
  24523. meshes = this.meshes;
  24524. }
  24525. // Check each mesh
  24526. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24527. mesh = meshes[meshIndex];
  24528. if (mesh.isBlocked) {
  24529. continue;
  24530. }
  24531. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24532. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24533. continue;
  24534. }
  24535. mesh.computeWorldMatrix();
  24536. // Intersections
  24537. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24538. this._meshesForIntersections.pushNoDuplicate(mesh);
  24539. }
  24540. // Switch to current LOD
  24541. meshLOD = mesh.getLOD(this.activeCamera);
  24542. if (meshLOD === undefined || meshLOD === null) {
  24543. continue;
  24544. }
  24545. mesh._preActivate();
  24546. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24547. this._activeMeshes.push(mesh);
  24548. this.activeCamera._activeMeshes.push(mesh);
  24549. mesh._activate(this._renderId);
  24550. if (meshLOD !== mesh) {
  24551. meshLOD._activate(this._renderId);
  24552. }
  24553. this._activeMesh(mesh, meshLOD);
  24554. }
  24555. }
  24556. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24557. // Particle systems
  24558. if (this.particlesEnabled) {
  24559. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24560. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24561. var particleSystem = this.particleSystems[particleIndex];
  24562. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24563. continue;
  24564. }
  24565. var emitter = particleSystem.emitter;
  24566. if (!emitter.position || emitter.isEnabled()) {
  24567. this._activeParticleSystems.push(particleSystem);
  24568. particleSystem.animate();
  24569. this._renderingManager.dispatchParticles(particleSystem);
  24570. }
  24571. }
  24572. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24573. }
  24574. };
  24575. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24576. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24577. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24578. mesh.skeleton.prepare();
  24579. }
  24580. if (!mesh.computeBonesUsingShaders) {
  24581. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24582. }
  24583. }
  24584. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24585. var boundingInfo = sourceMesh.getBoundingInfo();
  24586. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24587. }
  24588. if (mesh !== undefined && mesh !== null
  24589. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24590. // Submeshes Octrees
  24591. var len;
  24592. var subMeshes;
  24593. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24594. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24595. len = intersections.length;
  24596. subMeshes = intersections.data;
  24597. }
  24598. else {
  24599. subMeshes = mesh.subMeshes;
  24600. len = subMeshes.length;
  24601. }
  24602. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24603. subMesh = subMeshes[subIndex];
  24604. this._evaluateSubMesh(subMesh, mesh);
  24605. }
  24606. }
  24607. };
  24608. Scene.prototype.updateTransformMatrix = function (force) {
  24609. if (!this.activeCamera) {
  24610. return;
  24611. }
  24612. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24613. };
  24614. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24615. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24616. };
  24617. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24618. if (camera && camera._skipRendering) {
  24619. return;
  24620. }
  24621. var engine = this._engine;
  24622. this.activeCamera = camera;
  24623. if (!this.activeCamera)
  24624. throw new Error("Active camera not set");
  24625. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24626. // Viewport
  24627. engine.setViewport(this.activeCamera.viewport);
  24628. // Camera
  24629. this.resetCachedMaterial();
  24630. this._renderId++;
  24631. this.updateTransformMatrix();
  24632. if (camera._alternateCamera) {
  24633. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24634. this._alternateRendering = true;
  24635. }
  24636. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24637. // Meshes
  24638. this._evaluateActiveMeshes();
  24639. // Software skinning
  24640. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24641. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24642. mesh.applySkeleton(mesh.skeleton);
  24643. }
  24644. // Render targets
  24645. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24646. var needsRestoreFrameBuffer = false;
  24647. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24648. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24649. }
  24650. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24651. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24652. }
  24653. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24654. this._intermediateRendering = true;
  24655. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24656. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24657. var renderTarget = this._renderTargets.data[renderIndex];
  24658. if (renderTarget._shouldRender()) {
  24659. this._renderId++;
  24660. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24661. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24662. }
  24663. }
  24664. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24665. this._intermediateRendering = false;
  24666. this._renderId++;
  24667. needsRestoreFrameBuffer = true; // Restore back buffer
  24668. }
  24669. // Render EffecttLayer Texture
  24670. var stencilState = this._engine.getStencilBuffer();
  24671. var renderEffects = false;
  24672. var needStencil = false;
  24673. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24674. this._intermediateRendering = true;
  24675. for (var i = 0; i < this.effectLayers.length; i++) {
  24676. var effectLayer = this.effectLayers[i];
  24677. if (effectLayer.shouldRender() &&
  24678. (!effectLayer.camera ||
  24679. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24680. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24681. renderEffects = true;
  24682. needStencil = needStencil || effectLayer.needStencil();
  24683. var renderTarget = effectLayer._mainTexture;
  24684. if (renderTarget._shouldRender()) {
  24685. this._renderId++;
  24686. renderTarget.render(false, false);
  24687. needsRestoreFrameBuffer = true;
  24688. }
  24689. }
  24690. }
  24691. this._intermediateRendering = false;
  24692. this._renderId++;
  24693. }
  24694. if (needsRestoreFrameBuffer) {
  24695. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24696. }
  24697. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24698. // Prepare Frame
  24699. this.postProcessManager._prepareFrame();
  24700. // Backgrounds
  24701. var layerIndex;
  24702. var layer;
  24703. if (this.layers.length) {
  24704. engine.setDepthBuffer(false);
  24705. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24706. layer = this.layers[layerIndex];
  24707. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24708. layer.render();
  24709. }
  24710. }
  24711. engine.setDepthBuffer(true);
  24712. }
  24713. // Activate effect Layer stencil
  24714. if (needStencil) {
  24715. this._engine.setStencilBuffer(true);
  24716. }
  24717. // Render
  24718. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24719. this._renderingManager.render(null, null, true, true);
  24720. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24721. // Restore effect Layer stencil
  24722. if (needStencil) {
  24723. this._engine.setStencilBuffer(stencilState);
  24724. }
  24725. // Bounding boxes
  24726. if (this._boundingBoxRenderer) {
  24727. this._boundingBoxRenderer.render();
  24728. }
  24729. // Lens flares
  24730. if (this.lensFlaresEnabled) {
  24731. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24732. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24733. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24734. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24735. lensFlareSystem.render();
  24736. }
  24737. }
  24738. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24739. }
  24740. // Foregrounds
  24741. if (this.layers.length) {
  24742. engine.setDepthBuffer(false);
  24743. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24744. layer = this.layers[layerIndex];
  24745. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24746. layer.render();
  24747. }
  24748. }
  24749. engine.setDepthBuffer(true);
  24750. }
  24751. // Effect Layer
  24752. if (renderEffects) {
  24753. engine.setDepthBuffer(false);
  24754. for (var i = 0; i < this.effectLayers.length; i++) {
  24755. if (this.effectLayers[i].shouldRender()) {
  24756. this.effectLayers[i].render();
  24757. }
  24758. }
  24759. engine.setDepthBuffer(true);
  24760. }
  24761. // Finalize frame
  24762. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24763. // Reset some special arrays
  24764. this._renderTargets.reset();
  24765. this._alternateRendering = false;
  24766. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24767. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24768. };
  24769. Scene.prototype._processSubCameras = function (camera) {
  24770. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24771. this._renderForCamera(camera);
  24772. return;
  24773. }
  24774. // rig cameras
  24775. for (var index = 0; index < camera._rigCameras.length; index++) {
  24776. this._renderForCamera(camera._rigCameras[index], camera);
  24777. }
  24778. this.activeCamera = camera;
  24779. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24780. };
  24781. Scene.prototype._checkIntersections = function () {
  24782. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24783. var sourceMesh = this._meshesForIntersections.data[index];
  24784. if (!sourceMesh.actionManager) {
  24785. continue;
  24786. }
  24787. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24788. var action = sourceMesh.actionManager.actions[actionIndex];
  24789. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24790. var parameters = action.getTriggerParameter();
  24791. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24792. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24793. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24794. if (areIntersecting && currentIntersectionInProgress === -1) {
  24795. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24796. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24797. sourceMesh._intersectionsInProgress.push(otherMesh);
  24798. }
  24799. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24800. sourceMesh._intersectionsInProgress.push(otherMesh);
  24801. }
  24802. }
  24803. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24804. //They intersected, and now they don't.
  24805. //is this trigger an exit trigger? execute an event.
  24806. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24807. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24808. }
  24809. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24810. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24811. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24812. }
  24813. }
  24814. }
  24815. }
  24816. }
  24817. };
  24818. Scene.prototype.render = function () {
  24819. if (this.isDisposed) {
  24820. return;
  24821. }
  24822. this._activeParticles.fetchNewFrame();
  24823. this._totalVertices.fetchNewFrame();
  24824. this._activeIndices.fetchNewFrame();
  24825. this._activeBones.fetchNewFrame();
  24826. this._meshesForIntersections.reset();
  24827. this.resetCachedMaterial();
  24828. this.onBeforeAnimationsObservable.notifyObservers(this);
  24829. // Actions
  24830. if (this.actionManager) {
  24831. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24832. }
  24833. //Simplification Queue
  24834. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24835. this.simplificationQueue.executeNext();
  24836. }
  24837. if (this._engine.isDeterministicLockStep()) {
  24838. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24839. var defaultFPS = (60.0 / 1000.0);
  24840. var defaultFrameTime = 1000 / 60; // frame time in MS
  24841. if (this._physicsEngine) {
  24842. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24843. }
  24844. var stepsTaken = 0;
  24845. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24846. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24847. internalSteps = Math.min(internalSteps, maxSubSteps);
  24848. do {
  24849. this.onBeforeStepObservable.notifyObservers(this);
  24850. // Animations
  24851. this._animationRatio = defaultFrameTime * defaultFPS;
  24852. this._animate();
  24853. this.onAfterAnimationsObservable.notifyObservers(this);
  24854. // Physics
  24855. if (this._physicsEngine) {
  24856. this.onBeforePhysicsObservable.notifyObservers(this);
  24857. this._physicsEngine._step(defaultFrameTime / 1000);
  24858. this.onAfterPhysicsObservable.notifyObservers(this);
  24859. }
  24860. this.onAfterStepObservable.notifyObservers(this);
  24861. this._currentStepId++;
  24862. stepsTaken++;
  24863. deltaTime -= defaultFrameTime;
  24864. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24865. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24866. }
  24867. else {
  24868. // Animations
  24869. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24870. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24871. this._animate();
  24872. this.onAfterAnimationsObservable.notifyObservers(this);
  24873. // Physics
  24874. if (this._physicsEngine) {
  24875. this.onBeforePhysicsObservable.notifyObservers(this);
  24876. this._physicsEngine._step(deltaTime / 1000.0);
  24877. this.onAfterPhysicsObservable.notifyObservers(this);
  24878. }
  24879. }
  24880. // update gamepad manager
  24881. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24882. this._gamepadManager._checkGamepadsStatus();
  24883. }
  24884. // Update Cameras
  24885. if (this.activeCameras.length > 0) {
  24886. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24887. var camera = this.activeCameras[cameraIndex];
  24888. camera.update();
  24889. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24890. // rig cameras
  24891. for (var index = 0; index < camera._rigCameras.length; index++) {
  24892. camera._rigCameras[index].update();
  24893. }
  24894. }
  24895. }
  24896. }
  24897. else if (this.activeCamera) {
  24898. this.activeCamera.update();
  24899. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24900. // rig cameras
  24901. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24902. this.activeCamera._rigCameras[index].update();
  24903. }
  24904. }
  24905. }
  24906. // Before render
  24907. this.onBeforeRenderObservable.notifyObservers(this);
  24908. // Customs render targets
  24909. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24910. var engine = this.getEngine();
  24911. var currentActiveCamera = this.activeCamera;
  24912. if (this.renderTargetsEnabled) {
  24913. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24914. this._intermediateRendering = true;
  24915. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24916. var renderTarget = this.customRenderTargets[customIndex];
  24917. if (renderTarget._shouldRender()) {
  24918. this._renderId++;
  24919. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24920. if (!this.activeCamera)
  24921. throw new Error("Active camera not set");
  24922. // Viewport
  24923. engine.setViewport(this.activeCamera.viewport);
  24924. // Camera
  24925. this.updateTransformMatrix();
  24926. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24927. }
  24928. }
  24929. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24930. this._intermediateRendering = false;
  24931. this._renderId++;
  24932. }
  24933. // Restore back buffer
  24934. if (this.customRenderTargets.length > 0) {
  24935. engine.restoreDefaultFramebuffer();
  24936. }
  24937. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24938. this.activeCamera = currentActiveCamera;
  24939. // Procedural textures
  24940. if (this.proceduralTexturesEnabled) {
  24941. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24942. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24943. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24944. if (proceduralTexture._shouldRender()) {
  24945. proceduralTexture.render();
  24946. }
  24947. }
  24948. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24949. }
  24950. // Clear
  24951. if (this.autoClearDepthAndStencil || this.autoClear) {
  24952. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24953. }
  24954. // Shadows
  24955. if (this.shadowsEnabled) {
  24956. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24957. var light = this.lights[lightIndex];
  24958. var shadowGenerator = light.getShadowGenerator();
  24959. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24960. var shadowMap = (shadowGenerator.getShadowMap());
  24961. if (this.textures.indexOf(shadowMap) !== -1) {
  24962. this._renderTargets.push(shadowMap);
  24963. }
  24964. }
  24965. }
  24966. }
  24967. // Depth renderer
  24968. for (var key in this._depthRenderer) {
  24969. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24970. }
  24971. // Geometry renderer
  24972. if (this._geometryBufferRenderer) {
  24973. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24974. }
  24975. // RenderPipeline
  24976. if (this._postProcessRenderPipelineManager) {
  24977. this._postProcessRenderPipelineManager.update();
  24978. }
  24979. // Multi-cameras?
  24980. if (this.activeCameras.length > 0) {
  24981. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24982. if (cameraIndex > 0) {
  24983. this._engine.clear(null, false, true, true);
  24984. }
  24985. this._processSubCameras(this.activeCameras[cameraIndex]);
  24986. }
  24987. }
  24988. else {
  24989. if (!this.activeCamera) {
  24990. throw new Error("No camera defined");
  24991. }
  24992. this._processSubCameras(this.activeCamera);
  24993. }
  24994. // Intersection checks
  24995. this._checkIntersections();
  24996. // Update the audio listener attached to the camera
  24997. if (BABYLON.AudioEngine) {
  24998. this._updateAudioParameters();
  24999. }
  25000. // After render
  25001. if (this.afterRender) {
  25002. this.afterRender();
  25003. }
  25004. this.onAfterRenderObservable.notifyObservers(this);
  25005. // Cleaning
  25006. for (var index = 0; index < this._toBeDisposed.length; index++) {
  25007. var data = this._toBeDisposed.data[index];
  25008. if (data) {
  25009. data.dispose();
  25010. }
  25011. this._toBeDisposed[index] = null;
  25012. }
  25013. this._toBeDisposed.reset();
  25014. if (this.dumpNextRenderTargets) {
  25015. this.dumpNextRenderTargets = false;
  25016. }
  25017. this._activeBones.addCount(0, true);
  25018. this._activeIndices.addCount(0, true);
  25019. this._activeParticles.addCount(0, true);
  25020. };
  25021. Scene.prototype._updateAudioParameters = function () {
  25022. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  25023. return;
  25024. }
  25025. var listeningCamera;
  25026. var audioEngine = BABYLON.Engine.audioEngine;
  25027. if (this.activeCameras.length > 0) {
  25028. listeningCamera = this.activeCameras[0];
  25029. }
  25030. else {
  25031. listeningCamera = this.activeCamera;
  25032. }
  25033. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  25034. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  25035. // for VR cameras
  25036. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  25037. listeningCamera = listeningCamera.rigCameras[0];
  25038. }
  25039. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  25040. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  25041. cameraDirection.normalize();
  25042. // To avoid some errors on GearVR
  25043. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  25044. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  25045. }
  25046. var i;
  25047. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25048. var sound = this.mainSoundTrack.soundCollection[i];
  25049. if (sound.useCustomAttenuation) {
  25050. sound.updateDistanceFromListener();
  25051. }
  25052. }
  25053. for (i = 0; i < this.soundTracks.length; i++) {
  25054. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25055. sound = this.soundTracks[i].soundCollection[j];
  25056. if (sound.useCustomAttenuation) {
  25057. sound.updateDistanceFromListener();
  25058. }
  25059. }
  25060. }
  25061. }
  25062. };
  25063. Object.defineProperty(Scene.prototype, "audioEnabled", {
  25064. // Audio
  25065. get: function () {
  25066. return this._audioEnabled;
  25067. },
  25068. set: function (value) {
  25069. this._audioEnabled = value;
  25070. if (BABYLON.AudioEngine) {
  25071. if (this._audioEnabled) {
  25072. this._enableAudio();
  25073. }
  25074. else {
  25075. this._disableAudio();
  25076. }
  25077. }
  25078. },
  25079. enumerable: true,
  25080. configurable: true
  25081. });
  25082. Scene.prototype._disableAudio = function () {
  25083. var i;
  25084. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25085. this.mainSoundTrack.soundCollection[i].pause();
  25086. }
  25087. for (i = 0; i < this.soundTracks.length; i++) {
  25088. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25089. this.soundTracks[i].soundCollection[j].pause();
  25090. }
  25091. }
  25092. };
  25093. Scene.prototype._enableAudio = function () {
  25094. var i;
  25095. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25096. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25097. this.mainSoundTrack.soundCollection[i].play();
  25098. }
  25099. }
  25100. for (i = 0; i < this.soundTracks.length; i++) {
  25101. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25102. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25103. this.soundTracks[i].soundCollection[j].play();
  25104. }
  25105. }
  25106. }
  25107. };
  25108. Object.defineProperty(Scene.prototype, "headphone", {
  25109. get: function () {
  25110. return this._headphone;
  25111. },
  25112. set: function (value) {
  25113. this._headphone = value;
  25114. if (BABYLON.AudioEngine) {
  25115. if (this._headphone) {
  25116. this._switchAudioModeForHeadphones();
  25117. }
  25118. else {
  25119. this._switchAudioModeForNormalSpeakers();
  25120. }
  25121. }
  25122. },
  25123. enumerable: true,
  25124. configurable: true
  25125. });
  25126. Scene.prototype._switchAudioModeForHeadphones = function () {
  25127. this.mainSoundTrack.switchPanningModelToHRTF();
  25128. for (var i = 0; i < this.soundTracks.length; i++) {
  25129. this.soundTracks[i].switchPanningModelToHRTF();
  25130. }
  25131. };
  25132. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25133. this.mainSoundTrack.switchPanningModelToEqualPower();
  25134. for (var i = 0; i < this.soundTracks.length; i++) {
  25135. this.soundTracks[i].switchPanningModelToEqualPower();
  25136. }
  25137. };
  25138. /**
  25139. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25140. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25141. * @returns the created depth renderer
  25142. */
  25143. Scene.prototype.enableDepthRenderer = function (camera) {
  25144. camera = camera || this.activeCamera;
  25145. if (!camera) {
  25146. throw "No camera available to enable depth renderer";
  25147. }
  25148. if (!this._depthRenderer[camera.id]) {
  25149. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25150. }
  25151. return this._depthRenderer[camera.id];
  25152. };
  25153. /**
  25154. * Disables a depth renderer for a given camera
  25155. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25156. */
  25157. Scene.prototype.disableDepthRenderer = function (camera) {
  25158. camera = camera || this.activeCamera;
  25159. if (!camera || !this._depthRenderer[camera.id]) {
  25160. return;
  25161. }
  25162. this._depthRenderer[camera.id].dispose();
  25163. delete this._depthRenderer[camera.id];
  25164. };
  25165. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25166. if (ratio === void 0) { ratio = 1; }
  25167. if (this._geometryBufferRenderer) {
  25168. return this._geometryBufferRenderer;
  25169. }
  25170. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25171. if (!this._geometryBufferRenderer.isSupported) {
  25172. this._geometryBufferRenderer = null;
  25173. }
  25174. return this._geometryBufferRenderer;
  25175. };
  25176. Scene.prototype.disableGeometryBufferRenderer = function () {
  25177. if (!this._geometryBufferRenderer) {
  25178. return;
  25179. }
  25180. this._geometryBufferRenderer.dispose();
  25181. this._geometryBufferRenderer = null;
  25182. };
  25183. Scene.prototype.freezeMaterials = function () {
  25184. for (var i = 0; i < this.materials.length; i++) {
  25185. this.materials[i].freeze();
  25186. }
  25187. };
  25188. Scene.prototype.unfreezeMaterials = function () {
  25189. for (var i = 0; i < this.materials.length; i++) {
  25190. this.materials[i].unfreeze();
  25191. }
  25192. };
  25193. Scene.prototype.dispose = function () {
  25194. this.beforeRender = null;
  25195. this.afterRender = null;
  25196. this.skeletons = [];
  25197. this.morphTargetManagers = [];
  25198. this.importedMeshesFiles = new Array();
  25199. this.stopAllAnimations();
  25200. this.resetCachedMaterial();
  25201. for (var key in this._depthRenderer) {
  25202. this._depthRenderer[key].dispose();
  25203. }
  25204. if (this._gamepadManager) {
  25205. this._gamepadManager.dispose();
  25206. this._gamepadManager = null;
  25207. }
  25208. // Smart arrays
  25209. if (this.activeCamera) {
  25210. this.activeCamera._activeMeshes.dispose();
  25211. this.activeCamera = null;
  25212. }
  25213. this._activeMeshes.dispose();
  25214. this._renderingManager.dispose();
  25215. this._processedMaterials.dispose();
  25216. this._activeParticleSystems.dispose();
  25217. this._activeSkeletons.dispose();
  25218. this._softwareSkinnedMeshes.dispose();
  25219. this._renderTargets.dispose();
  25220. this._registeredForLateAnimationBindings.dispose();
  25221. if (this._boundingBoxRenderer) {
  25222. this._boundingBoxRenderer.dispose();
  25223. }
  25224. this._meshesForIntersections.dispose();
  25225. this._toBeDisposed.dispose();
  25226. // Abort active requests
  25227. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25228. var request = _a[_i];
  25229. request.abort();
  25230. }
  25231. // Debug layer
  25232. if (this._debugLayer) {
  25233. this._debugLayer.hide();
  25234. }
  25235. // Events
  25236. this.onDisposeObservable.notifyObservers(this);
  25237. this.onDisposeObservable.clear();
  25238. this.onBeforeRenderObservable.clear();
  25239. this.onAfterRenderObservable.clear();
  25240. this.OnBeforeRenderTargetsRenderObservable.clear();
  25241. this.OnAfterRenderTargetsRenderObservable.clear();
  25242. this.onAfterStepObservable.clear();
  25243. this.onBeforeStepObservable.clear();
  25244. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25245. this.onAfterActiveMeshesEvaluationObservable.clear();
  25246. this.onBeforeParticlesRenderingObservable.clear();
  25247. this.onAfterParticlesRenderingObservable.clear();
  25248. this.onBeforeSpritesRenderingObservable.clear();
  25249. this.onAfterSpritesRenderingObservable.clear();
  25250. this.onBeforeDrawPhaseObservable.clear();
  25251. this.onAfterDrawPhaseObservable.clear();
  25252. this.onBeforePhysicsObservable.clear();
  25253. this.onAfterPhysicsObservable.clear();
  25254. this.onBeforeAnimationsObservable.clear();
  25255. this.onAfterAnimationsObservable.clear();
  25256. this.onDataLoadedObservable.clear();
  25257. this.detachControl();
  25258. // Release sounds & sounds tracks
  25259. if (BABYLON.AudioEngine) {
  25260. this.disposeSounds();
  25261. }
  25262. // VR Helper
  25263. if (this.VRHelper) {
  25264. this.VRHelper.dispose();
  25265. }
  25266. // Detach cameras
  25267. var canvas = this._engine.getRenderingCanvas();
  25268. if (canvas) {
  25269. var index;
  25270. for (index = 0; index < this.cameras.length; index++) {
  25271. this.cameras[index].detachControl(canvas);
  25272. }
  25273. }
  25274. // Release animation groups
  25275. while (this.animationGroups.length) {
  25276. this.animationGroups[0].dispose();
  25277. }
  25278. // Release lights
  25279. while (this.lights.length) {
  25280. this.lights[0].dispose();
  25281. }
  25282. // Release meshes
  25283. while (this.meshes.length) {
  25284. this.meshes[0].dispose(true);
  25285. }
  25286. while (this.transformNodes.length) {
  25287. this.removeTransformNode(this.transformNodes[0]);
  25288. }
  25289. // Release cameras
  25290. while (this.cameras.length) {
  25291. this.cameras[0].dispose();
  25292. }
  25293. // Release materials
  25294. if (this.defaultMaterial) {
  25295. this.defaultMaterial.dispose();
  25296. }
  25297. while (this.multiMaterials.length) {
  25298. this.multiMaterials[0].dispose();
  25299. }
  25300. while (this.materials.length) {
  25301. this.materials[0].dispose();
  25302. }
  25303. // Release particles
  25304. while (this.particleSystems.length) {
  25305. this.particleSystems[0].dispose();
  25306. }
  25307. // Release sprites
  25308. while (this.spriteManagers.length) {
  25309. this.spriteManagers[0].dispose();
  25310. }
  25311. // Release postProcesses
  25312. while (this.postProcesses.length) {
  25313. this.postProcesses[0].dispose();
  25314. }
  25315. // Release layers
  25316. while (this.layers.length) {
  25317. this.layers[0].dispose();
  25318. }
  25319. while (this.effectLayers.length) {
  25320. this.effectLayers[0].dispose();
  25321. }
  25322. // Release textures
  25323. while (this.textures.length) {
  25324. this.textures[0].dispose();
  25325. }
  25326. // Release UBO
  25327. this._sceneUbo.dispose();
  25328. if (this._alternateSceneUbo) {
  25329. this._alternateSceneUbo.dispose();
  25330. }
  25331. // Post-processes
  25332. this.postProcessManager.dispose();
  25333. if (this._postProcessRenderPipelineManager) {
  25334. this._postProcessRenderPipelineManager.dispose();
  25335. }
  25336. // Physics
  25337. if (this._physicsEngine) {
  25338. this.disablePhysicsEngine();
  25339. }
  25340. // Remove from engine
  25341. index = this._engine.scenes.indexOf(this);
  25342. if (index > -1) {
  25343. this._engine.scenes.splice(index, 1);
  25344. }
  25345. this._engine.wipeCaches(true);
  25346. this._isDisposed = true;
  25347. };
  25348. Object.defineProperty(Scene.prototype, "isDisposed", {
  25349. get: function () {
  25350. return this._isDisposed;
  25351. },
  25352. enumerable: true,
  25353. configurable: true
  25354. });
  25355. // Release sounds & sounds tracks
  25356. Scene.prototype.disposeSounds = function () {
  25357. if (!this._mainSoundTrack) {
  25358. return;
  25359. }
  25360. this.mainSoundTrack.dispose();
  25361. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25362. this.soundTracks[scIndex].dispose();
  25363. }
  25364. };
  25365. // Octrees
  25366. /**
  25367. * Get the world extend vectors with an optional filter
  25368. *
  25369. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25370. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25371. */
  25372. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25373. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25374. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25375. filterPredicate = filterPredicate || (function () { return true; });
  25376. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25377. mesh.computeWorldMatrix(true);
  25378. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25379. return;
  25380. }
  25381. var boundingInfo = mesh.getBoundingInfo();
  25382. var minBox = boundingInfo.boundingBox.minimumWorld;
  25383. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25384. BABYLON.Tools.CheckExtends(minBox, min, max);
  25385. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25386. });
  25387. return {
  25388. min: min,
  25389. max: max
  25390. };
  25391. };
  25392. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25393. if (maxCapacity === void 0) { maxCapacity = 64; }
  25394. if (maxDepth === void 0) { maxDepth = 2; }
  25395. if (!this._selectionOctree) {
  25396. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25397. }
  25398. var worldExtends = this.getWorldExtends();
  25399. // Update octree
  25400. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25401. return this._selectionOctree;
  25402. };
  25403. // Picking
  25404. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25405. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25406. var result = BABYLON.Ray.Zero();
  25407. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25408. return result;
  25409. };
  25410. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25411. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25412. var engine = this._engine;
  25413. if (!camera) {
  25414. if (!this.activeCamera)
  25415. throw new Error("Active camera not set");
  25416. camera = this.activeCamera;
  25417. }
  25418. var cameraViewport = camera.viewport;
  25419. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25420. // Moving coordinates to local viewport world
  25421. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25422. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25423. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25424. return this;
  25425. };
  25426. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25427. var result = BABYLON.Ray.Zero();
  25428. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25429. return result;
  25430. };
  25431. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25432. if (!BABYLON.PickingInfo) {
  25433. return this;
  25434. }
  25435. var engine = this._engine;
  25436. if (!camera) {
  25437. if (!this.activeCamera)
  25438. throw new Error("Active camera not set");
  25439. camera = this.activeCamera;
  25440. }
  25441. var cameraViewport = camera.viewport;
  25442. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25443. var identity = BABYLON.Matrix.Identity();
  25444. // Moving coordinates to local viewport world
  25445. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25446. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25447. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25448. return this;
  25449. };
  25450. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25451. if (!BABYLON.PickingInfo) {
  25452. return null;
  25453. }
  25454. var pickingInfo = null;
  25455. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25456. var mesh = this.meshes[meshIndex];
  25457. if (predicate) {
  25458. if (!predicate(mesh)) {
  25459. continue;
  25460. }
  25461. }
  25462. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25463. continue;
  25464. }
  25465. var world = mesh.getWorldMatrix();
  25466. var ray = rayFunction(world);
  25467. var result = mesh.intersects(ray, fastCheck);
  25468. if (!result || !result.hit)
  25469. continue;
  25470. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25471. continue;
  25472. pickingInfo = result;
  25473. if (fastCheck) {
  25474. break;
  25475. }
  25476. }
  25477. return pickingInfo || new BABYLON.PickingInfo();
  25478. };
  25479. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25480. if (!BABYLON.PickingInfo) {
  25481. return null;
  25482. }
  25483. var pickingInfos = new Array();
  25484. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25485. var mesh = this.meshes[meshIndex];
  25486. if (predicate) {
  25487. if (!predicate(mesh)) {
  25488. continue;
  25489. }
  25490. }
  25491. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25492. continue;
  25493. }
  25494. var world = mesh.getWorldMatrix();
  25495. var ray = rayFunction(world);
  25496. var result = mesh.intersects(ray, false);
  25497. if (!result || !result.hit)
  25498. continue;
  25499. pickingInfos.push(result);
  25500. }
  25501. return pickingInfos;
  25502. };
  25503. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25504. if (!BABYLON.PickingInfo) {
  25505. return null;
  25506. }
  25507. var pickingInfo = null;
  25508. if (!camera) {
  25509. if (!this.activeCamera) {
  25510. return null;
  25511. }
  25512. camera = this.activeCamera;
  25513. }
  25514. if (this.spriteManagers.length > 0) {
  25515. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25516. var spriteManager = this.spriteManagers[spriteIndex];
  25517. if (!spriteManager.isPickable) {
  25518. continue;
  25519. }
  25520. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25521. if (!result || !result.hit)
  25522. continue;
  25523. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25524. continue;
  25525. pickingInfo = result;
  25526. if (fastCheck) {
  25527. break;
  25528. }
  25529. }
  25530. }
  25531. return pickingInfo || new BABYLON.PickingInfo();
  25532. };
  25533. /** Launch a ray to try to pick a mesh in the scene
  25534. * @param x position on screen
  25535. * @param y position on screen
  25536. * @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
  25537. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25538. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25539. */
  25540. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25541. var _this = this;
  25542. if (!BABYLON.PickingInfo) {
  25543. return null;
  25544. }
  25545. return this._internalPick(function (world) {
  25546. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25547. return _this._tempPickingRay;
  25548. }, predicate, fastCheck);
  25549. };
  25550. /** Launch a ray to try to pick a sprite in the scene
  25551. * @param x position on screen
  25552. * @param y position on screen
  25553. * @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
  25554. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25555. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25556. */
  25557. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25558. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25559. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25560. };
  25561. /** Use the given ray to pick a mesh in the scene
  25562. * @param ray The ray to use to pick meshes
  25563. * @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
  25564. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25565. */
  25566. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25567. var _this = this;
  25568. return this._internalPick(function (world) {
  25569. if (!_this._pickWithRayInverseMatrix) {
  25570. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25571. }
  25572. world.invertToRef(_this._pickWithRayInverseMatrix);
  25573. if (!_this._cachedRayForTransform) {
  25574. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25575. }
  25576. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25577. return _this._cachedRayForTransform;
  25578. }, predicate, fastCheck);
  25579. };
  25580. /**
  25581. * Launch a ray to try to pick a mesh in the scene
  25582. * @param x X position on screen
  25583. * @param y Y position on screen
  25584. * @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
  25585. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25586. */
  25587. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25588. var _this = this;
  25589. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25590. };
  25591. /**
  25592. * Launch a ray to try to pick a mesh in the scene
  25593. * @param ray Ray to use
  25594. * @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
  25595. */
  25596. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25597. var _this = this;
  25598. return this._internalMultiPick(function (world) {
  25599. if (!_this._pickWithRayInverseMatrix) {
  25600. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25601. }
  25602. world.invertToRef(_this._pickWithRayInverseMatrix);
  25603. if (!_this._cachedRayForTransform) {
  25604. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25605. }
  25606. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25607. return _this._cachedRayForTransform;
  25608. }, predicate);
  25609. };
  25610. Scene.prototype.setPointerOverMesh = function (mesh) {
  25611. if (this._pointerOverMesh === mesh) {
  25612. return;
  25613. }
  25614. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25615. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25616. }
  25617. this._pointerOverMesh = mesh;
  25618. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25619. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25620. }
  25621. };
  25622. Scene.prototype.getPointerOverMesh = function () {
  25623. return this._pointerOverMesh;
  25624. };
  25625. Scene.prototype.setPointerOverSprite = function (sprite) {
  25626. if (this._pointerOverSprite === sprite) {
  25627. return;
  25628. }
  25629. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25630. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25631. }
  25632. this._pointerOverSprite = sprite;
  25633. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25634. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25635. }
  25636. };
  25637. Scene.prototype.getPointerOverSprite = function () {
  25638. return this._pointerOverSprite;
  25639. };
  25640. // Physics
  25641. Scene.prototype.getPhysicsEngine = function () {
  25642. return this._physicsEngine;
  25643. };
  25644. /**
  25645. * Enables physics to the current scene
  25646. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25647. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25648. * @return {boolean} was the physics engine initialized
  25649. */
  25650. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25651. if (gravity === void 0) { gravity = null; }
  25652. if (this._physicsEngine) {
  25653. return true;
  25654. }
  25655. try {
  25656. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25657. return true;
  25658. }
  25659. catch (e) {
  25660. BABYLON.Tools.Error(e.message);
  25661. return false;
  25662. }
  25663. };
  25664. Scene.prototype.disablePhysicsEngine = function () {
  25665. if (!this._physicsEngine) {
  25666. return;
  25667. }
  25668. this._physicsEngine.dispose();
  25669. this._physicsEngine = null;
  25670. };
  25671. Scene.prototype.isPhysicsEnabled = function () {
  25672. return this._physicsEngine !== undefined;
  25673. };
  25674. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25675. var mesh = compound.parts[0].mesh;
  25676. if (mesh.physicsImpostor) {
  25677. mesh.physicsImpostor.dispose();
  25678. mesh.physicsImpostor = null;
  25679. }
  25680. };
  25681. // Misc.
  25682. Scene.prototype._rebuildGeometries = function () {
  25683. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25684. var geometry = _a[_i];
  25685. geometry._rebuild();
  25686. }
  25687. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25688. var mesh = _c[_b];
  25689. mesh._rebuild();
  25690. }
  25691. if (this.postProcessManager) {
  25692. this.postProcessManager._rebuild();
  25693. }
  25694. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25695. var layer = _e[_d];
  25696. layer._rebuild();
  25697. }
  25698. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25699. var effectLayer = _g[_f];
  25700. effectLayer._rebuild();
  25701. }
  25702. if (this._boundingBoxRenderer) {
  25703. this._boundingBoxRenderer._rebuild();
  25704. }
  25705. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25706. var system = _j[_h];
  25707. system.rebuild();
  25708. }
  25709. if (this._postProcessRenderPipelineManager) {
  25710. this._postProcessRenderPipelineManager._rebuild();
  25711. }
  25712. };
  25713. Scene.prototype._rebuildTextures = function () {
  25714. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25715. var texture = _a[_i];
  25716. texture._rebuild();
  25717. }
  25718. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25719. };
  25720. /**
  25721. * Creates a default light for the scene.
  25722. * @param replace Whether to replace the existing lights in the scene.
  25723. */
  25724. Scene.prototype.createDefaultLight = function (replace) {
  25725. if (replace === void 0) { replace = false; }
  25726. // Dispose existing light in replace mode.
  25727. if (replace) {
  25728. if (this.lights) {
  25729. for (var i = 0; i < this.lights.length; i++) {
  25730. this.lights[i].dispose();
  25731. }
  25732. }
  25733. }
  25734. // Light
  25735. if (this.lights.length === 0) {
  25736. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25737. }
  25738. };
  25739. /**
  25740. * Creates a default camera for the scene.
  25741. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25742. * @param replace Whether to replace the existing active camera in the scene.
  25743. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25744. */
  25745. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25746. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25747. if (replace === void 0) { replace = false; }
  25748. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25749. // Dispose existing camera in replace mode.
  25750. if (replace) {
  25751. if (this.activeCamera) {
  25752. this.activeCamera.dispose();
  25753. this.activeCamera = null;
  25754. }
  25755. }
  25756. // Camera
  25757. if (!this.activeCamera) {
  25758. var worldExtends = this.getWorldExtends();
  25759. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25760. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25761. var camera;
  25762. var radius = worldSize.length() * 1.5;
  25763. // empty scene scenario!
  25764. if (!isFinite(radius)) {
  25765. radius = 1;
  25766. worldCenter.copyFromFloats(0, 0, 0);
  25767. }
  25768. if (createArcRotateCamera) {
  25769. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25770. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25771. arcRotateCamera.wheelPrecision = 100 / radius;
  25772. camera = arcRotateCamera;
  25773. }
  25774. else {
  25775. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25776. freeCamera.setTarget(worldCenter);
  25777. camera = freeCamera;
  25778. }
  25779. camera.minZ = radius * 0.01;
  25780. camera.maxZ = radius * 1000;
  25781. camera.speed = radius * 0.2;
  25782. this.activeCamera = camera;
  25783. var canvas = this.getEngine().getRenderingCanvas();
  25784. if (attachCameraControls && canvas) {
  25785. camera.attachControl(canvas);
  25786. }
  25787. }
  25788. };
  25789. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25790. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25791. if (replace === void 0) { replace = false; }
  25792. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25793. this.createDefaultLight(replace);
  25794. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25795. };
  25796. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25797. if (pbr === void 0) { pbr = false; }
  25798. if (scale === void 0) { scale = 1000; }
  25799. if (blur === void 0) { blur = 0; }
  25800. if (environmentTexture) {
  25801. this.environmentTexture = environmentTexture;
  25802. }
  25803. if (!this.environmentTexture) {
  25804. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25805. return null;
  25806. }
  25807. // Skybox
  25808. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25809. if (pbr) {
  25810. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25811. hdrSkyboxMaterial.backFaceCulling = false;
  25812. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25813. if (hdrSkyboxMaterial.reflectionTexture) {
  25814. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25815. }
  25816. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25817. hdrSkyboxMaterial.disableLighting = true;
  25818. hdrSkyboxMaterial.twoSidedLighting = true;
  25819. hdrSkybox.infiniteDistance = true;
  25820. hdrSkybox.material = hdrSkyboxMaterial;
  25821. }
  25822. else {
  25823. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25824. skyboxMaterial.backFaceCulling = false;
  25825. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25826. if (skyboxMaterial.reflectionTexture) {
  25827. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25828. }
  25829. skyboxMaterial.disableLighting = true;
  25830. hdrSkybox.infiniteDistance = true;
  25831. hdrSkybox.material = skyboxMaterial;
  25832. }
  25833. return hdrSkybox;
  25834. };
  25835. Scene.prototype.createDefaultEnvironment = function (options) {
  25836. if (BABYLON.EnvironmentHelper) {
  25837. return new BABYLON.EnvironmentHelper(options, this);
  25838. }
  25839. return null;
  25840. };
  25841. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25842. if (webVROptions === void 0) { webVROptions = {}; }
  25843. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25844. };
  25845. // Tags
  25846. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25847. if (tagsQuery === undefined) {
  25848. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25849. return list;
  25850. }
  25851. var listByTags = [];
  25852. forEach = forEach || (function (item) { return; });
  25853. for (var i in list) {
  25854. var item = list[i];
  25855. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25856. listByTags.push(item);
  25857. forEach(item);
  25858. }
  25859. }
  25860. return listByTags;
  25861. };
  25862. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25863. return this._getByTags(this.meshes, tagsQuery, forEach);
  25864. };
  25865. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25866. return this._getByTags(this.cameras, tagsQuery, forEach);
  25867. };
  25868. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25869. return this._getByTags(this.lights, tagsQuery, forEach);
  25870. };
  25871. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25872. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25873. };
  25874. /**
  25875. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25876. * This allowed control for front to back rendering or reversly depending of the special needs.
  25877. *
  25878. * @param renderingGroupId The rendering group id corresponding to its index
  25879. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25880. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25881. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25882. */
  25883. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25884. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25885. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25886. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25887. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25888. };
  25889. /**
  25890. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25891. *
  25892. * @param renderingGroupId The rendering group id corresponding to its index
  25893. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25894. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25895. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25896. */
  25897. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25898. if (depth === void 0) { depth = true; }
  25899. if (stencil === void 0) { stencil = true; }
  25900. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25901. };
  25902. /**
  25903. * Will flag all materials as dirty to trigger new shader compilation
  25904. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25905. */
  25906. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25907. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25908. var material = _a[_i];
  25909. if (predicate && !predicate(material)) {
  25910. continue;
  25911. }
  25912. material.markAsDirty(flag);
  25913. }
  25914. };
  25915. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25916. var _this = this;
  25917. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25918. this._activeRequests.push(request);
  25919. request.onCompleteObservable.add(function (request) {
  25920. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25921. });
  25922. return request;
  25923. };
  25924. /** @ignore */
  25925. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25926. var _this = this;
  25927. return new Promise(function (resolve, reject) {
  25928. _this._loadFile(url, function (data) {
  25929. resolve(data);
  25930. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25931. reject(exception);
  25932. });
  25933. });
  25934. };
  25935. // Statics
  25936. Scene._FOGMODE_NONE = 0;
  25937. Scene._FOGMODE_EXP = 1;
  25938. Scene._FOGMODE_EXP2 = 2;
  25939. Scene._FOGMODE_LINEAR = 3;
  25940. Scene._uniqueIdCounter = 0;
  25941. Scene.MinDeltaTime = 1.0;
  25942. Scene.MaxDeltaTime = 1000.0;
  25943. /** The distance in pixel that you have to move to prevent some events */
  25944. Scene.DragMovementThreshold = 10; // in pixels
  25945. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25946. Scene.LongPressDelay = 500; // in milliseconds
  25947. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25948. Scene.DoubleClickDelay = 300; // in milliseconds
  25949. /** If you need to check double click without raising a single click at first click, enable this flag */
  25950. Scene.ExclusiveDoubleClickMode = false;
  25951. return Scene;
  25952. }());
  25953. BABYLON.Scene = Scene;
  25954. })(BABYLON || (BABYLON = {}));
  25955. //# sourceMappingURL=babylon.scene.js.map
  25956. "use strict";
  25957. var BABYLON;
  25958. (function (BABYLON) {
  25959. /**
  25960. * Set of assets to keep when moving a scene into an asset container.
  25961. */
  25962. var KeepAssets = /** @class */ (function () {
  25963. function KeepAssets() {
  25964. /**
  25965. * Cameras to keep.
  25966. */
  25967. this.cameras = new Array();
  25968. /**
  25969. * Lights to keep.
  25970. */
  25971. this.lights = new Array();
  25972. /**
  25973. * Meshes to keep.
  25974. */
  25975. this.meshes = new Array();
  25976. /**
  25977. * Skeletons to keep.
  25978. */
  25979. this.skeletons = new Array();
  25980. /**
  25981. * ParticleSystems to keep.
  25982. */
  25983. this.particleSystems = new Array();
  25984. /**
  25985. * Animations to keep.
  25986. */
  25987. this.animations = new Array();
  25988. /**
  25989. * MultiMaterials to keep.
  25990. */
  25991. this.multiMaterials = new Array();
  25992. /**
  25993. * Materials to keep.
  25994. */
  25995. this.materials = new Array();
  25996. /**
  25997. * MorphTargetManagers to keep.
  25998. */
  25999. this.morphTargetManagers = new Array();
  26000. /**
  26001. * Geometries to keep.
  26002. */
  26003. this.geometries = new Array();
  26004. /**
  26005. * TransformNodes to keep.
  26006. */
  26007. this.transformNodes = new Array();
  26008. /**
  26009. * LensFlareSystems to keep.
  26010. */
  26011. this.lensFlareSystems = new Array();
  26012. /**
  26013. * ShadowGenerators to keep.
  26014. */
  26015. this.shadowGenerators = new Array();
  26016. /**
  26017. * ActionManagers to keep.
  26018. */
  26019. this.actionManagers = new Array();
  26020. /**
  26021. * Sounds to keep.
  26022. */
  26023. this.sounds = new Array();
  26024. }
  26025. return KeepAssets;
  26026. }());
  26027. BABYLON.KeepAssets = KeepAssets;
  26028. /**
  26029. * Container with a set of assets that can be added or removed from a scene.
  26030. */
  26031. var AssetContainer = /** @class */ (function () {
  26032. /**
  26033. * Instantiates an AssetContainer.
  26034. * @param scene The scene the AssetContainer belongs to.
  26035. */
  26036. function AssetContainer(scene) {
  26037. // Objects
  26038. /**
  26039. * Cameras populated in the container.
  26040. */
  26041. this.cameras = new Array();
  26042. /**
  26043. * Lights populated in the container.
  26044. */
  26045. this.lights = new Array();
  26046. /**
  26047. * Meshes populated in the container.
  26048. */
  26049. this.meshes = new Array();
  26050. /**
  26051. * Skeletons populated in the container.
  26052. */
  26053. this.skeletons = new Array();
  26054. /**
  26055. * ParticleSystems populated in the container.
  26056. */
  26057. this.particleSystems = new Array();
  26058. /**
  26059. * Animations populated in the container.
  26060. */
  26061. this.animations = new Array();
  26062. /**
  26063. * MultiMaterials populated in the container.
  26064. */
  26065. this.multiMaterials = new Array();
  26066. /**
  26067. * Materials populated in the container.
  26068. */
  26069. this.materials = new Array();
  26070. /**
  26071. * MorphTargetManagers populated in the container.
  26072. */
  26073. this.morphTargetManagers = new Array();
  26074. /**
  26075. * Geometries populated in the container.
  26076. */
  26077. this.geometries = new Array();
  26078. /**
  26079. * TransformNodes populated in the container.
  26080. */
  26081. this.transformNodes = new Array();
  26082. /**
  26083. * LensFlareSystems populated in the container.
  26084. */
  26085. this.lensFlareSystems = new Array();
  26086. /**
  26087. * ShadowGenerators populated in the container.
  26088. */
  26089. this.shadowGenerators = new Array();
  26090. /**
  26091. * ActionManagers populated in the container.
  26092. */
  26093. this.actionManagers = new Array();
  26094. /**
  26095. * Sounds populated in the container.
  26096. */
  26097. this.sounds = new Array();
  26098. this.scene = scene;
  26099. }
  26100. /**
  26101. * Adds all the assets from the container to the scene.
  26102. */
  26103. AssetContainer.prototype.addAllToScene = function () {
  26104. var _this = this;
  26105. this.cameras.forEach(function (o) {
  26106. _this.scene.addCamera(o);
  26107. });
  26108. this.lights.forEach(function (o) {
  26109. _this.scene.addLight(o);
  26110. });
  26111. this.meshes.forEach(function (o) {
  26112. _this.scene.addMesh(o);
  26113. });
  26114. this.skeletons.forEach(function (o) {
  26115. _this.scene.addSkeleton(o);
  26116. });
  26117. this.particleSystems.forEach(function (o) {
  26118. _this.scene.addParticleSystem(o);
  26119. });
  26120. this.animations.forEach(function (o) {
  26121. _this.scene.addAnimation(o);
  26122. });
  26123. this.multiMaterials.forEach(function (o) {
  26124. _this.scene.addMultiMaterial(o);
  26125. });
  26126. this.materials.forEach(function (o) {
  26127. _this.scene.addMaterial(o);
  26128. });
  26129. this.morphTargetManagers.forEach(function (o) {
  26130. _this.scene.addMorphTargetManager(o);
  26131. });
  26132. this.geometries.forEach(function (o) {
  26133. _this.scene.addGeometry(o);
  26134. });
  26135. this.transformNodes.forEach(function (o) {
  26136. _this.scene.addTransformNode(o);
  26137. });
  26138. this.lensFlareSystems.forEach(function (o) {
  26139. _this.scene.addLensFlareSystem(o);
  26140. });
  26141. this.actionManagers.forEach(function (o) {
  26142. _this.scene.addActionManager(o);
  26143. });
  26144. this.sounds.forEach(function (o) {
  26145. o.play();
  26146. o.autoplay = true;
  26147. _this.scene.mainSoundTrack.AddSound(o);
  26148. });
  26149. };
  26150. /**
  26151. * Removes all the assets in the container from the scene
  26152. */
  26153. AssetContainer.prototype.removeAllFromScene = function () {
  26154. var _this = this;
  26155. this.cameras.forEach(function (o) {
  26156. _this.scene.removeCamera(o);
  26157. });
  26158. this.lights.forEach(function (o) {
  26159. _this.scene.removeLight(o);
  26160. });
  26161. this.meshes.forEach(function (o) {
  26162. _this.scene.removeMesh(o);
  26163. });
  26164. this.skeletons.forEach(function (o) {
  26165. _this.scene.removeSkeleton(o);
  26166. });
  26167. this.particleSystems.forEach(function (o) {
  26168. _this.scene.removeParticleSystem(o);
  26169. });
  26170. this.animations.forEach(function (o) {
  26171. _this.scene.removeAnimation(o);
  26172. });
  26173. this.multiMaterials.forEach(function (o) {
  26174. _this.scene.removeMultiMaterial(o);
  26175. });
  26176. this.materials.forEach(function (o) {
  26177. _this.scene.removeMaterial(o);
  26178. });
  26179. this.morphTargetManagers.forEach(function (o) {
  26180. _this.scene.removeMorphTargetManager(o);
  26181. });
  26182. this.geometries.forEach(function (o) {
  26183. _this.scene.removeGeometry(o);
  26184. });
  26185. this.transformNodes.forEach(function (o) {
  26186. _this.scene.removeTransformNode(o);
  26187. });
  26188. this.lensFlareSystems.forEach(function (o) {
  26189. _this.scene.removeLensFlareSystem(o);
  26190. });
  26191. this.actionManagers.forEach(function (o) {
  26192. _this.scene.removeActionManager(o);
  26193. });
  26194. this.sounds.forEach(function (o) {
  26195. o.stop();
  26196. o.autoplay = false;
  26197. _this.scene.mainSoundTrack.RemoveSound(o);
  26198. });
  26199. };
  26200. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26201. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26202. var asset = sourceAssets_1[_i];
  26203. var move = true;
  26204. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26205. var keepAsset = keepAssets_1[_a];
  26206. if (asset === keepAsset) {
  26207. move = false;
  26208. break;
  26209. }
  26210. }
  26211. if (move) {
  26212. targetAssets.push(asset);
  26213. }
  26214. }
  26215. };
  26216. /**
  26217. * Removes all the assets contained in the scene and adds them to the container.
  26218. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26219. */
  26220. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26221. if (keepAssets === undefined) {
  26222. keepAssets = new KeepAssets();
  26223. }
  26224. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26225. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26226. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26227. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26228. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26229. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26230. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26231. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26232. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26233. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26234. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26235. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26236. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26237. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26238. this.removeAllFromScene();
  26239. };
  26240. return AssetContainer;
  26241. }());
  26242. BABYLON.AssetContainer = AssetContainer;
  26243. })(BABYLON || (BABYLON = {}));
  26244. //# sourceMappingURL=babylon.assetContainer.js.map
  26245. "use strict";
  26246. var BABYLON;
  26247. (function (BABYLON) {
  26248. var Buffer = /** @class */ (function () {
  26249. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26250. if (instanced === void 0) { instanced = false; }
  26251. if (engine instanceof BABYLON.Mesh) {
  26252. this._engine = engine.getScene().getEngine();
  26253. }
  26254. else {
  26255. this._engine = engine;
  26256. }
  26257. this._updatable = updatable;
  26258. this._instanced = instanced;
  26259. this._data = data;
  26260. this._strideSize = stride;
  26261. if (!postponeInternalCreation) {
  26262. this.create();
  26263. }
  26264. }
  26265. /**
  26266. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26267. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26268. * @param offset defines offset in the buffer (0 by default)
  26269. * @param size defines the size in floats of attributes (position is 3 for instance)
  26270. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26271. * @param instanced defines if the vertex buffer contains indexed data
  26272. * @returns the new vertex buffer
  26273. */
  26274. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26275. // a lot of these parameters are ignored as they are overriden by the buffer
  26276. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26277. };
  26278. // Properties
  26279. Buffer.prototype.isUpdatable = function () {
  26280. return this._updatable;
  26281. };
  26282. Buffer.prototype.getData = function () {
  26283. return this._data;
  26284. };
  26285. Buffer.prototype.getBuffer = function () {
  26286. return this._buffer;
  26287. };
  26288. Buffer.prototype.getStrideSize = function () {
  26289. return this._strideSize;
  26290. };
  26291. // public getIsInstanced(): boolean {
  26292. // return this._instanced;
  26293. // }
  26294. // public get instanceDivisor(): number {
  26295. // return this._instanceDivisor;
  26296. // }
  26297. // public set instanceDivisor(value: number) {
  26298. // this._instanceDivisor = value;
  26299. // if (value == 0) {
  26300. // this._instanced = false;
  26301. // } else {
  26302. // this._instanced = true;
  26303. // }
  26304. // }
  26305. // Methods
  26306. Buffer.prototype.create = function (data) {
  26307. if (data === void 0) { data = null; }
  26308. if (!data && this._buffer) {
  26309. return; // nothing to do
  26310. }
  26311. data = data || this._data;
  26312. if (!data) {
  26313. return;
  26314. }
  26315. if (!this._buffer) {
  26316. if (this._updatable) {
  26317. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26318. this._data = data;
  26319. }
  26320. else {
  26321. this._buffer = this._engine.createVertexBuffer(data);
  26322. }
  26323. }
  26324. else if (this._updatable) {
  26325. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26326. this._data = data;
  26327. }
  26328. };
  26329. Buffer.prototype._rebuild = function () {
  26330. this._buffer = null;
  26331. this.create(this._data);
  26332. };
  26333. Buffer.prototype.update = function (data) {
  26334. this.create(data);
  26335. };
  26336. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26337. if (!this._buffer) {
  26338. return;
  26339. }
  26340. if (this._updatable) {
  26341. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26342. this._data = null;
  26343. }
  26344. };
  26345. Buffer.prototype.dispose = function () {
  26346. if (!this._buffer) {
  26347. return;
  26348. }
  26349. if (this._engine._releaseBuffer(this._buffer)) {
  26350. this._buffer = null;
  26351. }
  26352. };
  26353. return Buffer;
  26354. }());
  26355. BABYLON.Buffer = Buffer;
  26356. })(BABYLON || (BABYLON = {}));
  26357. //# sourceMappingURL=babylon.buffer.js.map
  26358. "use strict";
  26359. var BABYLON;
  26360. (function (BABYLON) {
  26361. var VertexBuffer = /** @class */ (function () {
  26362. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26363. if (data instanceof BABYLON.Buffer) {
  26364. if (!stride) {
  26365. stride = data.getStrideSize();
  26366. }
  26367. this._buffer = data;
  26368. this._ownsBuffer = false;
  26369. }
  26370. else {
  26371. if (!stride) {
  26372. stride = VertexBuffer.DeduceStride(kind);
  26373. }
  26374. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26375. this._ownsBuffer = true;
  26376. }
  26377. this._stride = stride;
  26378. this._instanced = instanced !== undefined ? instanced : false;
  26379. this._instanceDivisor = instanced ? 1 : 0;
  26380. this._offset = offset ? offset : 0;
  26381. this._size = size ? size : stride;
  26382. this._kind = kind;
  26383. }
  26384. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26385. /**
  26386. * Gets or sets the instance divisor when in instanced mode
  26387. */
  26388. get: function () {
  26389. return this._instanceDivisor;
  26390. },
  26391. set: function (value) {
  26392. this._instanceDivisor = value;
  26393. if (value == 0) {
  26394. this._instanced = false;
  26395. }
  26396. else {
  26397. this._instanced = true;
  26398. }
  26399. },
  26400. enumerable: true,
  26401. configurable: true
  26402. });
  26403. VertexBuffer.prototype._rebuild = function () {
  26404. if (!this._buffer) {
  26405. return;
  26406. }
  26407. this._buffer._rebuild();
  26408. };
  26409. /**
  26410. * Returns the kind of the VertexBuffer (string).
  26411. */
  26412. VertexBuffer.prototype.getKind = function () {
  26413. return this._kind;
  26414. };
  26415. // Properties
  26416. /**
  26417. * Boolean : is the VertexBuffer updatable ?
  26418. */
  26419. VertexBuffer.prototype.isUpdatable = function () {
  26420. return this._buffer.isUpdatable();
  26421. };
  26422. /**
  26423. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26424. */
  26425. VertexBuffer.prototype.getData = function () {
  26426. return this._buffer.getData();
  26427. };
  26428. /**
  26429. * Returns the WebGLBuffer associated to the VertexBuffer.
  26430. */
  26431. VertexBuffer.prototype.getBuffer = function () {
  26432. return this._buffer.getBuffer();
  26433. };
  26434. /**
  26435. * Returns the stride of the VertexBuffer (integer).
  26436. */
  26437. VertexBuffer.prototype.getStrideSize = function () {
  26438. return this._stride;
  26439. };
  26440. /**
  26441. * Returns the offset (integer).
  26442. */
  26443. VertexBuffer.prototype.getOffset = function () {
  26444. return this._offset;
  26445. };
  26446. /**
  26447. * Returns the VertexBuffer total size (integer).
  26448. */
  26449. VertexBuffer.prototype.getSize = function () {
  26450. return this._size;
  26451. };
  26452. /**
  26453. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26454. */
  26455. VertexBuffer.prototype.getIsInstanced = function () {
  26456. return this._instanced;
  26457. };
  26458. /**
  26459. * Returns the instancing divisor, zero for non-instanced (integer).
  26460. */
  26461. VertexBuffer.prototype.getInstanceDivisor = function () {
  26462. return this._instanceDivisor;
  26463. };
  26464. // Methods
  26465. /**
  26466. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26467. * Returns the created WebGLBuffer.
  26468. */
  26469. VertexBuffer.prototype.create = function (data) {
  26470. return this._buffer.create(data);
  26471. };
  26472. /**
  26473. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26474. * This function will create a new buffer if the current one is not updatable
  26475. * Returns the updated WebGLBuffer.
  26476. */
  26477. VertexBuffer.prototype.update = function (data) {
  26478. return this._buffer.update(data);
  26479. };
  26480. /**
  26481. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26482. * Returns the directly updated WebGLBuffer.
  26483. */
  26484. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26485. return this._buffer.updateDirectly(data, offset);
  26486. };
  26487. /**
  26488. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26489. */
  26490. VertexBuffer.prototype.dispose = function () {
  26491. if (this._ownsBuffer) {
  26492. this._buffer.dispose();
  26493. }
  26494. };
  26495. Object.defineProperty(VertexBuffer, "PositionKind", {
  26496. get: function () {
  26497. return VertexBuffer._PositionKind;
  26498. },
  26499. enumerable: true,
  26500. configurable: true
  26501. });
  26502. Object.defineProperty(VertexBuffer, "NormalKind", {
  26503. get: function () {
  26504. return VertexBuffer._NormalKind;
  26505. },
  26506. enumerable: true,
  26507. configurable: true
  26508. });
  26509. Object.defineProperty(VertexBuffer, "TangentKind", {
  26510. get: function () {
  26511. return VertexBuffer._TangentKind;
  26512. },
  26513. enumerable: true,
  26514. configurable: true
  26515. });
  26516. Object.defineProperty(VertexBuffer, "UVKind", {
  26517. get: function () {
  26518. return VertexBuffer._UVKind;
  26519. },
  26520. enumerable: true,
  26521. configurable: true
  26522. });
  26523. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26524. get: function () {
  26525. return VertexBuffer._UV2Kind;
  26526. },
  26527. enumerable: true,
  26528. configurable: true
  26529. });
  26530. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26531. get: function () {
  26532. return VertexBuffer._UV3Kind;
  26533. },
  26534. enumerable: true,
  26535. configurable: true
  26536. });
  26537. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26538. get: function () {
  26539. return VertexBuffer._UV4Kind;
  26540. },
  26541. enumerable: true,
  26542. configurable: true
  26543. });
  26544. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26545. get: function () {
  26546. return VertexBuffer._UV5Kind;
  26547. },
  26548. enumerable: true,
  26549. configurable: true
  26550. });
  26551. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26552. get: function () {
  26553. return VertexBuffer._UV6Kind;
  26554. },
  26555. enumerable: true,
  26556. configurable: true
  26557. });
  26558. Object.defineProperty(VertexBuffer, "ColorKind", {
  26559. get: function () {
  26560. return VertexBuffer._ColorKind;
  26561. },
  26562. enumerable: true,
  26563. configurable: true
  26564. });
  26565. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26566. get: function () {
  26567. return VertexBuffer._MatricesIndicesKind;
  26568. },
  26569. enumerable: true,
  26570. configurable: true
  26571. });
  26572. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26573. get: function () {
  26574. return VertexBuffer._MatricesWeightsKind;
  26575. },
  26576. enumerable: true,
  26577. configurable: true
  26578. });
  26579. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26580. get: function () {
  26581. return VertexBuffer._MatricesIndicesExtraKind;
  26582. },
  26583. enumerable: true,
  26584. configurable: true
  26585. });
  26586. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26587. get: function () {
  26588. return VertexBuffer._MatricesWeightsExtraKind;
  26589. },
  26590. enumerable: true,
  26591. configurable: true
  26592. });
  26593. /**
  26594. * Deduces the stride given a kind.
  26595. * @param kind The kind string to deduce
  26596. * @returns The deduced stride
  26597. */
  26598. VertexBuffer.DeduceStride = function (kind) {
  26599. switch (kind) {
  26600. case VertexBuffer.UVKind:
  26601. case VertexBuffer.UV2Kind:
  26602. case VertexBuffer.UV3Kind:
  26603. case VertexBuffer.UV4Kind:
  26604. case VertexBuffer.UV5Kind:
  26605. case VertexBuffer.UV6Kind:
  26606. return 2;
  26607. case VertexBuffer.NormalKind:
  26608. case VertexBuffer.PositionKind:
  26609. return 3;
  26610. case VertexBuffer.ColorKind:
  26611. case VertexBuffer.MatricesIndicesKind:
  26612. case VertexBuffer.MatricesIndicesExtraKind:
  26613. case VertexBuffer.MatricesWeightsKind:
  26614. case VertexBuffer.MatricesWeightsExtraKind:
  26615. case VertexBuffer.TangentKind:
  26616. return 4;
  26617. default:
  26618. throw new Error("Invalid kind '" + kind + "'");
  26619. }
  26620. };
  26621. // Enums
  26622. VertexBuffer._PositionKind = "position";
  26623. VertexBuffer._NormalKind = "normal";
  26624. VertexBuffer._TangentKind = "tangent";
  26625. VertexBuffer._UVKind = "uv";
  26626. VertexBuffer._UV2Kind = "uv2";
  26627. VertexBuffer._UV3Kind = "uv3";
  26628. VertexBuffer._UV4Kind = "uv4";
  26629. VertexBuffer._UV5Kind = "uv5";
  26630. VertexBuffer._UV6Kind = "uv6";
  26631. VertexBuffer._ColorKind = "color";
  26632. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26633. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26634. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26635. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26636. return VertexBuffer;
  26637. }());
  26638. BABYLON.VertexBuffer = VertexBuffer;
  26639. })(BABYLON || (BABYLON = {}));
  26640. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26641. "use strict";
  26642. var BABYLON;
  26643. (function (BABYLON) {
  26644. /**
  26645. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26646. */
  26647. var DummyInternalTextureTracker = /** @class */ (function () {
  26648. function DummyInternalTextureTracker() {
  26649. /**
  26650. * Gets or set the previous tracker in the list
  26651. */
  26652. this.previous = null;
  26653. /**
  26654. * Gets or set the next tracker in the list
  26655. */
  26656. this.next = null;
  26657. }
  26658. return DummyInternalTextureTracker;
  26659. }());
  26660. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26661. })(BABYLON || (BABYLON = {}));
  26662. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26663. "use strict";
  26664. var BABYLON;
  26665. (function (BABYLON) {
  26666. /**
  26667. * Class used to store data associated with WebGL texture data for the engine
  26668. * This class should not be used directly
  26669. */
  26670. var InternalTexture = /** @class */ (function () {
  26671. /**
  26672. * Creates a new InternalTexture
  26673. * @param engine defines the engine to use
  26674. * @param dataSource defines the type of data that will be used
  26675. */
  26676. function InternalTexture(engine, dataSource) {
  26677. /**
  26678. * Observable called when the texture is loaded
  26679. */
  26680. this.onLoadedObservable = new BABYLON.Observable();
  26681. /**
  26682. * Gets or set the previous tracker in the list
  26683. */
  26684. this.previous = null;
  26685. /**
  26686. * Gets or set the next tracker in the list
  26687. */
  26688. this.next = null;
  26689. // Private
  26690. /** @ignore */
  26691. this._initialSlot = -1;
  26692. /** @ignore */
  26693. this._designatedSlot = -1;
  26694. /** @ignore */
  26695. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26696. /** @ignore */
  26697. this._comparisonFunction = 0;
  26698. /** @ignore */
  26699. this._references = 1;
  26700. this._engine = engine;
  26701. this._dataSource = dataSource;
  26702. this._webGLTexture = engine._createTexture();
  26703. }
  26704. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26705. /**
  26706. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26707. */
  26708. get: function () {
  26709. return this._dataSource;
  26710. },
  26711. enumerable: true,
  26712. configurable: true
  26713. });
  26714. /**
  26715. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26716. */
  26717. InternalTexture.prototype.incrementReferences = function () {
  26718. this._references++;
  26719. };
  26720. /**
  26721. * Change the size of the texture (not the size of the content)
  26722. * @param width defines the new width
  26723. * @param height defines the new height
  26724. * @param depth defines the new depth (1 by default)
  26725. */
  26726. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26727. if (depth === void 0) { depth = 1; }
  26728. this.width = width;
  26729. this.height = height;
  26730. this.depth = depth;
  26731. this.baseWidth = width;
  26732. this.baseHeight = height;
  26733. this.baseDepth = depth;
  26734. this._size = width * height * depth;
  26735. };
  26736. /** @ignore */
  26737. InternalTexture.prototype._rebuild = function () {
  26738. var _this = this;
  26739. var proxy;
  26740. this.isReady = false;
  26741. this._cachedCoordinatesMode = null;
  26742. this._cachedWrapU = null;
  26743. this._cachedWrapV = null;
  26744. this._cachedAnisotropicFilteringLevel = null;
  26745. switch (this._dataSource) {
  26746. case InternalTexture.DATASOURCE_TEMP:
  26747. return;
  26748. case InternalTexture.DATASOURCE_URL:
  26749. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26750. _this.isReady = true;
  26751. }, null, this._buffer, undefined, this.format);
  26752. proxy._swapAndDie(this);
  26753. return;
  26754. case InternalTexture.DATASOURCE_RAW:
  26755. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26756. proxy._swapAndDie(this);
  26757. this.isReady = true;
  26758. return;
  26759. case InternalTexture.DATASOURCE_RAW3D:
  26760. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26761. proxy._swapAndDie(this);
  26762. this.isReady = true;
  26763. return;
  26764. case InternalTexture.DATASOURCE_DYNAMIC:
  26765. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26766. proxy._swapAndDie(this);
  26767. // The engine will make sure to update content so no need to flag it as isReady = true
  26768. return;
  26769. case InternalTexture.DATASOURCE_RENDERTARGET:
  26770. var options = new BABYLON.RenderTargetCreationOptions();
  26771. options.generateDepthBuffer = this._generateDepthBuffer;
  26772. options.generateMipMaps = this.generateMipMaps;
  26773. options.generateStencilBuffer = this._generateStencilBuffer;
  26774. options.samplingMode = this.samplingMode;
  26775. options.type = this.type;
  26776. if (this.isCube) {
  26777. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26778. }
  26779. else {
  26780. var size = {
  26781. width: this.width,
  26782. height: this.height
  26783. };
  26784. proxy = this._engine.createRenderTargetTexture(size, options);
  26785. }
  26786. proxy._swapAndDie(this);
  26787. this.isReady = true;
  26788. return;
  26789. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26790. var depthTextureOptions = {
  26791. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26792. comparisonFunction: this._comparisonFunction,
  26793. generateStencil: this._generateStencilBuffer,
  26794. isCube: this.isCube
  26795. };
  26796. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26797. proxy._swapAndDie(this);
  26798. this.isReady = true;
  26799. return;
  26800. case InternalTexture.DATASOURCE_CUBE:
  26801. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26802. _this.isReady = true;
  26803. }, null, this.format, this._extension);
  26804. proxy._swapAndDie(this);
  26805. return;
  26806. case InternalTexture.DATASOURCE_CUBERAW:
  26807. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26808. proxy._swapAndDie(this);
  26809. this.isReady = true;
  26810. return;
  26811. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26812. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26813. if (proxy) {
  26814. proxy._swapAndDie(_this);
  26815. }
  26816. _this.isReady = true;
  26817. }, null, this.format, this._extension);
  26818. return;
  26819. }
  26820. };
  26821. InternalTexture.prototype._swapAndDie = function (target) {
  26822. target._webGLTexture = this._webGLTexture;
  26823. if (this._framebuffer) {
  26824. target._framebuffer = this._framebuffer;
  26825. }
  26826. if (this._depthStencilBuffer) {
  26827. target._depthStencilBuffer = this._depthStencilBuffer;
  26828. }
  26829. if (this._lodTextureHigh) {
  26830. if (target._lodTextureHigh) {
  26831. target._lodTextureHigh.dispose();
  26832. }
  26833. target._lodTextureHigh = this._lodTextureHigh;
  26834. }
  26835. if (this._lodTextureMid) {
  26836. if (target._lodTextureMid) {
  26837. target._lodTextureMid.dispose();
  26838. }
  26839. target._lodTextureMid = this._lodTextureMid;
  26840. }
  26841. if (this._lodTextureLow) {
  26842. if (target._lodTextureLow) {
  26843. target._lodTextureLow.dispose();
  26844. }
  26845. target._lodTextureLow = this._lodTextureLow;
  26846. }
  26847. var cache = this._engine.getLoadedTexturesCache();
  26848. var index = cache.indexOf(this);
  26849. if (index !== -1) {
  26850. cache.splice(index, 1);
  26851. }
  26852. };
  26853. /**
  26854. * Dispose the current allocated resources
  26855. */
  26856. InternalTexture.prototype.dispose = function () {
  26857. if (!this._webGLTexture) {
  26858. return;
  26859. }
  26860. this._references--;
  26861. if (this._references === 0) {
  26862. this._engine._releaseTexture(this);
  26863. this._webGLTexture = null;
  26864. this.previous = null;
  26865. this.next = null;
  26866. }
  26867. };
  26868. /**
  26869. * The source of the texture data is unknown
  26870. */
  26871. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26872. /**
  26873. * Texture data comes from an URL
  26874. */
  26875. InternalTexture.DATASOURCE_URL = 1;
  26876. /**
  26877. * Texture data is only used for temporary storage
  26878. */
  26879. InternalTexture.DATASOURCE_TEMP = 2;
  26880. /**
  26881. * Texture data comes from raw data (ArrayBuffer)
  26882. */
  26883. InternalTexture.DATASOURCE_RAW = 3;
  26884. /**
  26885. * Texture content is dynamic (video or dynamic texture)
  26886. */
  26887. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26888. /**
  26889. * Texture content is generated by rendering to it
  26890. */
  26891. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26892. /**
  26893. * Texture content is part of a multi render target process
  26894. */
  26895. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26896. /**
  26897. * Texture data comes from a cube data file
  26898. */
  26899. InternalTexture.DATASOURCE_CUBE = 7;
  26900. /**
  26901. * Texture data comes from a raw cube data
  26902. */
  26903. InternalTexture.DATASOURCE_CUBERAW = 8;
  26904. /**
  26905. * Texture data come from a prefiltered cube data file
  26906. */
  26907. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26908. /**
  26909. * Texture content is raw 3D data
  26910. */
  26911. InternalTexture.DATASOURCE_RAW3D = 10;
  26912. /**
  26913. * Texture content is a depth texture
  26914. */
  26915. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26916. return InternalTexture;
  26917. }());
  26918. BABYLON.InternalTexture = InternalTexture;
  26919. })(BABYLON || (BABYLON = {}));
  26920. //# sourceMappingURL=babylon.internalTexture.js.map
  26921. "use strict";
  26922. var BABYLON;
  26923. (function (BABYLON) {
  26924. var BaseTexture = /** @class */ (function () {
  26925. function BaseTexture(scene) {
  26926. this._hasAlpha = false;
  26927. this.getAlphaFromRGB = false;
  26928. this.level = 1;
  26929. this.coordinatesIndex = 0;
  26930. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26931. /**
  26932. * | Value | Type | Description |
  26933. * | ----- | ------------------ | ----------- |
  26934. * | 0 | CLAMP_ADDRESSMODE | |
  26935. * | 1 | WRAP_ADDRESSMODE | |
  26936. * | 2 | MIRROR_ADDRESSMODE | |
  26937. */
  26938. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26939. /**
  26940. * | Value | Type | Description |
  26941. * | ----- | ------------------ | ----------- |
  26942. * | 0 | CLAMP_ADDRESSMODE | |
  26943. * | 1 | WRAP_ADDRESSMODE | |
  26944. * | 2 | MIRROR_ADDRESSMODE | |
  26945. */
  26946. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26947. /**
  26948. * | Value | Type | Description |
  26949. * | ----- | ------------------ | ----------- |
  26950. * | 0 | CLAMP_ADDRESSMODE | |
  26951. * | 1 | WRAP_ADDRESSMODE | |
  26952. * | 2 | MIRROR_ADDRESSMODE | |
  26953. */
  26954. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26955. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26956. this.isCube = false;
  26957. this.is3D = false;
  26958. this.gammaSpace = true;
  26959. this.invertZ = false;
  26960. this.lodLevelInAlpha = false;
  26961. this.lodGenerationOffset = 0.0;
  26962. this.lodGenerationScale = 0.8;
  26963. this.isRenderTarget = false;
  26964. this.animations = new Array();
  26965. /**
  26966. * An event triggered when the texture is disposed.
  26967. * @type {BABYLON.Observable}
  26968. */
  26969. this.onDisposeObservable = new BABYLON.Observable();
  26970. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26971. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26972. if (this._scene) {
  26973. this._scene.textures.push(this);
  26974. }
  26975. this._uid = null;
  26976. }
  26977. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26978. get: function () {
  26979. return this._hasAlpha;
  26980. },
  26981. set: function (value) {
  26982. if (this._hasAlpha === value) {
  26983. return;
  26984. }
  26985. this._hasAlpha = value;
  26986. if (this._scene) {
  26987. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26988. }
  26989. },
  26990. enumerable: true,
  26991. configurable: true
  26992. });
  26993. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26994. get: function () {
  26995. return this._coordinatesMode;
  26996. },
  26997. /**
  26998. * How a texture is mapped.
  26999. *
  27000. * | Value | Type | Description |
  27001. * | ----- | ----------------------------------- | ----------- |
  27002. * | 0 | EXPLICIT_MODE | |
  27003. * | 1 | SPHERICAL_MODE | |
  27004. * | 2 | PLANAR_MODE | |
  27005. * | 3 | CUBIC_MODE | |
  27006. * | 4 | PROJECTION_MODE | |
  27007. * | 5 | SKYBOX_MODE | |
  27008. * | 6 | INVCUBIC_MODE | |
  27009. * | 7 | EQUIRECTANGULAR_MODE | |
  27010. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  27011. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  27012. */
  27013. set: function (value) {
  27014. if (this._coordinatesMode === value) {
  27015. return;
  27016. }
  27017. this._coordinatesMode = value;
  27018. if (this._scene) {
  27019. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27020. }
  27021. },
  27022. enumerable: true,
  27023. configurable: true
  27024. });
  27025. Object.defineProperty(BaseTexture.prototype, "uid", {
  27026. get: function () {
  27027. if (!this._uid) {
  27028. this._uid = BABYLON.Tools.RandomId();
  27029. }
  27030. return this._uid;
  27031. },
  27032. enumerable: true,
  27033. configurable: true
  27034. });
  27035. BaseTexture.prototype.toString = function () {
  27036. return this.name;
  27037. };
  27038. BaseTexture.prototype.getClassName = function () {
  27039. return "BaseTexture";
  27040. };
  27041. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  27042. set: function (callback) {
  27043. if (this._onDisposeObserver) {
  27044. this.onDisposeObservable.remove(this._onDisposeObserver);
  27045. }
  27046. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27047. },
  27048. enumerable: true,
  27049. configurable: true
  27050. });
  27051. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  27052. get: function () {
  27053. return true;
  27054. },
  27055. enumerable: true,
  27056. configurable: true
  27057. });
  27058. BaseTexture.prototype.getScene = function () {
  27059. return this._scene;
  27060. };
  27061. BaseTexture.prototype.getTextureMatrix = function () {
  27062. return BABYLON.Matrix.IdentityReadOnly;
  27063. };
  27064. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27065. return BABYLON.Matrix.IdentityReadOnly;
  27066. };
  27067. BaseTexture.prototype.getInternalTexture = function () {
  27068. return this._texture;
  27069. };
  27070. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  27071. return !this.isBlocking || this.isReady();
  27072. };
  27073. BaseTexture.prototype.isReady = function () {
  27074. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27075. this.delayLoad();
  27076. return false;
  27077. }
  27078. if (this._texture) {
  27079. return this._texture.isReady;
  27080. }
  27081. return false;
  27082. };
  27083. BaseTexture.prototype.getSize = function () {
  27084. if (this._texture && this._texture.width) {
  27085. return new BABYLON.Size(this._texture.width, this._texture.height);
  27086. }
  27087. if (this._texture && this._texture._size) {
  27088. return new BABYLON.Size(this._texture._size, this._texture._size);
  27089. }
  27090. return BABYLON.Size.Zero();
  27091. };
  27092. BaseTexture.prototype.getBaseSize = function () {
  27093. if (!this.isReady() || !this._texture)
  27094. return BABYLON.Size.Zero();
  27095. if (this._texture._size) {
  27096. return new BABYLON.Size(this._texture._size, this._texture._size);
  27097. }
  27098. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27099. };
  27100. BaseTexture.prototype.scale = function (ratio) {
  27101. };
  27102. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27103. get: function () {
  27104. return false;
  27105. },
  27106. enumerable: true,
  27107. configurable: true
  27108. });
  27109. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27110. if (!this._scene) {
  27111. return null;
  27112. }
  27113. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27114. for (var index = 0; index < texturesCache.length; index++) {
  27115. var texturesCacheEntry = texturesCache[index];
  27116. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27117. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27118. texturesCacheEntry.incrementReferences();
  27119. return texturesCacheEntry;
  27120. }
  27121. }
  27122. }
  27123. return null;
  27124. };
  27125. BaseTexture.prototype._rebuild = function () {
  27126. };
  27127. BaseTexture.prototype.delayLoad = function () {
  27128. };
  27129. BaseTexture.prototype.clone = function () {
  27130. return null;
  27131. };
  27132. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27133. get: function () {
  27134. if (!this._texture) {
  27135. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27136. }
  27137. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27138. },
  27139. enumerable: true,
  27140. configurable: true
  27141. });
  27142. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27143. get: function () {
  27144. if (!this._texture) {
  27145. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27146. }
  27147. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27148. },
  27149. enumerable: true,
  27150. configurable: true
  27151. });
  27152. BaseTexture.prototype.readPixels = function (faceIndex) {
  27153. if (faceIndex === void 0) { faceIndex = 0; }
  27154. if (!this._texture) {
  27155. return null;
  27156. }
  27157. var size = this.getSize();
  27158. var scene = this.getScene();
  27159. if (!scene) {
  27160. return null;
  27161. }
  27162. var engine = scene.getEngine();
  27163. if (this._texture.isCube) {
  27164. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27165. }
  27166. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27167. };
  27168. BaseTexture.prototype.releaseInternalTexture = function () {
  27169. if (this._texture) {
  27170. this._texture.dispose();
  27171. this._texture = null;
  27172. }
  27173. };
  27174. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27175. get: function () {
  27176. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27177. return null;
  27178. }
  27179. if (!this._texture._sphericalPolynomial) {
  27180. this._texture._sphericalPolynomial =
  27181. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27182. }
  27183. return this._texture._sphericalPolynomial;
  27184. },
  27185. set: function (value) {
  27186. if (this._texture) {
  27187. this._texture._sphericalPolynomial = value;
  27188. }
  27189. },
  27190. enumerable: true,
  27191. configurable: true
  27192. });
  27193. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27194. get: function () {
  27195. if (this._texture) {
  27196. return this._texture._lodTextureHigh;
  27197. }
  27198. return null;
  27199. },
  27200. enumerable: true,
  27201. configurable: true
  27202. });
  27203. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27204. get: function () {
  27205. if (this._texture) {
  27206. return this._texture._lodTextureMid;
  27207. }
  27208. return null;
  27209. },
  27210. enumerable: true,
  27211. configurable: true
  27212. });
  27213. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27214. get: function () {
  27215. if (this._texture) {
  27216. return this._texture._lodTextureLow;
  27217. }
  27218. return null;
  27219. },
  27220. enumerable: true,
  27221. configurable: true
  27222. });
  27223. BaseTexture.prototype.dispose = function () {
  27224. if (!this._scene) {
  27225. return;
  27226. }
  27227. // Animations
  27228. this._scene.stopAnimation(this);
  27229. // Remove from scene
  27230. this._scene._removePendingData(this);
  27231. var index = this._scene.textures.indexOf(this);
  27232. if (index >= 0) {
  27233. this._scene.textures.splice(index, 1);
  27234. }
  27235. if (this._texture === undefined) {
  27236. return;
  27237. }
  27238. // Release
  27239. this.releaseInternalTexture();
  27240. // Callback
  27241. this.onDisposeObservable.notifyObservers(this);
  27242. this.onDisposeObservable.clear();
  27243. };
  27244. BaseTexture.prototype.serialize = function () {
  27245. if (!this.name) {
  27246. return null;
  27247. }
  27248. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27249. // Animations
  27250. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27251. return serializationObject;
  27252. };
  27253. BaseTexture.WhenAllReady = function (textures, callback) {
  27254. var numRemaining = textures.length;
  27255. if (numRemaining === 0) {
  27256. callback();
  27257. return;
  27258. }
  27259. var _loop_1 = function () {
  27260. texture = textures[i];
  27261. if (texture.isReady()) {
  27262. if (--numRemaining === 0) {
  27263. callback();
  27264. }
  27265. }
  27266. else {
  27267. onLoadObservable = texture.onLoadObservable;
  27268. var onLoadCallback_1 = function () {
  27269. onLoadObservable.removeCallback(onLoadCallback_1);
  27270. if (--numRemaining === 0) {
  27271. callback();
  27272. }
  27273. };
  27274. onLoadObservable.add(onLoadCallback_1);
  27275. }
  27276. };
  27277. var texture, onLoadObservable;
  27278. for (var i = 0; i < textures.length; i++) {
  27279. _loop_1();
  27280. }
  27281. };
  27282. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27283. __decorate([
  27284. BABYLON.serialize()
  27285. ], BaseTexture.prototype, "name", void 0);
  27286. __decorate([
  27287. BABYLON.serialize("hasAlpha")
  27288. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27289. __decorate([
  27290. BABYLON.serialize()
  27291. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27292. __decorate([
  27293. BABYLON.serialize()
  27294. ], BaseTexture.prototype, "level", void 0);
  27295. __decorate([
  27296. BABYLON.serialize()
  27297. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27298. __decorate([
  27299. BABYLON.serialize("coordinatesMode")
  27300. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27301. __decorate([
  27302. BABYLON.serialize()
  27303. ], BaseTexture.prototype, "wrapU", void 0);
  27304. __decorate([
  27305. BABYLON.serialize()
  27306. ], BaseTexture.prototype, "wrapV", void 0);
  27307. __decorate([
  27308. BABYLON.serialize()
  27309. ], BaseTexture.prototype, "wrapR", void 0);
  27310. __decorate([
  27311. BABYLON.serialize()
  27312. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27313. __decorate([
  27314. BABYLON.serialize()
  27315. ], BaseTexture.prototype, "isCube", void 0);
  27316. __decorate([
  27317. BABYLON.serialize()
  27318. ], BaseTexture.prototype, "is3D", void 0);
  27319. __decorate([
  27320. BABYLON.serialize()
  27321. ], BaseTexture.prototype, "gammaSpace", void 0);
  27322. __decorate([
  27323. BABYLON.serialize()
  27324. ], BaseTexture.prototype, "invertZ", void 0);
  27325. __decorate([
  27326. BABYLON.serialize()
  27327. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27328. __decorate([
  27329. BABYLON.serialize()
  27330. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27331. __decorate([
  27332. BABYLON.serialize()
  27333. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27334. __decorate([
  27335. BABYLON.serialize()
  27336. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27337. return BaseTexture;
  27338. }());
  27339. BABYLON.BaseTexture = BaseTexture;
  27340. })(BABYLON || (BABYLON = {}));
  27341. //# sourceMappingURL=babylon.baseTexture.js.map
  27342. "use strict";
  27343. var BABYLON;
  27344. (function (BABYLON) {
  27345. var Texture = /** @class */ (function (_super) {
  27346. __extends(Texture, _super);
  27347. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27348. if (noMipmap === void 0) { noMipmap = false; }
  27349. if (invertY === void 0) { invertY = true; }
  27350. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27351. if (onLoad === void 0) { onLoad = null; }
  27352. if (onError === void 0) { onError = null; }
  27353. if (buffer === void 0) { buffer = null; }
  27354. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27355. var _this = _super.call(this, scene) || this;
  27356. _this.uOffset = 0;
  27357. _this.vOffset = 0;
  27358. _this.uScale = 1.0;
  27359. _this.vScale = 1.0;
  27360. _this.uAng = 0;
  27361. _this.vAng = 0;
  27362. _this.wAng = 0;
  27363. _this._isBlocking = true;
  27364. _this.name = url || "";
  27365. _this.url = url;
  27366. _this._noMipmap = noMipmap;
  27367. _this._invertY = invertY;
  27368. _this._samplingMode = samplingMode;
  27369. _this._buffer = buffer;
  27370. _this._deleteBuffer = deleteBuffer;
  27371. if (format) {
  27372. _this._format = format;
  27373. }
  27374. scene = _this.getScene();
  27375. if (!scene) {
  27376. return _this;
  27377. }
  27378. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27379. var load = function () {
  27380. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27381. _this.onLoadObservable.notifyObservers(_this);
  27382. }
  27383. if (onLoad) {
  27384. onLoad();
  27385. }
  27386. if (!_this.isBlocking && scene) {
  27387. scene.resetCachedMaterial();
  27388. }
  27389. };
  27390. if (!_this.url) {
  27391. _this._delayedOnLoad = load;
  27392. _this._delayedOnError = onError;
  27393. return _this;
  27394. }
  27395. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27396. if (!_this._texture) {
  27397. if (!scene.useDelayedTextureLoading) {
  27398. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27399. if (deleteBuffer) {
  27400. delete _this._buffer;
  27401. }
  27402. }
  27403. else {
  27404. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27405. _this._delayedOnLoad = load;
  27406. _this._delayedOnError = onError;
  27407. }
  27408. }
  27409. else {
  27410. if (_this._texture.isReady) {
  27411. BABYLON.Tools.SetImmediate(function () { return load(); });
  27412. }
  27413. else {
  27414. _this._texture.onLoadedObservable.add(load);
  27415. }
  27416. }
  27417. return _this;
  27418. }
  27419. Object.defineProperty(Texture.prototype, "noMipmap", {
  27420. get: function () {
  27421. return this._noMipmap;
  27422. },
  27423. enumerable: true,
  27424. configurable: true
  27425. });
  27426. Object.defineProperty(Texture.prototype, "isBlocking", {
  27427. get: function () {
  27428. return this._isBlocking;
  27429. },
  27430. set: function (value) {
  27431. this._isBlocking = value;
  27432. },
  27433. enumerable: true,
  27434. configurable: true
  27435. });
  27436. Object.defineProperty(Texture.prototype, "samplingMode", {
  27437. get: function () {
  27438. return this._samplingMode;
  27439. },
  27440. enumerable: true,
  27441. configurable: true
  27442. });
  27443. Texture.prototype.updateURL = function (url) {
  27444. this.url = url;
  27445. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27446. this.delayLoad();
  27447. };
  27448. Texture.prototype.delayLoad = function () {
  27449. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27450. return;
  27451. }
  27452. var scene = this.getScene();
  27453. if (!scene) {
  27454. return;
  27455. }
  27456. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27457. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27458. if (!this._texture) {
  27459. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27460. if (this._deleteBuffer) {
  27461. delete this._buffer;
  27462. }
  27463. }
  27464. else {
  27465. if (this._delayedOnLoad) {
  27466. if (this._texture.isReady) {
  27467. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27468. }
  27469. else {
  27470. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27471. }
  27472. }
  27473. }
  27474. this._delayedOnLoad = null;
  27475. this._delayedOnError = null;
  27476. };
  27477. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27478. if (!this._texture) {
  27479. return;
  27480. }
  27481. var scene = this.getScene();
  27482. if (!scene) {
  27483. return;
  27484. }
  27485. this._samplingMode = samplingMode;
  27486. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27487. };
  27488. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27489. x *= this.uScale;
  27490. y *= this.vScale;
  27491. x -= 0.5 * this.uScale;
  27492. y -= 0.5 * this.vScale;
  27493. z -= 0.5;
  27494. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27495. t.x += 0.5 * this.uScale + this.uOffset;
  27496. t.y += 0.5 * this.vScale + this.vOffset;
  27497. t.z += 0.5;
  27498. };
  27499. Texture.prototype.getTextureMatrix = function () {
  27500. var _this = this;
  27501. if (this.uOffset === this._cachedUOffset &&
  27502. this.vOffset === this._cachedVOffset &&
  27503. this.uScale === this._cachedUScale &&
  27504. this.vScale === this._cachedVScale &&
  27505. this.uAng === this._cachedUAng &&
  27506. this.vAng === this._cachedVAng &&
  27507. this.wAng === this._cachedWAng) {
  27508. return this._cachedTextureMatrix;
  27509. }
  27510. this._cachedUOffset = this.uOffset;
  27511. this._cachedVOffset = this.vOffset;
  27512. this._cachedUScale = this.uScale;
  27513. this._cachedVScale = this.vScale;
  27514. this._cachedUAng = this.uAng;
  27515. this._cachedVAng = this.vAng;
  27516. this._cachedWAng = this.wAng;
  27517. if (!this._cachedTextureMatrix) {
  27518. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27519. this._rowGenerationMatrix = new BABYLON.Matrix();
  27520. this._t0 = BABYLON.Vector3.Zero();
  27521. this._t1 = BABYLON.Vector3.Zero();
  27522. this._t2 = BABYLON.Vector3.Zero();
  27523. }
  27524. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27525. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27526. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27527. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27528. this._t1.subtractInPlace(this._t0);
  27529. this._t2.subtractInPlace(this._t0);
  27530. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27531. this._cachedTextureMatrix.m[0] = this._t1.x;
  27532. this._cachedTextureMatrix.m[1] = this._t1.y;
  27533. this._cachedTextureMatrix.m[2] = this._t1.z;
  27534. this._cachedTextureMatrix.m[4] = this._t2.x;
  27535. this._cachedTextureMatrix.m[5] = this._t2.y;
  27536. this._cachedTextureMatrix.m[6] = this._t2.z;
  27537. this._cachedTextureMatrix.m[8] = this._t0.x;
  27538. this._cachedTextureMatrix.m[9] = this._t0.y;
  27539. this._cachedTextureMatrix.m[10] = this._t0.z;
  27540. var scene = this.getScene();
  27541. if (!scene) {
  27542. return this._cachedTextureMatrix;
  27543. }
  27544. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27545. return mat.hasTexture(_this);
  27546. });
  27547. return this._cachedTextureMatrix;
  27548. };
  27549. Texture.prototype.getReflectionTextureMatrix = function () {
  27550. var _this = this;
  27551. var scene = this.getScene();
  27552. if (!scene) {
  27553. return this._cachedTextureMatrix;
  27554. }
  27555. if (this.uOffset === this._cachedUOffset &&
  27556. this.vOffset === this._cachedVOffset &&
  27557. this.uScale === this._cachedUScale &&
  27558. this.vScale === this._cachedVScale &&
  27559. this.coordinatesMode === this._cachedCoordinatesMode) {
  27560. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27561. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27562. return this._cachedTextureMatrix;
  27563. }
  27564. }
  27565. else {
  27566. return this._cachedTextureMatrix;
  27567. }
  27568. }
  27569. if (!this._cachedTextureMatrix) {
  27570. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27571. }
  27572. if (!this._projectionModeMatrix) {
  27573. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27574. }
  27575. this._cachedUOffset = this.uOffset;
  27576. this._cachedVOffset = this.vOffset;
  27577. this._cachedUScale = this.uScale;
  27578. this._cachedVScale = this.vScale;
  27579. this._cachedCoordinatesMode = this.coordinatesMode;
  27580. switch (this.coordinatesMode) {
  27581. case Texture.PLANAR_MODE:
  27582. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27583. this._cachedTextureMatrix[0] = this.uScale;
  27584. this._cachedTextureMatrix[5] = this.vScale;
  27585. this._cachedTextureMatrix[12] = this.uOffset;
  27586. this._cachedTextureMatrix[13] = this.vOffset;
  27587. break;
  27588. case Texture.PROJECTION_MODE:
  27589. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27590. this._projectionModeMatrix.m[0] = 0.5;
  27591. this._projectionModeMatrix.m[5] = -0.5;
  27592. this._projectionModeMatrix.m[10] = 0.0;
  27593. this._projectionModeMatrix.m[12] = 0.5;
  27594. this._projectionModeMatrix.m[13] = 0.5;
  27595. this._projectionModeMatrix.m[14] = 1.0;
  27596. this._projectionModeMatrix.m[15] = 1.0;
  27597. var projectionMatrix = scene.getProjectionMatrix();
  27598. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27599. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27600. break;
  27601. default:
  27602. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27603. break;
  27604. }
  27605. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27606. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27607. });
  27608. return this._cachedTextureMatrix;
  27609. };
  27610. Texture.prototype.clone = function () {
  27611. var _this = this;
  27612. return BABYLON.SerializationHelper.Clone(function () {
  27613. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27614. }, this);
  27615. };
  27616. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27617. get: function () {
  27618. if (!this._onLoadObservable) {
  27619. this._onLoadObservable = new BABYLON.Observable();
  27620. }
  27621. return this._onLoadObservable;
  27622. },
  27623. enumerable: true,
  27624. configurable: true
  27625. });
  27626. Texture.prototype.serialize = function () {
  27627. var serializationObject = _super.prototype.serialize.call(this);
  27628. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27629. serializationObject.base64String = this._buffer;
  27630. serializationObject.name = serializationObject.name.replace("data:", "");
  27631. }
  27632. return serializationObject;
  27633. };
  27634. Texture.prototype.getClassName = function () {
  27635. return "Texture";
  27636. };
  27637. Texture.prototype.dispose = function () {
  27638. _super.prototype.dispose.call(this);
  27639. if (this.onLoadObservable) {
  27640. this.onLoadObservable.clear();
  27641. this._onLoadObservable = null;
  27642. }
  27643. this._delayedOnLoad = null;
  27644. this._delayedOnError = null;
  27645. };
  27646. // Statics
  27647. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27648. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27649. if (onLoad === void 0) { onLoad = null; }
  27650. if (onError === void 0) { onError = null; }
  27651. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27652. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27653. };
  27654. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27655. if (parsedTexture.customType) {
  27656. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27657. // Update Sampling Mode
  27658. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27659. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27660. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27661. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27662. }
  27663. }
  27664. return parsedCustomTexture;
  27665. }
  27666. if (parsedTexture.isCube) {
  27667. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27668. }
  27669. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27670. return null;
  27671. }
  27672. var texture = BABYLON.SerializationHelper.Parse(function () {
  27673. var generateMipMaps = true;
  27674. if (parsedTexture.noMipmap) {
  27675. generateMipMaps = false;
  27676. }
  27677. if (parsedTexture.mirrorPlane) {
  27678. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27679. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27680. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27681. return mirrorTexture;
  27682. }
  27683. else if (parsedTexture.isRenderTarget) {
  27684. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27685. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27686. return renderTargetTexture;
  27687. }
  27688. else {
  27689. var texture;
  27690. if (parsedTexture.base64String) {
  27691. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27692. }
  27693. else {
  27694. var url = rootUrl + parsedTexture.name;
  27695. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27696. url = parsedTexture.url;
  27697. }
  27698. texture = new Texture(url, scene, !generateMipMaps);
  27699. }
  27700. return texture;
  27701. }
  27702. }, parsedTexture, scene);
  27703. // Update Sampling Mode
  27704. if (parsedTexture.samplingMode) {
  27705. var sampling = parsedTexture.samplingMode;
  27706. if (texture._samplingMode !== sampling) {
  27707. texture.updateSamplingMode(sampling);
  27708. }
  27709. }
  27710. // Animations
  27711. if (parsedTexture.animations) {
  27712. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27713. var parsedAnimation = parsedTexture.animations[animationIndex];
  27714. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27715. }
  27716. }
  27717. return texture;
  27718. };
  27719. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27720. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27721. if (noMipmap === void 0) { noMipmap = false; }
  27722. if (invertY === void 0) { invertY = true; }
  27723. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27724. if (onLoad === void 0) { onLoad = null; }
  27725. if (onError === void 0) { onError = null; }
  27726. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27727. if (name.substr(0, 5) !== "data:") {
  27728. name = "data:" + name;
  27729. }
  27730. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27731. };
  27732. // Constants
  27733. Texture.NEAREST_SAMPLINGMODE = 1;
  27734. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27735. Texture.BILINEAR_SAMPLINGMODE = 2;
  27736. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27737. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27738. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27739. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27740. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27741. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27742. Texture.NEAREST_LINEAR = 7;
  27743. Texture.NEAREST_NEAREST = 8;
  27744. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27745. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27746. Texture.LINEAR_LINEAR = 11;
  27747. Texture.LINEAR_NEAREST = 12;
  27748. Texture.EXPLICIT_MODE = 0;
  27749. Texture.SPHERICAL_MODE = 1;
  27750. Texture.PLANAR_MODE = 2;
  27751. Texture.CUBIC_MODE = 3;
  27752. Texture.PROJECTION_MODE = 4;
  27753. Texture.SKYBOX_MODE = 5;
  27754. Texture.INVCUBIC_MODE = 6;
  27755. Texture.EQUIRECTANGULAR_MODE = 7;
  27756. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27757. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27758. Texture.CLAMP_ADDRESSMODE = 0;
  27759. Texture.WRAP_ADDRESSMODE = 1;
  27760. Texture.MIRROR_ADDRESSMODE = 2;
  27761. /**
  27762. * 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
  27763. */
  27764. Texture.UseSerializedUrlIfAny = false;
  27765. __decorate([
  27766. BABYLON.serialize()
  27767. ], Texture.prototype, "url", void 0);
  27768. __decorate([
  27769. BABYLON.serialize()
  27770. ], Texture.prototype, "uOffset", void 0);
  27771. __decorate([
  27772. BABYLON.serialize()
  27773. ], Texture.prototype, "vOffset", void 0);
  27774. __decorate([
  27775. BABYLON.serialize()
  27776. ], Texture.prototype, "uScale", void 0);
  27777. __decorate([
  27778. BABYLON.serialize()
  27779. ], Texture.prototype, "vScale", void 0);
  27780. __decorate([
  27781. BABYLON.serialize()
  27782. ], Texture.prototype, "uAng", void 0);
  27783. __decorate([
  27784. BABYLON.serialize()
  27785. ], Texture.prototype, "vAng", void 0);
  27786. __decorate([
  27787. BABYLON.serialize()
  27788. ], Texture.prototype, "wAng", void 0);
  27789. __decorate([
  27790. BABYLON.serialize()
  27791. ], Texture.prototype, "isBlocking", null);
  27792. return Texture;
  27793. }(BABYLON.BaseTexture));
  27794. BABYLON.Texture = Texture;
  27795. })(BABYLON || (BABYLON = {}));
  27796. //# sourceMappingURL=babylon.texture.js.map
  27797. "use strict";
  27798. var BABYLON;
  27799. (function (BABYLON) {
  27800. var _InstancesBatch = /** @class */ (function () {
  27801. function _InstancesBatch() {
  27802. this.mustReturn = false;
  27803. this.visibleInstances = new Array();
  27804. this.renderSelf = new Array();
  27805. }
  27806. return _InstancesBatch;
  27807. }());
  27808. BABYLON._InstancesBatch = _InstancesBatch;
  27809. var Mesh = /** @class */ (function (_super) {
  27810. __extends(Mesh, _super);
  27811. /**
  27812. * @constructor
  27813. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27814. * @param {Scene} scene The scene to add this mesh to.
  27815. * @param {Node} parent The parent of this mesh, if it has one
  27816. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27817. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27818. * When false, achieved by calling a clone(), also passing False.
  27819. * This will make creation of children, recursive.
  27820. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27821. */
  27822. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27823. if (scene === void 0) { scene = null; }
  27824. if (parent === void 0) { parent = null; }
  27825. if (source === void 0) { source = null; }
  27826. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27827. var _this = _super.call(this, name, scene) || this;
  27828. // Events
  27829. /**
  27830. * An event triggered before rendering the mesh
  27831. * @type {BABYLON.Observable}
  27832. */
  27833. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27834. /**
  27835. * An event triggered after rendering the mesh
  27836. * @type {BABYLON.Observable}
  27837. */
  27838. _this.onAfterRenderObservable = new BABYLON.Observable();
  27839. /**
  27840. * An event triggered before drawing the mesh
  27841. * @type {BABYLON.Observable}
  27842. */
  27843. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27844. // Members
  27845. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27846. _this.instances = new Array();
  27847. _this._LODLevels = new Array();
  27848. _this._visibleInstances = {};
  27849. _this._renderIdForInstances = new Array();
  27850. _this._batchCache = new _InstancesBatch();
  27851. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27852. // Use by builder only to know what orientation were the mesh build in.
  27853. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27854. _this.overrideMaterialSideOrientation = null;
  27855. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27856. // Will be used to save a source mesh reference, If any
  27857. _this._source = null;
  27858. scene = _this.getScene();
  27859. if (source) {
  27860. // Source mesh
  27861. _this._source = source;
  27862. // Geometry
  27863. if (source._geometry) {
  27864. source._geometry.applyToMesh(_this);
  27865. }
  27866. // Deep copy
  27867. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27868. // Metadata
  27869. if (source.metadata && source.metadata.clone) {
  27870. _this.metadata = source.metadata.clone();
  27871. }
  27872. else {
  27873. _this.metadata = source.metadata;
  27874. }
  27875. // Tags
  27876. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27877. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27878. }
  27879. // Parent
  27880. _this.parent = source.parent;
  27881. // Pivot
  27882. _this.setPivotMatrix(source.getPivotMatrix());
  27883. _this.id = name + "." + source.id;
  27884. // Material
  27885. _this.material = source.material;
  27886. var index;
  27887. if (!doNotCloneChildren) {
  27888. // Children
  27889. var directDescendants = source.getDescendants(true);
  27890. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27891. var child = directDescendants[index_1];
  27892. if (child.clone) {
  27893. child.clone(name + "." + child.name, _this);
  27894. }
  27895. }
  27896. }
  27897. // Physics clone
  27898. var physicsEngine = _this.getScene().getPhysicsEngine();
  27899. if (clonePhysicsImpostor && physicsEngine) {
  27900. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27901. if (impostor) {
  27902. _this.physicsImpostor = impostor.clone(_this);
  27903. }
  27904. }
  27905. // Particles
  27906. for (index = 0; index < scene.particleSystems.length; index++) {
  27907. var system = scene.particleSystems[index];
  27908. if (system.emitter === source) {
  27909. system.clone(system.name, _this);
  27910. }
  27911. }
  27912. _this.computeWorldMatrix(true);
  27913. }
  27914. // Parent
  27915. if (parent !== null) {
  27916. _this.parent = parent;
  27917. }
  27918. return _this;
  27919. }
  27920. Object.defineProperty(Mesh, "FRONTSIDE", {
  27921. /**
  27922. * Mesh side orientation : usually the external or front surface
  27923. */
  27924. get: function () {
  27925. return Mesh._FRONTSIDE;
  27926. },
  27927. enumerable: true,
  27928. configurable: true
  27929. });
  27930. Object.defineProperty(Mesh, "BACKSIDE", {
  27931. /**
  27932. * Mesh side orientation : usually the internal or back surface
  27933. */
  27934. get: function () {
  27935. return Mesh._BACKSIDE;
  27936. },
  27937. enumerable: true,
  27938. configurable: true
  27939. });
  27940. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27941. /**
  27942. * Mesh side orientation : both internal and external or front and back surfaces
  27943. */
  27944. get: function () {
  27945. return Mesh._DOUBLESIDE;
  27946. },
  27947. enumerable: true,
  27948. configurable: true
  27949. });
  27950. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27951. /**
  27952. * Mesh side orientation : by default, `FRONTSIDE`
  27953. */
  27954. get: function () {
  27955. return Mesh._DEFAULTSIDE;
  27956. },
  27957. enumerable: true,
  27958. configurable: true
  27959. });
  27960. Object.defineProperty(Mesh, "NO_CAP", {
  27961. /**
  27962. * Mesh cap setting : no cap
  27963. */
  27964. get: function () {
  27965. return Mesh._NO_CAP;
  27966. },
  27967. enumerable: true,
  27968. configurable: true
  27969. });
  27970. Object.defineProperty(Mesh, "CAP_START", {
  27971. /**
  27972. * Mesh cap setting : one cap at the beginning of the mesh
  27973. */
  27974. get: function () {
  27975. return Mesh._CAP_START;
  27976. },
  27977. enumerable: true,
  27978. configurable: true
  27979. });
  27980. Object.defineProperty(Mesh, "CAP_END", {
  27981. /**
  27982. * Mesh cap setting : one cap at the end of the mesh
  27983. */
  27984. get: function () {
  27985. return Mesh._CAP_END;
  27986. },
  27987. enumerable: true,
  27988. configurable: true
  27989. });
  27990. Object.defineProperty(Mesh, "CAP_ALL", {
  27991. /**
  27992. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27993. */
  27994. get: function () {
  27995. return Mesh._CAP_ALL;
  27996. },
  27997. enumerable: true,
  27998. configurable: true
  27999. });
  28000. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  28001. set: function (callback) {
  28002. if (this._onBeforeDrawObserver) {
  28003. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  28004. }
  28005. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  28006. },
  28007. enumerable: true,
  28008. configurable: true
  28009. });
  28010. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  28011. get: function () {
  28012. return this._morphTargetManager;
  28013. },
  28014. set: function (value) {
  28015. if (this._morphTargetManager === value) {
  28016. return;
  28017. }
  28018. this._morphTargetManager = value;
  28019. this._syncGeometryWithMorphTargetManager();
  28020. },
  28021. enumerable: true,
  28022. configurable: true
  28023. });
  28024. Object.defineProperty(Mesh.prototype, "source", {
  28025. get: function () {
  28026. return this._source;
  28027. },
  28028. enumerable: true,
  28029. configurable: true
  28030. });
  28031. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  28032. get: function () {
  28033. return this._unIndexed;
  28034. },
  28035. set: function (value) {
  28036. if (this._unIndexed !== value) {
  28037. this._unIndexed = value;
  28038. this._markSubMeshesAsAttributesDirty();
  28039. }
  28040. },
  28041. enumerable: true,
  28042. configurable: true
  28043. });
  28044. // Methods
  28045. /**
  28046. * Returns the string "Mesh".
  28047. */
  28048. Mesh.prototype.getClassName = function () {
  28049. return "Mesh";
  28050. };
  28051. /**
  28052. * Returns a string.
  28053. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28054. */
  28055. Mesh.prototype.toString = function (fullDetails) {
  28056. var ret = _super.prototype.toString.call(this, fullDetails);
  28057. ret += ", n vertices: " + this.getTotalVertices();
  28058. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  28059. if (this.animations) {
  28060. for (var i = 0; i < this.animations.length; i++) {
  28061. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  28062. }
  28063. }
  28064. if (fullDetails) {
  28065. if (this._geometry) {
  28066. var ib = this.getIndices();
  28067. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28068. if (vb && ib) {
  28069. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  28070. }
  28071. }
  28072. else {
  28073. ret += ", flat shading: UNKNOWN";
  28074. }
  28075. }
  28076. return ret;
  28077. };
  28078. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  28079. /**
  28080. * True if the mesh has some Levels Of Details (LOD).
  28081. * Returns a boolean.
  28082. */
  28083. get: function () {
  28084. return this._LODLevels.length > 0;
  28085. },
  28086. enumerable: true,
  28087. configurable: true
  28088. });
  28089. /**
  28090. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28091. * @returns an array of {BABYLON.MeshLODLevel}
  28092. */
  28093. Mesh.prototype.getLODLevels = function () {
  28094. return this._LODLevels;
  28095. };
  28096. Mesh.prototype._sortLODLevels = function () {
  28097. this._LODLevels.sort(function (a, b) {
  28098. if (a.distance < b.distance) {
  28099. return 1;
  28100. }
  28101. if (a.distance > b.distance) {
  28102. return -1;
  28103. }
  28104. return 0;
  28105. });
  28106. };
  28107. /**
  28108. * Add a mesh as LOD level triggered at the given distance.
  28109. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28110. * @param {number} distance The distance from the center of the object to show this level
  28111. * @param {Mesh} mesh The mesh to be added as LOD level
  28112. * @return {Mesh} This mesh (for chaining)
  28113. */
  28114. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28115. if (mesh && mesh._masterMesh) {
  28116. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28117. return this;
  28118. }
  28119. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28120. this._LODLevels.push(level);
  28121. if (mesh) {
  28122. mesh._masterMesh = this;
  28123. }
  28124. this._sortLODLevels();
  28125. return this;
  28126. };
  28127. /**
  28128. * Returns the LOD level mesh at the passed distance or null if not found.
  28129. * It is related to the method `addLODLevel(distance, mesh)`.
  28130. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28131. * Returns an object Mesh or `null`.
  28132. */
  28133. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28134. for (var index = 0; index < this._LODLevels.length; index++) {
  28135. var level = this._LODLevels[index];
  28136. if (level.distance === distance) {
  28137. return level.mesh;
  28138. }
  28139. }
  28140. return null;
  28141. };
  28142. /**
  28143. * Remove a mesh from the LOD array
  28144. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28145. * @param {Mesh} mesh The mesh to be removed.
  28146. * @return {Mesh} This mesh (for chaining)
  28147. */
  28148. Mesh.prototype.removeLODLevel = function (mesh) {
  28149. for (var index = 0; index < this._LODLevels.length; index++) {
  28150. if (this._LODLevels[index].mesh === mesh) {
  28151. this._LODLevels.splice(index, 1);
  28152. if (mesh) {
  28153. mesh._masterMesh = null;
  28154. }
  28155. }
  28156. }
  28157. this._sortLODLevels();
  28158. return this;
  28159. };
  28160. /**
  28161. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28162. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28163. */
  28164. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28165. if (!this._LODLevels || this._LODLevels.length === 0) {
  28166. return this;
  28167. }
  28168. var bSphere;
  28169. if (boundingSphere) {
  28170. bSphere = boundingSphere;
  28171. }
  28172. else {
  28173. var boundingInfo = this.getBoundingInfo();
  28174. bSphere = boundingInfo.boundingSphere;
  28175. }
  28176. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28177. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28178. if (this.onLODLevelSelection) {
  28179. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28180. }
  28181. return this;
  28182. }
  28183. for (var index = 0; index < this._LODLevels.length; index++) {
  28184. var level = this._LODLevels[index];
  28185. if (level.distance < distanceToCamera) {
  28186. if (level.mesh) {
  28187. level.mesh._preActivate();
  28188. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28189. }
  28190. if (this.onLODLevelSelection) {
  28191. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28192. }
  28193. return level.mesh;
  28194. }
  28195. }
  28196. if (this.onLODLevelSelection) {
  28197. this.onLODLevelSelection(distanceToCamera, this, this);
  28198. }
  28199. return this;
  28200. };
  28201. Object.defineProperty(Mesh.prototype, "geometry", {
  28202. /**
  28203. * Returns the mesh internal Geometry object.
  28204. */
  28205. get: function () {
  28206. return this._geometry;
  28207. },
  28208. enumerable: true,
  28209. configurable: true
  28210. });
  28211. /**
  28212. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28213. */
  28214. Mesh.prototype.getTotalVertices = function () {
  28215. if (this._geometry === null || this._geometry === undefined) {
  28216. return 0;
  28217. }
  28218. return this._geometry.getTotalVertices();
  28219. };
  28220. /**
  28221. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28222. * 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.
  28223. * You can force the copy with forceCopy === true
  28224. * Returns null if the mesh has no geometry or no vertex buffer.
  28225. * Possible `kind` values :
  28226. * - BABYLON.VertexBuffer.PositionKind
  28227. * - BABYLON.VertexBuffer.UVKind
  28228. * - BABYLON.VertexBuffer.UV2Kind
  28229. * - BABYLON.VertexBuffer.UV3Kind
  28230. * - BABYLON.VertexBuffer.UV4Kind
  28231. * - BABYLON.VertexBuffer.UV5Kind
  28232. * - BABYLON.VertexBuffer.UV6Kind
  28233. * - BABYLON.VertexBuffer.ColorKind
  28234. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28235. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28236. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28237. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28238. */
  28239. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28240. if (!this._geometry) {
  28241. return null;
  28242. }
  28243. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28244. };
  28245. /**
  28246. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28247. * Returns `null` if the mesh has no geometry.
  28248. * Possible `kind` values :
  28249. * - BABYLON.VertexBuffer.PositionKind
  28250. * - BABYLON.VertexBuffer.UVKind
  28251. * - BABYLON.VertexBuffer.UV2Kind
  28252. * - BABYLON.VertexBuffer.UV3Kind
  28253. * - BABYLON.VertexBuffer.UV4Kind
  28254. * - BABYLON.VertexBuffer.UV5Kind
  28255. * - BABYLON.VertexBuffer.UV6Kind
  28256. * - BABYLON.VertexBuffer.ColorKind
  28257. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28258. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28259. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28260. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28261. */
  28262. Mesh.prototype.getVertexBuffer = function (kind) {
  28263. if (!this._geometry) {
  28264. return null;
  28265. }
  28266. return this._geometry.getVertexBuffer(kind);
  28267. };
  28268. /**
  28269. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28270. * Possible `kind` values :
  28271. * - BABYLON.VertexBuffer.PositionKind
  28272. * - BABYLON.VertexBuffer.UVKind
  28273. * - BABYLON.VertexBuffer.UV2Kind
  28274. * - BABYLON.VertexBuffer.UV3Kind
  28275. * - BABYLON.VertexBuffer.UV4Kind
  28276. * - BABYLON.VertexBuffer.UV5Kind
  28277. * - BABYLON.VertexBuffer.UV6Kind
  28278. * - BABYLON.VertexBuffer.ColorKind
  28279. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28280. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28281. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28282. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28283. */
  28284. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28285. if (!this._geometry) {
  28286. if (this._delayInfo) {
  28287. return this._delayInfo.indexOf(kind) !== -1;
  28288. }
  28289. return false;
  28290. }
  28291. return this._geometry.isVerticesDataPresent(kind);
  28292. };
  28293. /**
  28294. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28295. * Possible `kind` values :
  28296. * - BABYLON.VertexBuffer.PositionKind
  28297. * - BABYLON.VertexBuffer.UVKind
  28298. * - BABYLON.VertexBuffer.UV2Kind
  28299. * - BABYLON.VertexBuffer.UV3Kind
  28300. * - BABYLON.VertexBuffer.UV4Kind
  28301. * - BABYLON.VertexBuffer.UV5Kind
  28302. * - BABYLON.VertexBuffer.UV6Kind
  28303. * - BABYLON.VertexBuffer.ColorKind
  28304. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28305. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28306. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28307. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28308. */
  28309. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28310. if (!this._geometry) {
  28311. if (this._delayInfo) {
  28312. return this._delayInfo.indexOf(kind) !== -1;
  28313. }
  28314. return false;
  28315. }
  28316. return this._geometry.isVertexBufferUpdatable(kind);
  28317. };
  28318. /**
  28319. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28320. * Possible `kind` values :
  28321. * - BABYLON.VertexBuffer.PositionKind
  28322. * - BABYLON.VertexBuffer.UVKind
  28323. * - BABYLON.VertexBuffer.UV2Kind
  28324. * - BABYLON.VertexBuffer.UV3Kind
  28325. * - BABYLON.VertexBuffer.UV4Kind
  28326. * - BABYLON.VertexBuffer.UV5Kind
  28327. * - BABYLON.VertexBuffer.UV6Kind
  28328. * - BABYLON.VertexBuffer.ColorKind
  28329. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28330. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28331. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28332. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28333. */
  28334. Mesh.prototype.getVerticesDataKinds = function () {
  28335. if (!this._geometry) {
  28336. var result = new Array();
  28337. if (this._delayInfo) {
  28338. this._delayInfo.forEach(function (kind, index, array) {
  28339. result.push(kind);
  28340. });
  28341. }
  28342. return result;
  28343. }
  28344. return this._geometry.getVerticesDataKinds();
  28345. };
  28346. /**
  28347. * Returns a positive integer : the total number of indices in this mesh geometry.
  28348. * Returns zero if the mesh has no geometry.
  28349. */
  28350. Mesh.prototype.getTotalIndices = function () {
  28351. if (!this._geometry) {
  28352. return 0;
  28353. }
  28354. return this._geometry.getTotalIndices();
  28355. };
  28356. /**
  28357. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28358. * 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.
  28359. * Returns an empty array if the mesh has no geometry.
  28360. */
  28361. Mesh.prototype.getIndices = function (copyWhenShared) {
  28362. if (!this._geometry) {
  28363. return [];
  28364. }
  28365. return this._geometry.getIndices(copyWhenShared);
  28366. };
  28367. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28368. get: function () {
  28369. return this._masterMesh !== null && this._masterMesh !== undefined;
  28370. },
  28371. enumerable: true,
  28372. configurable: true
  28373. });
  28374. /**
  28375. * Determine if the current mesh is ready to be rendered
  28376. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28377. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28378. * @returns true if all associated assets are ready (material, textures, shaders)
  28379. */
  28380. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28381. if (completeCheck === void 0) { completeCheck = false; }
  28382. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28383. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28384. return false;
  28385. }
  28386. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28387. return false;
  28388. }
  28389. if (!this.subMeshes || this.subMeshes.length === 0) {
  28390. return true;
  28391. }
  28392. if (!completeCheck) {
  28393. return true;
  28394. }
  28395. var engine = this.getEngine();
  28396. var scene = this.getScene();
  28397. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28398. this.computeWorldMatrix();
  28399. var mat = this.material || scene.defaultMaterial;
  28400. if (mat) {
  28401. if (mat.storeEffectOnSubMeshes) {
  28402. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28403. var subMesh = _a[_i];
  28404. var effectiveMaterial = subMesh.getMaterial();
  28405. if (effectiveMaterial) {
  28406. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28407. return false;
  28408. }
  28409. }
  28410. }
  28411. }
  28412. else {
  28413. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28414. return false;
  28415. }
  28416. }
  28417. }
  28418. // Shadows
  28419. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28420. var light = _c[_b];
  28421. var generator = light.getShadowGenerator();
  28422. if (generator) {
  28423. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28424. var subMesh = _e[_d];
  28425. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28426. return false;
  28427. }
  28428. }
  28429. }
  28430. }
  28431. // LOD
  28432. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28433. var lod = _g[_f];
  28434. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28435. return false;
  28436. }
  28437. }
  28438. return true;
  28439. };
  28440. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28441. /**
  28442. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28443. * This property is pertinent only for updatable parametric shapes.
  28444. */
  28445. get: function () {
  28446. return this._areNormalsFrozen;
  28447. },
  28448. enumerable: true,
  28449. configurable: true
  28450. });
  28451. /**
  28452. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28453. * It has no effect at all on other shapes.
  28454. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28455. * Returns the Mesh.
  28456. */
  28457. Mesh.prototype.freezeNormals = function () {
  28458. this._areNormalsFrozen = true;
  28459. return this;
  28460. };
  28461. /**
  28462. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28463. * It has no effect at all on other shapes.
  28464. * It reactivates the mesh normals computation if it was previously frozen.
  28465. * Returns the Mesh.
  28466. */
  28467. Mesh.prototype.unfreezeNormals = function () {
  28468. this._areNormalsFrozen = false;
  28469. return this;
  28470. };
  28471. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28472. /**
  28473. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28474. */
  28475. set: function (count) {
  28476. this._overridenInstanceCount = count;
  28477. },
  28478. enumerable: true,
  28479. configurable: true
  28480. });
  28481. // Methods
  28482. Mesh.prototype._preActivate = function () {
  28483. var sceneRenderId = this.getScene().getRenderId();
  28484. if (this._preActivateId === sceneRenderId) {
  28485. return this;
  28486. }
  28487. this._preActivateId = sceneRenderId;
  28488. this._visibleInstances = null;
  28489. return this;
  28490. };
  28491. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28492. if (this._visibleInstances) {
  28493. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28494. }
  28495. return this;
  28496. };
  28497. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28498. if (!this._visibleInstances) {
  28499. this._visibleInstances = {};
  28500. this._visibleInstances.defaultRenderId = renderId;
  28501. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28502. }
  28503. if (!this._visibleInstances[renderId]) {
  28504. this._visibleInstances[renderId] = new Array();
  28505. }
  28506. this._visibleInstances[renderId].push(instance);
  28507. return this;
  28508. };
  28509. /**
  28510. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28511. * This means the mesh underlying bounding box and sphere are recomputed.
  28512. * Returns the Mesh.
  28513. */
  28514. Mesh.prototype.refreshBoundingInfo = function () {
  28515. return this._refreshBoundingInfo(false);
  28516. };
  28517. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28518. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28519. return this;
  28520. }
  28521. var data = this._getPositionData(applySkeleton);
  28522. if (data) {
  28523. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28524. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28525. }
  28526. if (this.subMeshes) {
  28527. for (var index = 0; index < this.subMeshes.length; index++) {
  28528. this.subMeshes[index].refreshBoundingInfo();
  28529. }
  28530. }
  28531. this._updateBoundingInfo();
  28532. return this;
  28533. };
  28534. Mesh.prototype._getPositionData = function (applySkeleton) {
  28535. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28536. if (data && applySkeleton && this.skeleton) {
  28537. data = BABYLON.Tools.Slice(data);
  28538. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28539. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28540. if (matricesWeightsData && matricesIndicesData) {
  28541. var needExtras = this.numBoneInfluencers > 4;
  28542. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28543. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28544. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28545. var tempVector = BABYLON.Tmp.Vector3[0];
  28546. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28547. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28548. var matWeightIdx = 0;
  28549. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28550. finalMatrix.reset();
  28551. var inf;
  28552. var weight;
  28553. for (inf = 0; inf < 4; inf++) {
  28554. weight = matricesWeightsData[matWeightIdx + inf];
  28555. if (weight <= 0)
  28556. break;
  28557. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28558. finalMatrix.addToSelf(tempMatrix);
  28559. }
  28560. if (needExtras) {
  28561. for (inf = 0; inf < 4; inf++) {
  28562. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28563. if (weight <= 0)
  28564. break;
  28565. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28566. finalMatrix.addToSelf(tempMatrix);
  28567. }
  28568. }
  28569. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28570. tempVector.toArray(data, index);
  28571. }
  28572. }
  28573. }
  28574. return data;
  28575. };
  28576. Mesh.prototype._createGlobalSubMesh = function (force) {
  28577. var totalVertices = this.getTotalVertices();
  28578. if (!totalVertices || !this.getIndices()) {
  28579. return null;
  28580. }
  28581. // Check if we need to recreate the submeshes
  28582. if (this.subMeshes && this.subMeshes.length > 0) {
  28583. var ib = this.getIndices();
  28584. if (!ib) {
  28585. return null;
  28586. }
  28587. var totalIndices = ib.length;
  28588. var needToRecreate = false;
  28589. if (force) {
  28590. needToRecreate = true;
  28591. }
  28592. else {
  28593. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28594. var submesh = _a[_i];
  28595. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28596. needToRecreate = true;
  28597. break;
  28598. }
  28599. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28600. needToRecreate = true;
  28601. break;
  28602. }
  28603. }
  28604. }
  28605. if (!needToRecreate) {
  28606. return this.subMeshes[0];
  28607. }
  28608. }
  28609. this.releaseSubMeshes();
  28610. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28611. };
  28612. Mesh.prototype.subdivide = function (count) {
  28613. if (count < 1) {
  28614. return;
  28615. }
  28616. var totalIndices = this.getTotalIndices();
  28617. var subdivisionSize = (totalIndices / count) | 0;
  28618. var offset = 0;
  28619. // Ensure that subdivisionSize is a multiple of 3
  28620. while (subdivisionSize % 3 !== 0) {
  28621. subdivisionSize++;
  28622. }
  28623. this.releaseSubMeshes();
  28624. for (var index = 0; index < count; index++) {
  28625. if (offset >= totalIndices) {
  28626. break;
  28627. }
  28628. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28629. offset += subdivisionSize;
  28630. }
  28631. this.synchronizeInstances();
  28632. };
  28633. /**
  28634. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28635. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28636. * The `data` are either a numeric array either a Float32Array.
  28637. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28638. * 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).
  28639. * Note that a new underlying VertexBuffer object is created each call.
  28640. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28641. *
  28642. * Possible `kind` values :
  28643. * - BABYLON.VertexBuffer.PositionKind
  28644. * - BABYLON.VertexBuffer.UVKind
  28645. * - BABYLON.VertexBuffer.UV2Kind
  28646. * - BABYLON.VertexBuffer.UV3Kind
  28647. * - BABYLON.VertexBuffer.UV4Kind
  28648. * - BABYLON.VertexBuffer.UV5Kind
  28649. * - BABYLON.VertexBuffer.UV6Kind
  28650. * - BABYLON.VertexBuffer.ColorKind
  28651. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28652. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28653. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28654. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28655. *
  28656. * Returns the Mesh.
  28657. */
  28658. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28659. if (updatable === void 0) { updatable = false; }
  28660. if (!this._geometry) {
  28661. var vertexData = new BABYLON.VertexData();
  28662. vertexData.set(data, kind);
  28663. var scene = this.getScene();
  28664. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28665. }
  28666. else {
  28667. this._geometry.setVerticesData(kind, data, updatable, stride);
  28668. }
  28669. return this;
  28670. };
  28671. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28672. if (updatable === void 0) { updatable = true; }
  28673. var vb = this.getVertexBuffer(kind);
  28674. if (!vb || vb.isUpdatable() === updatable) {
  28675. return;
  28676. }
  28677. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28678. };
  28679. /**
  28680. * Sets the mesh VertexBuffer.
  28681. * Returns the Mesh.
  28682. */
  28683. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28684. if (!this._geometry) {
  28685. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28686. }
  28687. this._geometry.setVerticesBuffer(buffer);
  28688. return this;
  28689. };
  28690. /**
  28691. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28692. * If the mesh has no geometry, it is simply returned as it is.
  28693. * The `data` are either a numeric array either a Float32Array.
  28694. * No new underlying VertexBuffer object is created.
  28695. * 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.
  28696. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28697. *
  28698. * Possible `kind` values :
  28699. * - BABYLON.VertexBuffer.PositionKind
  28700. * - BABYLON.VertexBuffer.UVKind
  28701. * - BABYLON.VertexBuffer.UV2Kind
  28702. * - BABYLON.VertexBuffer.UV3Kind
  28703. * - BABYLON.VertexBuffer.UV4Kind
  28704. * - BABYLON.VertexBuffer.UV5Kind
  28705. * - BABYLON.VertexBuffer.UV6Kind
  28706. * - BABYLON.VertexBuffer.ColorKind
  28707. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28708. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28709. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28710. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28711. *
  28712. * Returns the Mesh.
  28713. */
  28714. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28715. if (!this._geometry) {
  28716. return this;
  28717. }
  28718. if (!makeItUnique) {
  28719. this._geometry.updateVerticesData(kind, data, updateExtends);
  28720. }
  28721. else {
  28722. this.makeGeometryUnique();
  28723. this.updateVerticesData(kind, data, updateExtends, false);
  28724. }
  28725. return this;
  28726. };
  28727. /**
  28728. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28729. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28730. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28731. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28732. * Returns the Mesh.
  28733. */
  28734. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28735. if (computeNormals === void 0) { computeNormals = true; }
  28736. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28737. if (!positions) {
  28738. return this;
  28739. }
  28740. positionFunction(positions);
  28741. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28742. if (computeNormals) {
  28743. var indices = this.getIndices();
  28744. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28745. if (!normals) {
  28746. return this;
  28747. }
  28748. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28749. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28750. }
  28751. return this;
  28752. };
  28753. /**
  28754. * Creates a un-shared specific occurence of the geometry for the mesh.
  28755. * Returns the Mesh.
  28756. */
  28757. Mesh.prototype.makeGeometryUnique = function () {
  28758. if (!this._geometry) {
  28759. return this;
  28760. }
  28761. var oldGeometry = this._geometry;
  28762. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28763. oldGeometry.releaseForMesh(this, true);
  28764. geometry.applyToMesh(this);
  28765. return this;
  28766. };
  28767. /**
  28768. * Sets the mesh indices.
  28769. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28770. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28771. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28772. * This method creates a new index buffer each call.
  28773. * Returns the Mesh.
  28774. */
  28775. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28776. if (totalVertices === void 0) { totalVertices = null; }
  28777. if (updatable === void 0) { updatable = false; }
  28778. if (!this._geometry) {
  28779. var vertexData = new BABYLON.VertexData();
  28780. vertexData.indices = indices;
  28781. var scene = this.getScene();
  28782. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28783. }
  28784. else {
  28785. this._geometry.setIndices(indices, totalVertices, updatable);
  28786. }
  28787. return this;
  28788. };
  28789. /**
  28790. * Update the current index buffer
  28791. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28792. * Returns the Mesh.
  28793. */
  28794. Mesh.prototype.updateIndices = function (indices, offset) {
  28795. if (!this._geometry) {
  28796. return this;
  28797. }
  28798. this._geometry.updateIndices(indices, offset);
  28799. return this;
  28800. };
  28801. /**
  28802. * Invert the geometry to move from a right handed system to a left handed one.
  28803. * Returns the Mesh.
  28804. */
  28805. Mesh.prototype.toLeftHanded = function () {
  28806. if (!this._geometry) {
  28807. return this;
  28808. }
  28809. this._geometry.toLeftHanded();
  28810. return this;
  28811. };
  28812. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28813. if (!this._geometry) {
  28814. return this;
  28815. }
  28816. var engine = this.getScene().getEngine();
  28817. // Wireframe
  28818. var indexToBind;
  28819. if (this._unIndexed) {
  28820. indexToBind = null;
  28821. }
  28822. else {
  28823. switch (fillMode) {
  28824. case BABYLON.Material.PointFillMode:
  28825. indexToBind = null;
  28826. break;
  28827. case BABYLON.Material.WireFrameFillMode:
  28828. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28829. break;
  28830. default:
  28831. case BABYLON.Material.TriangleFillMode:
  28832. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28833. break;
  28834. }
  28835. }
  28836. // VBOs
  28837. this._geometry._bind(effect, indexToBind);
  28838. return this;
  28839. };
  28840. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28841. if (alternate === void 0) { alternate = false; }
  28842. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28843. return this;
  28844. }
  28845. this.onBeforeDrawObservable.notifyObservers(this);
  28846. var scene = this.getScene();
  28847. var engine = scene.getEngine();
  28848. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28849. // or triangles as points
  28850. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28851. }
  28852. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28853. // Triangles as wireframe
  28854. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28855. }
  28856. else {
  28857. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28858. }
  28859. if (scene._isAlternateRenderingEnabled && !alternate) {
  28860. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28861. if (!effect || !scene.activeCamera) {
  28862. return this;
  28863. }
  28864. scene._switchToAlternateCameraConfiguration(true);
  28865. this._effectiveMaterial.bindView(effect);
  28866. this._effectiveMaterial.bindViewProjection(effect);
  28867. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28868. this._draw(subMesh, fillMode, instancesCount, true);
  28869. engine.setViewport(scene.activeCamera.viewport);
  28870. scene._switchToAlternateCameraConfiguration(false);
  28871. this._effectiveMaterial.bindView(effect);
  28872. this._effectiveMaterial.bindViewProjection(effect);
  28873. }
  28874. return this;
  28875. };
  28876. /**
  28877. * Registers for this mesh a javascript function called just before the rendering process.
  28878. * This function is passed the current mesh.
  28879. * Return the Mesh.
  28880. */
  28881. Mesh.prototype.registerBeforeRender = function (func) {
  28882. this.onBeforeRenderObservable.add(func);
  28883. return this;
  28884. };
  28885. /**
  28886. * Disposes a previously registered javascript function called before the rendering.
  28887. * This function is passed the current mesh.
  28888. * Returns the Mesh.
  28889. */
  28890. Mesh.prototype.unregisterBeforeRender = function (func) {
  28891. this.onBeforeRenderObservable.removeCallback(func);
  28892. return this;
  28893. };
  28894. /**
  28895. * Registers for this mesh a javascript function called just after the rendering is complete.
  28896. * This function is passed the current mesh.
  28897. * Returns the Mesh.
  28898. */
  28899. Mesh.prototype.registerAfterRender = function (func) {
  28900. this.onAfterRenderObservable.add(func);
  28901. return this;
  28902. };
  28903. /**
  28904. * Disposes a previously registered javascript function called after the rendering.
  28905. * This function is passed the current mesh.
  28906. * Return the Mesh.
  28907. */
  28908. Mesh.prototype.unregisterAfterRender = function (func) {
  28909. this.onAfterRenderObservable.removeCallback(func);
  28910. return this;
  28911. };
  28912. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28913. var scene = this.getScene();
  28914. this._batchCache.mustReturn = false;
  28915. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28916. this._batchCache.visibleInstances[subMeshId] = null;
  28917. if (this._visibleInstances) {
  28918. var currentRenderId = scene.getRenderId();
  28919. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28920. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28921. var selfRenderId = this._renderId;
  28922. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28923. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28924. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28925. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28926. }
  28927. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28928. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28929. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28930. this._batchCache.mustReturn = true;
  28931. return this._batchCache;
  28932. }
  28933. if (currentRenderId !== selfRenderId) {
  28934. this._batchCache.renderSelf[subMeshId] = false;
  28935. }
  28936. }
  28937. this._renderIdForInstances[subMeshId] = currentRenderId;
  28938. }
  28939. return this._batchCache;
  28940. };
  28941. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28942. var visibleInstances = batch.visibleInstances[subMesh._id];
  28943. if (!visibleInstances) {
  28944. return this;
  28945. }
  28946. var matricesCount = visibleInstances.length + 1;
  28947. var bufferSize = matricesCount * 16 * 4;
  28948. var currentInstancesBufferSize = this._instancesBufferSize;
  28949. var instancesBuffer = this._instancesBuffer;
  28950. while (this._instancesBufferSize < bufferSize) {
  28951. this._instancesBufferSize *= 2;
  28952. }
  28953. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28954. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28955. }
  28956. var offset = 0;
  28957. var instancesCount = 0;
  28958. var world = this.getWorldMatrix();
  28959. if (batch.renderSelf[subMesh._id]) {
  28960. world.copyToArray(this._instancesData, offset);
  28961. offset += 16;
  28962. instancesCount++;
  28963. }
  28964. if (visibleInstances) {
  28965. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28966. var instance = visibleInstances[instanceIndex];
  28967. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28968. offset += 16;
  28969. instancesCount++;
  28970. }
  28971. }
  28972. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28973. if (instancesBuffer) {
  28974. instancesBuffer.dispose();
  28975. }
  28976. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28977. this._instancesBuffer = instancesBuffer;
  28978. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28979. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28980. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28981. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28982. }
  28983. else {
  28984. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28985. }
  28986. this._bind(subMesh, effect, fillMode);
  28987. this._draw(subMesh, fillMode, instancesCount);
  28988. engine.unbindInstanceAttributes();
  28989. return this;
  28990. };
  28991. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28992. var scene = this.getScene();
  28993. var engine = scene.getEngine();
  28994. if (hardwareInstancedRendering) {
  28995. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28996. }
  28997. else {
  28998. if (batch.renderSelf[subMesh._id]) {
  28999. // Draw
  29000. if (onBeforeDraw) {
  29001. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  29002. }
  29003. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  29004. }
  29005. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  29006. if (visibleInstancesForSubMesh) {
  29007. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  29008. var instance = visibleInstancesForSubMesh[instanceIndex];
  29009. // World
  29010. var world = instance.getWorldMatrix();
  29011. if (onBeforeDraw) {
  29012. onBeforeDraw(true, world, effectiveMaterial);
  29013. }
  29014. // Draw
  29015. this._draw(subMesh, fillMode);
  29016. }
  29017. }
  29018. }
  29019. return this;
  29020. };
  29021. /**
  29022. * Triggers the draw call for the mesh.
  29023. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  29024. * Returns the Mesh.
  29025. */
  29026. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  29027. this.checkOcclusionQuery();
  29028. if (this._isOccluded) {
  29029. return this;
  29030. }
  29031. var scene = this.getScene();
  29032. // Managing instances
  29033. var batch = this._getInstancesRenderList(subMesh._id);
  29034. if (batch.mustReturn) {
  29035. return this;
  29036. }
  29037. // Checking geometry state
  29038. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29039. return this;
  29040. }
  29041. this.onBeforeRenderObservable.notifyObservers(this);
  29042. var engine = scene.getEngine();
  29043. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29044. // Material
  29045. var material = subMesh.getMaterial();
  29046. if (!material) {
  29047. return this;
  29048. }
  29049. this._effectiveMaterial = material;
  29050. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29051. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  29052. return this;
  29053. }
  29054. }
  29055. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  29056. return this;
  29057. }
  29058. // Alpha mode
  29059. if (enableAlphaMode) {
  29060. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  29061. }
  29062. // Outline - step 1
  29063. var savedDepthWrite = engine.getDepthWrite();
  29064. if (this.renderOutline) {
  29065. engine.setDepthWrite(false);
  29066. scene.getOutlineRenderer().render(subMesh, batch);
  29067. engine.setDepthWrite(savedDepthWrite);
  29068. }
  29069. var effect;
  29070. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29071. effect = subMesh.effect;
  29072. }
  29073. else {
  29074. effect = this._effectiveMaterial.getEffect();
  29075. }
  29076. if (!effect) {
  29077. return this;
  29078. }
  29079. var sideOrientation = this.overrideMaterialSideOrientation;
  29080. if (sideOrientation == null) {
  29081. sideOrientation = this._effectiveMaterial.sideOrientation;
  29082. if (this._getWorldMatrixDeterminant() < 0) {
  29083. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29084. }
  29085. }
  29086. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29087. if (this._effectiveMaterial.forceDepthWrite) {
  29088. engine.setDepthWrite(true);
  29089. }
  29090. // Bind
  29091. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29092. if (!hardwareInstancedRendering) {
  29093. this._bind(subMesh, effect, fillMode);
  29094. }
  29095. var world = this.getWorldMatrix();
  29096. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29097. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29098. }
  29099. else {
  29100. this._effectiveMaterial.bind(world, this);
  29101. }
  29102. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29103. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29104. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29105. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29106. }
  29107. // Draw
  29108. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29109. // Unbind
  29110. this._effectiveMaterial.unbind();
  29111. // Outline - step 2
  29112. if (this.renderOutline && savedDepthWrite) {
  29113. engine.setDepthWrite(true);
  29114. engine.setColorWrite(false);
  29115. scene.getOutlineRenderer().render(subMesh, batch);
  29116. engine.setColorWrite(true);
  29117. }
  29118. // Overlay
  29119. if (this.renderOverlay) {
  29120. var currentMode = engine.getAlphaMode();
  29121. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29122. scene.getOutlineRenderer().render(subMesh, batch, true);
  29123. engine.setAlphaMode(currentMode);
  29124. }
  29125. this.onAfterRenderObservable.notifyObservers(this);
  29126. return this;
  29127. };
  29128. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29129. if (isInstance && effectiveMaterial) {
  29130. effectiveMaterial.bindOnlyWorldMatrix(world);
  29131. }
  29132. };
  29133. /**
  29134. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29135. */
  29136. Mesh.prototype.getEmittedParticleSystems = function () {
  29137. var results = new Array();
  29138. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29139. var particleSystem = this.getScene().particleSystems[index];
  29140. if (particleSystem.emitter === this) {
  29141. results.push(particleSystem);
  29142. }
  29143. }
  29144. return results;
  29145. };
  29146. /**
  29147. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29148. */
  29149. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29150. var results = new Array();
  29151. var descendants = this.getDescendants();
  29152. descendants.push(this);
  29153. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29154. var particleSystem = this.getScene().particleSystems[index];
  29155. var emitter = particleSystem.emitter;
  29156. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29157. results.push(particleSystem);
  29158. }
  29159. }
  29160. return results;
  29161. };
  29162. Mesh.prototype._checkDelayState = function () {
  29163. var scene = this.getScene();
  29164. if (this._geometry) {
  29165. this._geometry.load(scene);
  29166. }
  29167. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29168. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29169. this._queueLoad(scene);
  29170. }
  29171. return this;
  29172. };
  29173. Mesh.prototype._queueLoad = function (scene) {
  29174. var _this = this;
  29175. scene._addPendingData(this);
  29176. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29177. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29178. if (data instanceof ArrayBuffer) {
  29179. _this._delayLoadingFunction(data, _this);
  29180. }
  29181. else {
  29182. _this._delayLoadingFunction(JSON.parse(data), _this);
  29183. }
  29184. _this.instances.forEach(function (instance) {
  29185. instance._syncSubMeshes();
  29186. });
  29187. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29188. scene._removePendingData(_this);
  29189. }, function () { }, scene.database, getBinaryData);
  29190. return this;
  29191. };
  29192. /**
  29193. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29194. */
  29195. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29196. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29197. return false;
  29198. }
  29199. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29200. return false;
  29201. }
  29202. this._checkDelayState();
  29203. return true;
  29204. };
  29205. /**
  29206. * Sets the mesh material by the material or multiMaterial `id` property.
  29207. * The material `id` is a string identifying the material or the multiMaterial.
  29208. * This method returns the Mesh.
  29209. */
  29210. Mesh.prototype.setMaterialByID = function (id) {
  29211. var materials = this.getScene().materials;
  29212. var index;
  29213. for (index = materials.length - 1; index > -1; index--) {
  29214. if (materials[index].id === id) {
  29215. this.material = materials[index];
  29216. return this;
  29217. }
  29218. }
  29219. // Multi
  29220. var multiMaterials = this.getScene().multiMaterials;
  29221. for (index = multiMaterials.length - 1; index > -1; index--) {
  29222. if (multiMaterials[index].id === id) {
  29223. this.material = multiMaterials[index];
  29224. return this;
  29225. }
  29226. }
  29227. return this;
  29228. };
  29229. /**
  29230. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29231. */
  29232. Mesh.prototype.getAnimatables = function () {
  29233. var results = new Array();
  29234. if (this.material) {
  29235. results.push(this.material);
  29236. }
  29237. if (this.skeleton) {
  29238. results.push(this.skeleton);
  29239. }
  29240. return results;
  29241. };
  29242. /**
  29243. * Modifies the mesh geometry according to the passed transformation matrix.
  29244. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29245. * The mesh normals are modified accordingly the same transformation.
  29246. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29247. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29248. * Returns the Mesh.
  29249. */
  29250. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29251. // Position
  29252. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29253. return this;
  29254. }
  29255. var submeshes = this.subMeshes.splice(0);
  29256. this._resetPointsArrayCache();
  29257. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29258. var temp = new Array();
  29259. var index;
  29260. for (index = 0; index < data.length; index += 3) {
  29261. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29262. }
  29263. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29264. // Normals
  29265. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29266. return this;
  29267. }
  29268. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29269. temp = [];
  29270. for (index = 0; index < data.length; index += 3) {
  29271. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29272. }
  29273. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29274. // flip faces?
  29275. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29276. this.flipFaces();
  29277. }
  29278. // Restore submeshes
  29279. this.releaseSubMeshes();
  29280. this.subMeshes = submeshes;
  29281. return this;
  29282. };
  29283. /**
  29284. * Modifies the mesh geometry according to its own current World Matrix.
  29285. * The mesh World Matrix is then reset.
  29286. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29287. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29288. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29289. * Returns the Mesh.
  29290. */
  29291. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29292. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29293. this.scaling.copyFromFloats(1, 1, 1);
  29294. this.position.copyFromFloats(0, 0, 0);
  29295. this.rotation.copyFromFloats(0, 0, 0);
  29296. //only if quaternion is already set
  29297. if (this.rotationQuaternion) {
  29298. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29299. }
  29300. this._worldMatrix = BABYLON.Matrix.Identity();
  29301. return this;
  29302. };
  29303. Object.defineProperty(Mesh.prototype, "_positions", {
  29304. // Cache
  29305. get: function () {
  29306. if (this._geometry) {
  29307. return this._geometry._positions;
  29308. }
  29309. return null;
  29310. },
  29311. enumerable: true,
  29312. configurable: true
  29313. });
  29314. Mesh.prototype._resetPointsArrayCache = function () {
  29315. if (this._geometry) {
  29316. this._geometry._resetPointsArrayCache();
  29317. }
  29318. return this;
  29319. };
  29320. Mesh.prototype._generatePointsArray = function () {
  29321. if (this._geometry) {
  29322. return this._geometry._generatePointsArray();
  29323. }
  29324. return false;
  29325. };
  29326. /**
  29327. * Returns a new Mesh object generated from the current mesh properties.
  29328. * This method must not get confused with createInstance().
  29329. * The parameter `name` is a string, the name given to the new mesh.
  29330. * The optional parameter `newParent` can be any Node object (default `null`).
  29331. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29332. * 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.
  29333. */
  29334. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29335. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29336. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29337. };
  29338. /**
  29339. * Releases resources associated with this mesh.
  29340. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29341. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29342. */
  29343. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29344. var _this = this;
  29345. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29346. this.morphTargetManager = null;
  29347. if (this._geometry) {
  29348. this._geometry.releaseForMesh(this, true);
  29349. }
  29350. // Sources
  29351. var meshes = this.getScene().meshes;
  29352. meshes.forEach(function (abstractMesh) {
  29353. var mesh = abstractMesh;
  29354. if (mesh._source && mesh._source === _this) {
  29355. mesh._source = null;
  29356. }
  29357. });
  29358. this._source = null;
  29359. // Instances
  29360. if (this._instancesBuffer) {
  29361. this._instancesBuffer.dispose();
  29362. this._instancesBuffer = null;
  29363. }
  29364. while (this.instances.length) {
  29365. this.instances[0].dispose();
  29366. }
  29367. // Effect layers.
  29368. var effectLayers = this.getScene().effectLayers;
  29369. for (var i = 0; i < effectLayers.length; i++) {
  29370. var effectLayer = effectLayers[i];
  29371. if (effectLayer) {
  29372. effectLayer._disposeMesh(this);
  29373. }
  29374. }
  29375. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29376. };
  29377. /**
  29378. * Modifies the mesh geometry according to a displacement map.
  29379. * 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.
  29380. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29381. * This method returns nothing.
  29382. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29383. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29384. * 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.
  29385. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29386. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29387. *
  29388. * Returns the Mesh.
  29389. */
  29390. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29391. var _this = this;
  29392. var scene = this.getScene();
  29393. var onload = function (img) {
  29394. // Getting height map data
  29395. var canvas = document.createElement("canvas");
  29396. var context = canvas.getContext("2d");
  29397. var heightMapWidth = img.width;
  29398. var heightMapHeight = img.height;
  29399. canvas.width = heightMapWidth;
  29400. canvas.height = heightMapHeight;
  29401. context.drawImage(img, 0, 0);
  29402. // Create VertexData from map data
  29403. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29404. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29405. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29406. //execute success callback, if set
  29407. if (onSuccess) {
  29408. onSuccess(_this);
  29409. }
  29410. };
  29411. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29412. return this;
  29413. };
  29414. /**
  29415. * Modifies the mesh geometry according to a displacementMap buffer.
  29416. * 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.
  29417. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29418. * This method returns nothing.
  29419. * 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.
  29420. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29421. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29422. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29423. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29424. *
  29425. * Returns the Mesh.
  29426. */
  29427. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29428. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29429. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29430. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29431. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29432. return this;
  29433. }
  29434. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29435. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29436. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29437. var position = BABYLON.Vector3.Zero();
  29438. var normal = BABYLON.Vector3.Zero();
  29439. var uv = BABYLON.Vector2.Zero();
  29440. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29441. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29442. for (var index = 0; index < positions.length; index += 3) {
  29443. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29444. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29445. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29446. // Compute height
  29447. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29448. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29449. var pos = (u + v * heightMapWidth) * 4;
  29450. var r = buffer[pos] / 255.0;
  29451. var g = buffer[pos + 1] / 255.0;
  29452. var b = buffer[pos + 2] / 255.0;
  29453. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29454. normal.normalize();
  29455. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29456. position = position.add(normal);
  29457. position.toArray(positions, index);
  29458. }
  29459. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29460. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29461. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29462. return this;
  29463. };
  29464. /**
  29465. * Modify the mesh to get a flat shading rendering.
  29466. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29467. * This method returns the Mesh.
  29468. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29469. */
  29470. Mesh.prototype.convertToFlatShadedMesh = function () {
  29471. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29472. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29473. var kinds = this.getVerticesDataKinds();
  29474. var vbs = {};
  29475. var data = {};
  29476. var newdata = {};
  29477. var updatableNormals = false;
  29478. var kindIndex;
  29479. var kind;
  29480. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29481. kind = kinds[kindIndex];
  29482. var vertexBuffer = this.getVertexBuffer(kind);
  29483. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29484. updatableNormals = vertexBuffer.isUpdatable();
  29485. kinds.splice(kindIndex, 1);
  29486. kindIndex--;
  29487. continue;
  29488. }
  29489. vbs[kind] = vertexBuffer;
  29490. data[kind] = vbs[kind].getData();
  29491. newdata[kind] = [];
  29492. }
  29493. // Save previous submeshes
  29494. var previousSubmeshes = this.subMeshes.slice(0);
  29495. var indices = this.getIndices();
  29496. var totalIndices = this.getTotalIndices();
  29497. // Generating unique vertices per face
  29498. var index;
  29499. for (index = 0; index < totalIndices; index++) {
  29500. var vertexIndex = indices[index];
  29501. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29502. kind = kinds[kindIndex];
  29503. var stride = vbs[kind].getStrideSize();
  29504. for (var offset = 0; offset < stride; offset++) {
  29505. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29506. }
  29507. }
  29508. }
  29509. // Updating faces & normal
  29510. var normals = [];
  29511. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29512. for (index = 0; index < totalIndices; index += 3) {
  29513. indices[index] = index;
  29514. indices[index + 1] = index + 1;
  29515. indices[index + 2] = index + 2;
  29516. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29517. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29518. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29519. var p1p2 = p1.subtract(p2);
  29520. var p3p2 = p3.subtract(p2);
  29521. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29522. // Store same normals for every vertex
  29523. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29524. normals.push(normal.x);
  29525. normals.push(normal.y);
  29526. normals.push(normal.z);
  29527. }
  29528. }
  29529. this.setIndices(indices);
  29530. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29531. // Updating vertex buffers
  29532. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29533. kind = kinds[kindIndex];
  29534. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29535. }
  29536. // Updating submeshes
  29537. this.releaseSubMeshes();
  29538. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29539. var previousOne = previousSubmeshes[submeshIndex];
  29540. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29541. }
  29542. this.synchronizeInstances();
  29543. return this;
  29544. };
  29545. /**
  29546. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29547. * In other words, more vertices, no more indices and a single bigger VBO.
  29548. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29549. * Returns the Mesh.
  29550. */
  29551. Mesh.prototype.convertToUnIndexedMesh = function () {
  29552. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29553. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29554. var kinds = this.getVerticesDataKinds();
  29555. var vbs = {};
  29556. var data = {};
  29557. var newdata = {};
  29558. var kindIndex;
  29559. var kind;
  29560. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29561. kind = kinds[kindIndex];
  29562. var vertexBuffer = this.getVertexBuffer(kind);
  29563. vbs[kind] = vertexBuffer;
  29564. data[kind] = vbs[kind].getData();
  29565. newdata[kind] = [];
  29566. }
  29567. // Save previous submeshes
  29568. var previousSubmeshes = this.subMeshes.slice(0);
  29569. var indices = this.getIndices();
  29570. var totalIndices = this.getTotalIndices();
  29571. // Generating unique vertices per face
  29572. var index;
  29573. for (index = 0; index < totalIndices; index++) {
  29574. var vertexIndex = indices[index];
  29575. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29576. kind = kinds[kindIndex];
  29577. var stride = vbs[kind].getStrideSize();
  29578. for (var offset = 0; offset < stride; offset++) {
  29579. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29580. }
  29581. }
  29582. }
  29583. // Updating indices
  29584. for (index = 0; index < totalIndices; index += 3) {
  29585. indices[index] = index;
  29586. indices[index + 1] = index + 1;
  29587. indices[index + 2] = index + 2;
  29588. }
  29589. this.setIndices(indices);
  29590. // Updating vertex buffers
  29591. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29592. kind = kinds[kindIndex];
  29593. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29594. }
  29595. // Updating submeshes
  29596. this.releaseSubMeshes();
  29597. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29598. var previousOne = previousSubmeshes[submeshIndex];
  29599. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29600. }
  29601. this._unIndexed = true;
  29602. this.synchronizeInstances();
  29603. return this;
  29604. };
  29605. /**
  29606. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29607. * This method returns the Mesh.
  29608. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29609. */
  29610. Mesh.prototype.flipFaces = function (flipNormals) {
  29611. if (flipNormals === void 0) { flipNormals = false; }
  29612. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29613. var i;
  29614. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29615. for (i = 0; i < vertex_data.normals.length; i++) {
  29616. vertex_data.normals[i] *= -1;
  29617. }
  29618. }
  29619. if (vertex_data.indices) {
  29620. var temp;
  29621. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29622. // reassign indices
  29623. temp = vertex_data.indices[i + 1];
  29624. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29625. vertex_data.indices[i + 2] = temp;
  29626. }
  29627. }
  29628. vertex_data.applyToMesh(this);
  29629. return this;
  29630. };
  29631. // Instances
  29632. /**
  29633. * Creates a new InstancedMesh object from the mesh model.
  29634. * An instance shares the same properties and the same material than its model.
  29635. * Only these properties of each instance can then be set individually :
  29636. * - position
  29637. * - rotation
  29638. * - rotationQuaternion
  29639. * - setPivotMatrix
  29640. * - scaling
  29641. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29642. * Warning : this method is not supported for Line mesh and LineSystem
  29643. */
  29644. Mesh.prototype.createInstance = function (name) {
  29645. return new BABYLON.InstancedMesh(name, this);
  29646. };
  29647. /**
  29648. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29649. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29650. * This method returns the Mesh.
  29651. */
  29652. Mesh.prototype.synchronizeInstances = function () {
  29653. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29654. var instance = this.instances[instanceIndex];
  29655. instance._syncSubMeshes();
  29656. }
  29657. return this;
  29658. };
  29659. /**
  29660. * Simplify the mesh according to the given array of settings.
  29661. * Function will return immediately and will simplify async. It returns the Mesh.
  29662. * @param settings a collection of simplification settings.
  29663. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29664. * @param type the type of simplification to run.
  29665. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29666. */
  29667. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29668. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29669. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29670. this.getScene().simplificationQueue.addTask({
  29671. settings: settings,
  29672. parallelProcessing: parallelProcessing,
  29673. mesh: this,
  29674. simplificationType: simplificationType,
  29675. successCallback: successCallback
  29676. });
  29677. return this;
  29678. };
  29679. /**
  29680. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29681. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29682. * This should be used together with the simplification to avoid disappearing triangles.
  29683. * Returns the Mesh.
  29684. * @param successCallback an optional success callback to be called after the optimization finished.
  29685. */
  29686. Mesh.prototype.optimizeIndices = function (successCallback) {
  29687. var _this = this;
  29688. var indices = this.getIndices();
  29689. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29690. if (!positions || !indices) {
  29691. return this;
  29692. }
  29693. var vectorPositions = new Array();
  29694. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29695. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29696. }
  29697. var dupes = new Array();
  29698. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29699. var realPos = vectorPositions.length - 1 - iteration;
  29700. var testedPosition = vectorPositions[realPos];
  29701. for (var j = 0; j < realPos; ++j) {
  29702. var againstPosition = vectorPositions[j];
  29703. if (testedPosition.equals(againstPosition)) {
  29704. dupes[realPos] = j;
  29705. break;
  29706. }
  29707. }
  29708. }, function () {
  29709. for (var i = 0; i < indices.length; ++i) {
  29710. indices[i] = dupes[indices[i]] || indices[i];
  29711. }
  29712. //indices are now reordered
  29713. var originalSubMeshes = _this.subMeshes.slice(0);
  29714. _this.setIndices(indices);
  29715. _this.subMeshes = originalSubMeshes;
  29716. if (successCallback) {
  29717. successCallback(_this);
  29718. }
  29719. });
  29720. return this;
  29721. };
  29722. Mesh.prototype.serialize = function (serializationObject) {
  29723. serializationObject.name = this.name;
  29724. serializationObject.id = this.id;
  29725. serializationObject.type = this.getClassName();
  29726. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29727. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29728. }
  29729. serializationObject.position = this.position.asArray();
  29730. if (this.rotationQuaternion) {
  29731. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29732. }
  29733. else if (this.rotation) {
  29734. serializationObject.rotation = this.rotation.asArray();
  29735. }
  29736. serializationObject.scaling = this.scaling.asArray();
  29737. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29738. serializationObject.isEnabled = this.isEnabled(false);
  29739. serializationObject.isVisible = this.isVisible;
  29740. serializationObject.infiniteDistance = this.infiniteDistance;
  29741. serializationObject.pickable = this.isPickable;
  29742. serializationObject.receiveShadows = this.receiveShadows;
  29743. serializationObject.billboardMode = this.billboardMode;
  29744. serializationObject.visibility = this.visibility;
  29745. serializationObject.checkCollisions = this.checkCollisions;
  29746. serializationObject.isBlocker = this.isBlocker;
  29747. // Parent
  29748. if (this.parent) {
  29749. serializationObject.parentId = this.parent.id;
  29750. }
  29751. // Geometry
  29752. serializationObject.isUnIndexed = this.isUnIndexed;
  29753. var geometry = this._geometry;
  29754. if (geometry) {
  29755. var geometryId = geometry.id;
  29756. serializationObject.geometryId = geometryId;
  29757. // SubMeshes
  29758. serializationObject.subMeshes = [];
  29759. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29760. var subMesh = this.subMeshes[subIndex];
  29761. serializationObject.subMeshes.push({
  29762. materialIndex: subMesh.materialIndex,
  29763. verticesStart: subMesh.verticesStart,
  29764. verticesCount: subMesh.verticesCount,
  29765. indexStart: subMesh.indexStart,
  29766. indexCount: subMesh.indexCount
  29767. });
  29768. }
  29769. }
  29770. // Material
  29771. if (this.material) {
  29772. serializationObject.materialId = this.material.id;
  29773. }
  29774. else {
  29775. this.material = null;
  29776. }
  29777. // Morph targets
  29778. if (this.morphTargetManager) {
  29779. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29780. }
  29781. // Skeleton
  29782. if (this.skeleton) {
  29783. serializationObject.skeletonId = this.skeleton.id;
  29784. }
  29785. // Physics
  29786. //TODO implement correct serialization for physics impostors.
  29787. var impostor = this.getPhysicsImpostor();
  29788. if (impostor) {
  29789. serializationObject.physicsMass = impostor.getParam("mass");
  29790. serializationObject.physicsFriction = impostor.getParam("friction");
  29791. serializationObject.physicsRestitution = impostor.getParam("mass");
  29792. serializationObject.physicsImpostor = impostor.type;
  29793. }
  29794. // Metadata
  29795. if (this.metadata) {
  29796. serializationObject.metadata = this.metadata;
  29797. }
  29798. // Instances
  29799. serializationObject.instances = [];
  29800. for (var index = 0; index < this.instances.length; index++) {
  29801. var instance = this.instances[index];
  29802. var serializationInstance = {
  29803. name: instance.name,
  29804. id: instance.id,
  29805. position: instance.position.asArray(),
  29806. scaling: instance.scaling.asArray()
  29807. };
  29808. if (instance.rotationQuaternion) {
  29809. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29810. }
  29811. else if (instance.rotation) {
  29812. serializationInstance.rotation = instance.rotation.asArray();
  29813. }
  29814. serializationObject.instances.push(serializationInstance);
  29815. // Animations
  29816. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29817. serializationInstance.ranges = instance.serializeAnimationRanges();
  29818. }
  29819. //
  29820. // Animations
  29821. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29822. serializationObject.ranges = this.serializeAnimationRanges();
  29823. // Layer mask
  29824. serializationObject.layerMask = this.layerMask;
  29825. // Alpha
  29826. serializationObject.alphaIndex = this.alphaIndex;
  29827. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29828. // Overlay
  29829. serializationObject.overlayAlpha = this.overlayAlpha;
  29830. serializationObject.overlayColor = this.overlayColor.asArray();
  29831. serializationObject.renderOverlay = this.renderOverlay;
  29832. // Fog
  29833. serializationObject.applyFog = this.applyFog;
  29834. // Action Manager
  29835. if (this.actionManager) {
  29836. serializationObject.actions = this.actionManager.serialize(this.name);
  29837. }
  29838. };
  29839. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29840. if (!this.geometry) {
  29841. return;
  29842. }
  29843. this._markSubMeshesAsAttributesDirty();
  29844. var morphTargetManager = this._morphTargetManager;
  29845. if (morphTargetManager && morphTargetManager.vertexCount) {
  29846. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29847. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29848. this.morphTargetManager = null;
  29849. return;
  29850. }
  29851. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29852. var morphTarget = morphTargetManager.getActiveTarget(index);
  29853. var positions = morphTarget.getPositions();
  29854. if (!positions) {
  29855. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29856. return;
  29857. }
  29858. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29859. var normals = morphTarget.getNormals();
  29860. if (normals) {
  29861. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29862. }
  29863. var tangents = morphTarget.getTangents();
  29864. if (tangents) {
  29865. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29866. }
  29867. }
  29868. }
  29869. else {
  29870. var index = 0;
  29871. // Positions
  29872. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29873. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29874. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29875. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29876. }
  29877. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29878. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29879. }
  29880. index++;
  29881. }
  29882. }
  29883. };
  29884. // Statics
  29885. /**
  29886. * Returns a new Mesh object parsed from the source provided.
  29887. * The parameter `parsedMesh` is the source.
  29888. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29889. */
  29890. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29891. var mesh;
  29892. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29893. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29894. }
  29895. else {
  29896. mesh = new Mesh(parsedMesh.name, scene);
  29897. }
  29898. mesh.id = parsedMesh.id;
  29899. if (BABYLON.Tags) {
  29900. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29901. }
  29902. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29903. if (parsedMesh.metadata !== undefined) {
  29904. mesh.metadata = parsedMesh.metadata;
  29905. }
  29906. if (parsedMesh.rotationQuaternion) {
  29907. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29908. }
  29909. else if (parsedMesh.rotation) {
  29910. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29911. }
  29912. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29913. if (parsedMesh.localMatrix) {
  29914. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29915. }
  29916. else if (parsedMesh.pivotMatrix) {
  29917. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29918. }
  29919. mesh.setEnabled(parsedMesh.isEnabled);
  29920. mesh.isVisible = parsedMesh.isVisible;
  29921. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29922. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29923. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29924. if (parsedMesh.applyFog !== undefined) {
  29925. mesh.applyFog = parsedMesh.applyFog;
  29926. }
  29927. if (parsedMesh.pickable !== undefined) {
  29928. mesh.isPickable = parsedMesh.pickable;
  29929. }
  29930. if (parsedMesh.alphaIndex !== undefined) {
  29931. mesh.alphaIndex = parsedMesh.alphaIndex;
  29932. }
  29933. mesh.receiveShadows = parsedMesh.receiveShadows;
  29934. mesh.billboardMode = parsedMesh.billboardMode;
  29935. if (parsedMesh.visibility !== undefined) {
  29936. mesh.visibility = parsedMesh.visibility;
  29937. }
  29938. mesh.checkCollisions = parsedMesh.checkCollisions;
  29939. if (parsedMesh.isBlocker !== undefined) {
  29940. mesh.isBlocker = parsedMesh.isBlocker;
  29941. }
  29942. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29943. // freezeWorldMatrix
  29944. if (parsedMesh.freezeWorldMatrix) {
  29945. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29946. }
  29947. // Parent
  29948. if (parsedMesh.parentId) {
  29949. mesh._waitingParentId = parsedMesh.parentId;
  29950. }
  29951. // Actions
  29952. if (parsedMesh.actions !== undefined) {
  29953. mesh._waitingActions = parsedMesh.actions;
  29954. }
  29955. // Overlay
  29956. if (parsedMesh.overlayAlpha !== undefined) {
  29957. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29958. }
  29959. if (parsedMesh.overlayColor !== undefined) {
  29960. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29961. }
  29962. if (parsedMesh.renderOverlay !== undefined) {
  29963. mesh.renderOverlay = parsedMesh.renderOverlay;
  29964. }
  29965. // Geometry
  29966. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29967. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29968. if (parsedMesh.delayLoadingFile) {
  29969. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29970. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29971. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29972. if (parsedMesh._binaryInfo) {
  29973. mesh._binaryInfo = parsedMesh._binaryInfo;
  29974. }
  29975. mesh._delayInfo = [];
  29976. if (parsedMesh.hasUVs) {
  29977. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29978. }
  29979. if (parsedMesh.hasUVs2) {
  29980. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29981. }
  29982. if (parsedMesh.hasUVs3) {
  29983. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29984. }
  29985. if (parsedMesh.hasUVs4) {
  29986. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29987. }
  29988. if (parsedMesh.hasUVs5) {
  29989. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29990. }
  29991. if (parsedMesh.hasUVs6) {
  29992. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29993. }
  29994. if (parsedMesh.hasColors) {
  29995. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29996. }
  29997. if (parsedMesh.hasMatricesIndices) {
  29998. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29999. }
  30000. if (parsedMesh.hasMatricesWeights) {
  30001. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30002. }
  30003. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  30004. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  30005. mesh._checkDelayState();
  30006. }
  30007. }
  30008. else {
  30009. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  30010. }
  30011. // Material
  30012. if (parsedMesh.materialId) {
  30013. mesh.setMaterialByID(parsedMesh.materialId);
  30014. }
  30015. else {
  30016. mesh.material = null;
  30017. }
  30018. // Morph targets
  30019. if (parsedMesh.morphTargetManagerId > -1) {
  30020. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  30021. }
  30022. // Skeleton
  30023. if (parsedMesh.skeletonId > -1) {
  30024. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  30025. if (parsedMesh.numBoneInfluencers) {
  30026. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  30027. }
  30028. }
  30029. // Animations
  30030. if (parsedMesh.animations) {
  30031. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30032. var parsedAnimation = parsedMesh.animations[animationIndex];
  30033. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30034. }
  30035. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  30036. }
  30037. if (parsedMesh.autoAnimate) {
  30038. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  30039. }
  30040. // Layer Mask
  30041. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  30042. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  30043. }
  30044. else {
  30045. mesh.layerMask = 0x0FFFFFFF;
  30046. }
  30047. // Physics
  30048. if (parsedMesh.physicsImpostor) {
  30049. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  30050. mass: parsedMesh.physicsMass,
  30051. friction: parsedMesh.physicsFriction,
  30052. restitution: parsedMesh.physicsRestitution
  30053. }, scene);
  30054. }
  30055. // Instances
  30056. if (parsedMesh.instances) {
  30057. for (var index = 0; index < parsedMesh.instances.length; index++) {
  30058. var parsedInstance = parsedMesh.instances[index];
  30059. var instance = mesh.createInstance(parsedInstance.name);
  30060. if (parsedInstance.id) {
  30061. instance.id = parsedInstance.id;
  30062. }
  30063. if (BABYLON.Tags) {
  30064. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  30065. }
  30066. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  30067. if (parsedInstance.parentId) {
  30068. instance._waitingParentId = parsedInstance.parentId;
  30069. }
  30070. if (parsedInstance.rotationQuaternion) {
  30071. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  30072. }
  30073. else if (parsedInstance.rotation) {
  30074. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  30075. }
  30076. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  30077. instance.checkCollisions = mesh.checkCollisions;
  30078. if (parsedMesh.animations) {
  30079. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30080. parsedAnimation = parsedMesh.animations[animationIndex];
  30081. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30082. }
  30083. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30084. }
  30085. }
  30086. }
  30087. return mesh;
  30088. };
  30089. /**
  30090. * Creates a ribbon mesh.
  30091. * Please consider using the same method from the MeshBuilder class instead.
  30092. * 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.
  30093. *
  30094. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30095. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30096. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30097. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30098. * 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.
  30099. * 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.
  30100. * 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
  30101. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30102. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30103. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30104. */
  30105. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30106. if (closeArray === void 0) { closeArray = false; }
  30107. if (updatable === void 0) { updatable = false; }
  30108. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30109. pathArray: pathArray,
  30110. closeArray: closeArray,
  30111. closePath: closePath,
  30112. offset: offset,
  30113. updatable: updatable,
  30114. sideOrientation: sideOrientation,
  30115. instance: instance
  30116. }, scene);
  30117. };
  30118. /**
  30119. * Creates a plane polygonal mesh. By default, this is a disc.
  30120. * Please consider using the same method from the MeshBuilder class instead.
  30121. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30122. * 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.
  30123. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30124. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30125. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30126. */
  30127. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30128. if (scene === void 0) { scene = null; }
  30129. var options = {
  30130. radius: radius,
  30131. tessellation: tessellation,
  30132. sideOrientation: sideOrientation,
  30133. updatable: updatable
  30134. };
  30135. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30136. };
  30137. /**
  30138. * Creates a box mesh.
  30139. * Please consider using the same method from the MeshBuilder class instead.
  30140. * The parameter `size` sets the size (float) of each box side (default 1).
  30141. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30142. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30143. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30144. */
  30145. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30146. if (scene === void 0) { scene = null; }
  30147. var options = {
  30148. size: size,
  30149. sideOrientation: sideOrientation,
  30150. updatable: updatable
  30151. };
  30152. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30153. };
  30154. /**
  30155. * Creates a sphere mesh.
  30156. * Please consider using the same method from the MeshBuilder class instead.
  30157. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30158. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30162. */
  30163. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30164. var options = {
  30165. segments: segments,
  30166. diameterX: diameter,
  30167. diameterY: diameter,
  30168. diameterZ: diameter,
  30169. sideOrientation: sideOrientation,
  30170. updatable: updatable
  30171. };
  30172. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30173. };
  30174. /**
  30175. * Creates a cylinder or a cone mesh.
  30176. * Please consider using the same method from the MeshBuilder class instead.
  30177. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30178. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30179. * 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.
  30180. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30181. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30182. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30183. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30184. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30185. */
  30186. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30187. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30188. if (scene !== undefined) {
  30189. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30190. updatable = scene;
  30191. }
  30192. scene = subdivisions;
  30193. subdivisions = 1;
  30194. }
  30195. var options = {
  30196. height: height,
  30197. diameterTop: diameterTop,
  30198. diameterBottom: diameterBottom,
  30199. tessellation: tessellation,
  30200. subdivisions: subdivisions,
  30201. sideOrientation: sideOrientation,
  30202. updatable: updatable
  30203. };
  30204. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30205. };
  30206. // Torus (Code from SharpDX.org)
  30207. /**
  30208. * Creates a torus mesh.
  30209. * Please consider using the same method from the MeshBuilder class instead.
  30210. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30211. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30212. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30213. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30214. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30215. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30216. */
  30217. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30218. var options = {
  30219. diameter: diameter,
  30220. thickness: thickness,
  30221. tessellation: tessellation,
  30222. sideOrientation: sideOrientation,
  30223. updatable: updatable
  30224. };
  30225. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30226. };
  30227. /**
  30228. * Creates a torus knot mesh.
  30229. * Please consider using the same method from the MeshBuilder class instead.
  30230. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30231. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30232. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30233. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30234. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30235. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30236. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30237. */
  30238. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30239. var options = {
  30240. radius: radius,
  30241. tube: tube,
  30242. radialSegments: radialSegments,
  30243. tubularSegments: tubularSegments,
  30244. p: p,
  30245. q: q,
  30246. sideOrientation: sideOrientation,
  30247. updatable: updatable
  30248. };
  30249. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30250. };
  30251. /**
  30252. * Creates a line mesh.
  30253. * Please consider using the same method from the MeshBuilder class instead.
  30254. * 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.
  30255. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30256. * The parameter `points` is an array successive Vector3.
  30257. * 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
  30258. * When updating an instance, remember that only point positions can change, not the number of points.
  30259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30260. */
  30261. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30262. if (scene === void 0) { scene = null; }
  30263. if (updatable === void 0) { updatable = false; }
  30264. if (instance === void 0) { instance = null; }
  30265. var options = {
  30266. points: points,
  30267. updatable: updatable,
  30268. instance: instance
  30269. };
  30270. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30271. };
  30272. /**
  30273. * Creates a dashed line mesh.
  30274. * Please consider using the same method from the MeshBuilder class instead.
  30275. * 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.
  30276. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30277. * The parameter `points` is an array successive Vector3.
  30278. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30279. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30280. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30281. * 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
  30282. * When updating an instance, remember that only point positions can change, not the number of points.
  30283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30284. */
  30285. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30286. if (scene === void 0) { scene = null; }
  30287. var options = {
  30288. points: points,
  30289. dashSize: dashSize,
  30290. gapSize: gapSize,
  30291. dashNb: dashNb,
  30292. updatable: updatable,
  30293. instance: instance
  30294. };
  30295. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30296. };
  30297. /**
  30298. * Creates a polygon mesh.
  30299. * Please consider using the same method from the MeshBuilder class instead.
  30300. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30301. * 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.
  30302. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30304. * Remember you can only change the shape positions, not their number when updating a polygon.
  30305. */
  30306. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30307. var options = {
  30308. shape: shape,
  30309. holes: holes,
  30310. updatable: updatable,
  30311. sideOrientation: sideOrientation
  30312. };
  30313. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30314. };
  30315. /**
  30316. * Creates an extruded polygon mesh, with depth in the Y direction.
  30317. * Please consider using the same method from the MeshBuilder class instead.
  30318. */
  30319. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30320. var options = {
  30321. shape: shape,
  30322. holes: holes,
  30323. depth: depth,
  30324. updatable: updatable,
  30325. sideOrientation: sideOrientation
  30326. };
  30327. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30328. };
  30329. /**
  30330. * Creates an extruded shape mesh.
  30331. * 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.
  30332. * Please consider using the same method from the MeshBuilder class instead.
  30333. *
  30334. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30335. * 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
  30336. * extruded along the Z axis.
  30337. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30338. * 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.
  30339. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30340. * 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
  30341. * 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
  30342. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30343. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30344. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30345. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30346. */
  30347. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30348. if (scene === void 0) { scene = null; }
  30349. var options = {
  30350. shape: shape,
  30351. path: path,
  30352. scale: scale,
  30353. rotation: rotation,
  30354. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30355. sideOrientation: sideOrientation,
  30356. instance: instance,
  30357. updatable: updatable
  30358. };
  30359. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30360. };
  30361. /**
  30362. * Creates an custom extruded shape mesh.
  30363. * 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.
  30364. * Please consider using the same method from the MeshBuilder class instead.
  30365. *
  30366. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30367. * 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
  30368. * extruded along the Z axis.
  30369. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30370. * 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
  30371. * and the distance of this point from the begining of the path :
  30372. * ```javascript
  30373. * var rotationFunction = function(i, distance) {
  30374. * // do things
  30375. * return rotationValue; }
  30376. * ```
  30377. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30378. * 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
  30379. * and the distance of this point from the begining of the path :
  30380. * ```javascript
  30381. * var scaleFunction = function(i, distance) {
  30382. * // do things
  30383. * return scaleValue;}
  30384. * ```
  30385. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30386. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30387. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30388. * 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
  30389. * 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
  30390. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30391. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30392. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30394. */
  30395. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30396. var options = {
  30397. shape: shape,
  30398. path: path,
  30399. scaleFunction: scaleFunction,
  30400. rotationFunction: rotationFunction,
  30401. ribbonCloseArray: ribbonCloseArray,
  30402. ribbonClosePath: ribbonClosePath,
  30403. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30404. sideOrientation: sideOrientation,
  30405. instance: instance,
  30406. updatable: updatable
  30407. };
  30408. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30409. };
  30410. /**
  30411. * Creates lathe mesh.
  30412. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30413. * Please consider using the same method from the MeshBuilder class instead.
  30414. * 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
  30415. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30416. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30417. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30418. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30419. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30420. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30421. */
  30422. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30423. var options = {
  30424. shape: shape,
  30425. radius: radius,
  30426. tessellation: tessellation,
  30427. sideOrientation: sideOrientation,
  30428. updatable: updatable
  30429. };
  30430. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30431. };
  30432. /**
  30433. * Creates a plane mesh.
  30434. * Please consider using the same method from the MeshBuilder class instead.
  30435. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30436. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30437. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30439. */
  30440. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30441. var options = {
  30442. size: size,
  30443. width: size,
  30444. height: size,
  30445. sideOrientation: sideOrientation,
  30446. updatable: updatable
  30447. };
  30448. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30449. };
  30450. /**
  30451. * Creates a ground mesh.
  30452. * Please consider using the same method from the MeshBuilder class instead.
  30453. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30454. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30456. */
  30457. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30458. var options = {
  30459. width: width,
  30460. height: height,
  30461. subdivisions: subdivisions,
  30462. updatable: updatable
  30463. };
  30464. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30465. };
  30466. /**
  30467. * Creates a tiled ground mesh.
  30468. * Please consider using the same method from the MeshBuilder class instead.
  30469. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30470. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30471. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30472. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30473. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30474. * numbers of subdivisions on the ground width and height of each tile.
  30475. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30476. */
  30477. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30478. var options = {
  30479. xmin: xmin,
  30480. zmin: zmin,
  30481. xmax: xmax,
  30482. zmax: zmax,
  30483. subdivisions: subdivisions,
  30484. precision: precision,
  30485. updatable: updatable
  30486. };
  30487. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30488. };
  30489. /**
  30490. * Creates a ground mesh from a height map.
  30491. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30492. * Please consider using the same method from the MeshBuilder class instead.
  30493. * The parameter `url` sets the URL of the height map image resource.
  30494. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30495. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30496. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30497. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30498. * 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).
  30499. * This function is passed the newly built mesh :
  30500. * ```javascript
  30501. * function(mesh) { // do things
  30502. * return; }
  30503. * ```
  30504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30505. */
  30506. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30507. var options = {
  30508. width: width,
  30509. height: height,
  30510. subdivisions: subdivisions,
  30511. minHeight: minHeight,
  30512. maxHeight: maxHeight,
  30513. updatable: updatable,
  30514. onReady: onReady
  30515. };
  30516. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30517. };
  30518. /**
  30519. * Creates a tube mesh.
  30520. * 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.
  30521. * Please consider using the same method from the MeshBuilder class instead.
  30522. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30523. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30524. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30525. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30526. * 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.
  30527. * It must return a radius value (positive float) :
  30528. * ```javascript
  30529. * var radiusFunction = function(i, distance) {
  30530. * // do things
  30531. * return radius; }
  30532. * ```
  30533. * 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
  30534. * 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
  30535. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30536. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30537. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30538. */
  30539. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30540. var options = {
  30541. path: path,
  30542. radius: radius,
  30543. tessellation: tessellation,
  30544. radiusFunction: radiusFunction,
  30545. arc: 1,
  30546. cap: cap,
  30547. updatable: updatable,
  30548. sideOrientation: sideOrientation,
  30549. instance: instance
  30550. };
  30551. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30552. };
  30553. /**
  30554. * Creates a polyhedron mesh.
  30555. * Please consider using the same method from the MeshBuilder class instead.
  30556. * 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
  30557. * to choose the wanted type.
  30558. * The parameter `size` (positive float, default 1) sets the polygon size.
  30559. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30560. * 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`.
  30561. * 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
  30562. * 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)`).
  30563. * 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
  30564. * 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.
  30565. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30566. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30567. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30568. */
  30569. Mesh.CreatePolyhedron = function (name, options, scene) {
  30570. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30571. };
  30572. /**
  30573. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30574. * Please consider using the same method from the MeshBuilder class instead.
  30575. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30576. * 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`).
  30577. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30578. * 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.
  30579. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30580. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30582. */
  30583. Mesh.CreateIcoSphere = function (name, options, scene) {
  30584. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30585. };
  30586. /**
  30587. * Creates a decal mesh.
  30588. * Please consider using the same method from the MeshBuilder class instead.
  30589. * 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.
  30590. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30591. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30592. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30593. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30594. */
  30595. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30596. var options = {
  30597. position: position,
  30598. normal: normal,
  30599. size: size,
  30600. angle: angle
  30601. };
  30602. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30603. };
  30604. // Skeletons
  30605. /**
  30606. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30607. */
  30608. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30609. if (!this._sourcePositions) {
  30610. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30611. if (!source) {
  30612. return this._sourcePositions;
  30613. }
  30614. this._sourcePositions = new Float32Array(source);
  30615. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30616. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30617. }
  30618. }
  30619. return this._sourcePositions;
  30620. };
  30621. /**
  30622. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30623. */
  30624. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30625. if (!this._sourceNormals) {
  30626. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30627. if (!source) {
  30628. return this._sourceNormals;
  30629. }
  30630. this._sourceNormals = new Float32Array(source);
  30631. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30632. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30633. }
  30634. }
  30635. return this._sourceNormals;
  30636. };
  30637. /**
  30638. * Updates the vertex buffer by applying transformation from the bones.
  30639. * Returns the Mesh.
  30640. *
  30641. * @param {skeleton} skeleton to apply
  30642. */
  30643. Mesh.prototype.applySkeleton = function (skeleton) {
  30644. if (!this.geometry) {
  30645. return this;
  30646. }
  30647. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30648. return this;
  30649. }
  30650. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30651. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30652. return this;
  30653. }
  30654. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30655. return this;
  30656. }
  30657. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30658. return this;
  30659. }
  30660. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30661. return this;
  30662. }
  30663. if (!this._sourcePositions) {
  30664. var submeshes = this.subMeshes.slice();
  30665. this.setPositionsForCPUSkinning();
  30666. this.subMeshes = submeshes;
  30667. }
  30668. if (!this._sourceNormals) {
  30669. this.setNormalsForCPUSkinning();
  30670. }
  30671. // positionsData checks for not being Float32Array will only pass at most once
  30672. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30673. if (!positionsData) {
  30674. return this;
  30675. }
  30676. if (!(positionsData instanceof Float32Array)) {
  30677. positionsData = new Float32Array(positionsData);
  30678. }
  30679. // normalsData checks for not being Float32Array will only pass at most once
  30680. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30681. if (!normalsData) {
  30682. return this;
  30683. }
  30684. if (!(normalsData instanceof Float32Array)) {
  30685. normalsData = new Float32Array(normalsData);
  30686. }
  30687. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30688. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30689. if (!matricesWeightsData || !matricesIndicesData) {
  30690. return this;
  30691. }
  30692. var needExtras = this.numBoneInfluencers > 4;
  30693. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30694. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30695. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30696. var tempVector3 = BABYLON.Vector3.Zero();
  30697. var finalMatrix = new BABYLON.Matrix();
  30698. var tempMatrix = new BABYLON.Matrix();
  30699. var matWeightIdx = 0;
  30700. var inf;
  30701. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30702. var weight;
  30703. for (inf = 0; inf < 4; inf++) {
  30704. weight = matricesWeightsData[matWeightIdx + inf];
  30705. if (weight > 0) {
  30706. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30707. finalMatrix.addToSelf(tempMatrix);
  30708. }
  30709. else
  30710. break;
  30711. }
  30712. if (needExtras) {
  30713. for (inf = 0; inf < 4; inf++) {
  30714. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30715. if (weight > 0) {
  30716. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30717. finalMatrix.addToSelf(tempMatrix);
  30718. }
  30719. else
  30720. break;
  30721. }
  30722. }
  30723. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30724. tempVector3.toArray(positionsData, index);
  30725. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30726. tempVector3.toArray(normalsData, index);
  30727. finalMatrix.reset();
  30728. }
  30729. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30730. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30731. return this;
  30732. };
  30733. // Tools
  30734. /**
  30735. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30736. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30737. */
  30738. Mesh.MinMax = function (meshes) {
  30739. var minVector = null;
  30740. var maxVector = null;
  30741. meshes.forEach(function (mesh, index, array) {
  30742. var boundingInfo = mesh.getBoundingInfo();
  30743. var boundingBox = boundingInfo.boundingBox;
  30744. if (!minVector || !maxVector) {
  30745. minVector = boundingBox.minimumWorld;
  30746. maxVector = boundingBox.maximumWorld;
  30747. }
  30748. else {
  30749. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30750. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30751. }
  30752. });
  30753. if (!minVector || !maxVector) {
  30754. return {
  30755. min: BABYLON.Vector3.Zero(),
  30756. max: BABYLON.Vector3.Zero()
  30757. };
  30758. }
  30759. return {
  30760. min: minVector,
  30761. max: maxVector
  30762. };
  30763. };
  30764. /**
  30765. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30766. */
  30767. Mesh.Center = function (meshesOrMinMaxVector) {
  30768. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30769. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30770. };
  30771. /**
  30772. * Merge the array of meshes into a single mesh for performance reasons.
  30773. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30774. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30775. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30776. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30777. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30778. */
  30779. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30780. if (disposeSource === void 0) { disposeSource = true; }
  30781. var index;
  30782. if (!allow32BitsIndices) {
  30783. var totalVertices = 0;
  30784. // Counting vertices
  30785. for (index = 0; index < meshes.length; index++) {
  30786. if (meshes[index]) {
  30787. totalVertices += meshes[index].getTotalVertices();
  30788. if (totalVertices > 65536) {
  30789. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30790. return null;
  30791. }
  30792. }
  30793. }
  30794. }
  30795. // Merge
  30796. var vertexData = null;
  30797. var otherVertexData;
  30798. var indiceArray = new Array();
  30799. var source = null;
  30800. for (index = 0; index < meshes.length; index++) {
  30801. if (meshes[index]) {
  30802. meshes[index].computeWorldMatrix(true);
  30803. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30804. otherVertexData.transform(meshes[index].getWorldMatrix());
  30805. if (vertexData) {
  30806. vertexData.merge(otherVertexData);
  30807. }
  30808. else {
  30809. vertexData = otherVertexData;
  30810. source = meshes[index];
  30811. }
  30812. if (subdivideWithSubMeshes) {
  30813. indiceArray.push(meshes[index].getTotalIndices());
  30814. }
  30815. }
  30816. }
  30817. source = source;
  30818. if (!meshSubclass) {
  30819. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30820. }
  30821. vertexData.applyToMesh(meshSubclass);
  30822. // Setting properties
  30823. meshSubclass.material = source.material;
  30824. meshSubclass.checkCollisions = source.checkCollisions;
  30825. // Cleaning
  30826. if (disposeSource) {
  30827. for (index = 0; index < meshes.length; index++) {
  30828. if (meshes[index]) {
  30829. meshes[index].dispose();
  30830. }
  30831. }
  30832. }
  30833. // Subdivide
  30834. if (subdivideWithSubMeshes) {
  30835. //-- Suppresions du submesh global
  30836. meshSubclass.releaseSubMeshes();
  30837. index = 0;
  30838. var offset = 0;
  30839. //-- aplique la subdivision en fonction du tableau d'indices
  30840. while (index < indiceArray.length) {
  30841. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30842. offset += indiceArray[index];
  30843. index++;
  30844. }
  30845. }
  30846. return meshSubclass;
  30847. };
  30848. // Consts
  30849. Mesh._FRONTSIDE = 0;
  30850. Mesh._BACKSIDE = 1;
  30851. Mesh._DOUBLESIDE = 2;
  30852. Mesh._DEFAULTSIDE = 0;
  30853. Mesh._NO_CAP = 0;
  30854. Mesh._CAP_START = 1;
  30855. Mesh._CAP_END = 2;
  30856. Mesh._CAP_ALL = 3;
  30857. return Mesh;
  30858. }(BABYLON.AbstractMesh));
  30859. BABYLON.Mesh = Mesh;
  30860. })(BABYLON || (BABYLON = {}));
  30861. //# sourceMappingURL=babylon.mesh.js.map
  30862. "use strict";
  30863. var BABYLON;
  30864. (function (BABYLON) {
  30865. var BaseSubMesh = /** @class */ (function () {
  30866. function BaseSubMesh() {
  30867. }
  30868. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30869. get: function () {
  30870. return this._materialEffect;
  30871. },
  30872. enumerable: true,
  30873. configurable: true
  30874. });
  30875. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30876. if (defines === void 0) { defines = null; }
  30877. if (this._materialEffect === effect) {
  30878. if (!effect) {
  30879. this._materialDefines = null;
  30880. }
  30881. return;
  30882. }
  30883. this._materialDefines = defines;
  30884. this._materialEffect = effect;
  30885. };
  30886. return BaseSubMesh;
  30887. }());
  30888. BABYLON.BaseSubMesh = BaseSubMesh;
  30889. var SubMesh = /** @class */ (function (_super) {
  30890. __extends(SubMesh, _super);
  30891. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30892. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30893. var _this = _super.call(this) || this;
  30894. _this.materialIndex = materialIndex;
  30895. _this.verticesStart = verticesStart;
  30896. _this.verticesCount = verticesCount;
  30897. _this.indexStart = indexStart;
  30898. _this.indexCount = indexCount;
  30899. _this._renderId = 0;
  30900. _this._mesh = mesh;
  30901. _this._renderingMesh = renderingMesh || mesh;
  30902. mesh.subMeshes.push(_this);
  30903. _this._trianglePlanes = [];
  30904. _this._id = mesh.subMeshes.length - 1;
  30905. if (createBoundingBox) {
  30906. _this.refreshBoundingInfo();
  30907. mesh.computeWorldMatrix(true);
  30908. }
  30909. return _this;
  30910. }
  30911. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30912. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30913. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30914. };
  30915. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30916. get: function () {
  30917. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30918. },
  30919. enumerable: true,
  30920. configurable: true
  30921. });
  30922. /**
  30923. * Returns the submesh BoudingInfo object.
  30924. */
  30925. SubMesh.prototype.getBoundingInfo = function () {
  30926. if (this.IsGlobal) {
  30927. return this._mesh.getBoundingInfo();
  30928. }
  30929. return this._boundingInfo;
  30930. };
  30931. /**
  30932. * Sets the submesh BoundingInfo.
  30933. * Return the SubMesh.
  30934. */
  30935. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30936. this._boundingInfo = boundingInfo;
  30937. return this;
  30938. };
  30939. /**
  30940. * Returns the mesh of the current submesh.
  30941. */
  30942. SubMesh.prototype.getMesh = function () {
  30943. return this._mesh;
  30944. };
  30945. /**
  30946. * Returns the rendering mesh of the submesh.
  30947. */
  30948. SubMesh.prototype.getRenderingMesh = function () {
  30949. return this._renderingMesh;
  30950. };
  30951. /**
  30952. * Returns the submesh material.
  30953. */
  30954. SubMesh.prototype.getMaterial = function () {
  30955. var rootMaterial = this._renderingMesh.material;
  30956. if (rootMaterial === null || rootMaterial === undefined) {
  30957. return this._mesh.getScene().defaultMaterial;
  30958. }
  30959. else if (rootMaterial.getSubMaterial) {
  30960. var multiMaterial = rootMaterial;
  30961. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30962. if (this._currentMaterial !== effectiveMaterial) {
  30963. this._currentMaterial = effectiveMaterial;
  30964. this._materialDefines = null;
  30965. }
  30966. return effectiveMaterial;
  30967. }
  30968. return rootMaterial;
  30969. };
  30970. // Methods
  30971. /**
  30972. * Sets a new updated BoundingInfo object to the submesh.
  30973. * Returns the SubMesh.
  30974. */
  30975. SubMesh.prototype.refreshBoundingInfo = function () {
  30976. this._lastColliderWorldVertices = null;
  30977. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30978. return this;
  30979. }
  30980. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30981. if (!data) {
  30982. this._boundingInfo = this._mesh.getBoundingInfo();
  30983. return this;
  30984. }
  30985. var indices = this._renderingMesh.getIndices();
  30986. var extend;
  30987. //is this the only submesh?
  30988. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30989. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30990. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30991. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30992. }
  30993. else {
  30994. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30995. }
  30996. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30997. return this;
  30998. };
  30999. SubMesh.prototype._checkCollision = function (collider) {
  31000. var boundingInfo = this._renderingMesh.getBoundingInfo();
  31001. return boundingInfo._checkCollision(collider);
  31002. };
  31003. /**
  31004. * Updates the submesh BoundingInfo.
  31005. * Returns the Submesh.
  31006. */
  31007. SubMesh.prototype.updateBoundingInfo = function (world) {
  31008. var boundingInfo = this.getBoundingInfo();
  31009. if (!boundingInfo) {
  31010. this.refreshBoundingInfo();
  31011. boundingInfo = this.getBoundingInfo();
  31012. }
  31013. boundingInfo.update(world);
  31014. return this;
  31015. };
  31016. /**
  31017. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  31018. * Boolean returned.
  31019. */
  31020. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  31021. var boundingInfo = this.getBoundingInfo();
  31022. if (!boundingInfo) {
  31023. return false;
  31024. }
  31025. return boundingInfo.isInFrustum(frustumPlanes);
  31026. };
  31027. /**
  31028. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  31029. * Boolean returned.
  31030. */
  31031. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  31032. var boundingInfo = this.getBoundingInfo();
  31033. if (!boundingInfo) {
  31034. return false;
  31035. }
  31036. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  31037. };
  31038. /**
  31039. * Renders the submesh.
  31040. * Returns it.
  31041. */
  31042. SubMesh.prototype.render = function (enableAlphaMode) {
  31043. this._renderingMesh.render(this, enableAlphaMode);
  31044. return this;
  31045. };
  31046. /**
  31047. * Returns a new Index Buffer.
  31048. * Type returned : WebGLBuffer.
  31049. */
  31050. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  31051. if (!this._linesIndexBuffer) {
  31052. var linesIndices = [];
  31053. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31054. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  31055. }
  31056. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  31057. this.linesIndexCount = linesIndices.length;
  31058. }
  31059. return this._linesIndexBuffer;
  31060. };
  31061. /**
  31062. * True is the passed Ray intersects the submesh bounding box.
  31063. * Boolean returned.
  31064. */
  31065. SubMesh.prototype.canIntersects = function (ray) {
  31066. var boundingInfo = this.getBoundingInfo();
  31067. if (!boundingInfo) {
  31068. return false;
  31069. }
  31070. return ray.intersectsBox(boundingInfo.boundingBox);
  31071. };
  31072. /**
  31073. * Returns an object IntersectionInfo.
  31074. */
  31075. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  31076. var intersectInfo = null;
  31077. var material = this.getMaterial();
  31078. if (!material) {
  31079. return null;
  31080. }
  31081. switch (material.fillMode) {
  31082. case BABYLON.Material.PointListDrawMode:
  31083. case BABYLON.Material.LineListDrawMode:
  31084. case BABYLON.Material.LineLoopDrawMode:
  31085. case BABYLON.Material.LineStripDrawMode:
  31086. case BABYLON.Material.TriangleFanDrawMode:
  31087. case BABYLON.Material.TriangleStripDrawMode:
  31088. return null;
  31089. }
  31090. // LineMesh first as it's also a Mesh...
  31091. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31092. var lineMesh = this._mesh;
  31093. // Line test
  31094. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31095. var p0 = positions[indices[index]];
  31096. var p1 = positions[indices[index + 1]];
  31097. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31098. if (length < 0) {
  31099. continue;
  31100. }
  31101. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31102. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31103. if (fastCheck) {
  31104. break;
  31105. }
  31106. }
  31107. }
  31108. }
  31109. else {
  31110. // Triangles test
  31111. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31112. var p0 = positions[indices[index]];
  31113. var p1 = positions[indices[index + 1]];
  31114. var p2 = positions[indices[index + 2]];
  31115. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31116. if (currentIntersectInfo) {
  31117. if (currentIntersectInfo.distance < 0) {
  31118. continue;
  31119. }
  31120. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31121. intersectInfo = currentIntersectInfo;
  31122. intersectInfo.faceId = index / 3;
  31123. if (fastCheck) {
  31124. break;
  31125. }
  31126. }
  31127. }
  31128. }
  31129. }
  31130. return intersectInfo;
  31131. };
  31132. SubMesh.prototype._rebuild = function () {
  31133. if (this._linesIndexBuffer) {
  31134. this._linesIndexBuffer = null;
  31135. }
  31136. };
  31137. // Clone
  31138. /**
  31139. * Creates a new Submesh from the passed Mesh.
  31140. */
  31141. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31142. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31143. if (!this.IsGlobal) {
  31144. var boundingInfo = this.getBoundingInfo();
  31145. if (!boundingInfo) {
  31146. return result;
  31147. }
  31148. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31149. }
  31150. return result;
  31151. };
  31152. // Dispose
  31153. /**
  31154. * Disposes the Submesh.
  31155. * Returns nothing.
  31156. */
  31157. SubMesh.prototype.dispose = function () {
  31158. if (this._linesIndexBuffer) {
  31159. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31160. this._linesIndexBuffer = null;
  31161. }
  31162. // Remove from mesh
  31163. var index = this._mesh.subMeshes.indexOf(this);
  31164. this._mesh.subMeshes.splice(index, 1);
  31165. };
  31166. // Statics
  31167. /**
  31168. * Creates a new Submesh from the passed parameters :
  31169. * - materialIndex (integer) : the index of the main mesh material.
  31170. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31171. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31172. * - mesh (Mesh) : the main mesh to create the submesh from.
  31173. * - renderingMesh (optional Mesh) : rendering mesh.
  31174. */
  31175. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31176. var minVertexIndex = Number.MAX_VALUE;
  31177. var maxVertexIndex = -Number.MAX_VALUE;
  31178. renderingMesh = (renderingMesh || mesh);
  31179. var indices = renderingMesh.getIndices();
  31180. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31181. var vertexIndex = indices[index];
  31182. if (vertexIndex < minVertexIndex)
  31183. minVertexIndex = vertexIndex;
  31184. if (vertexIndex > maxVertexIndex)
  31185. maxVertexIndex = vertexIndex;
  31186. }
  31187. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31188. };
  31189. return SubMesh;
  31190. }(BaseSubMesh));
  31191. BABYLON.SubMesh = SubMesh;
  31192. })(BABYLON || (BABYLON = {}));
  31193. //# sourceMappingURL=babylon.subMesh.js.map
  31194. "use strict";
  31195. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31196. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31197. s = arguments[i];
  31198. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31199. t[p] = s[p];
  31200. }
  31201. return t;
  31202. };
  31203. var BABYLON;
  31204. (function (BABYLON) {
  31205. /**
  31206. * Manages the defines for the Material.
  31207. */
  31208. var MaterialDefines = /** @class */ (function () {
  31209. function MaterialDefines() {
  31210. this._isDirty = true;
  31211. this._areLightsDirty = true;
  31212. this._areAttributesDirty = true;
  31213. this._areTexturesDirty = true;
  31214. this._areFresnelDirty = true;
  31215. this._areMiscDirty = true;
  31216. this._areImageProcessingDirty = true;
  31217. this._normals = false;
  31218. this._uvs = false;
  31219. this._needNormals = false;
  31220. this._needUVs = false;
  31221. }
  31222. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31223. /**
  31224. * Specifies if the material needs to be re-calculated.
  31225. */
  31226. get: function () {
  31227. return this._isDirty;
  31228. },
  31229. enumerable: true,
  31230. configurable: true
  31231. });
  31232. /**
  31233. * Marks the material to indicate that it has been re-calculated.
  31234. */
  31235. MaterialDefines.prototype.markAsProcessed = function () {
  31236. this._isDirty = false;
  31237. this._areAttributesDirty = false;
  31238. this._areTexturesDirty = false;
  31239. this._areFresnelDirty = false;
  31240. this._areLightsDirty = false;
  31241. this._areMiscDirty = false;
  31242. this._areImageProcessingDirty = false;
  31243. };
  31244. /**
  31245. * Marks the material to indicate that it needs to be re-calculated.
  31246. */
  31247. MaterialDefines.prototype.markAsUnprocessed = function () {
  31248. this._isDirty = true;
  31249. };
  31250. /**
  31251. * Marks the material to indicate all of its defines need to be re-calculated.
  31252. */
  31253. MaterialDefines.prototype.markAllAsDirty = function () {
  31254. this._areTexturesDirty = true;
  31255. this._areAttributesDirty = true;
  31256. this._areLightsDirty = true;
  31257. this._areFresnelDirty = true;
  31258. this._areMiscDirty = true;
  31259. this._areImageProcessingDirty = true;
  31260. this._isDirty = true;
  31261. };
  31262. /**
  31263. * Marks the material to indicate that image processing needs to be re-calculated.
  31264. */
  31265. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31266. this._areImageProcessingDirty = true;
  31267. this._isDirty = true;
  31268. };
  31269. /**
  31270. * Marks the material to indicate the lights need to be re-calculated.
  31271. */
  31272. MaterialDefines.prototype.markAsLightDirty = function () {
  31273. this._areLightsDirty = true;
  31274. this._isDirty = true;
  31275. };
  31276. /**
  31277. * Marks the attribute state as changed.
  31278. */
  31279. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31280. this._areAttributesDirty = true;
  31281. this._isDirty = true;
  31282. };
  31283. /**
  31284. * Marks the texture state as changed.
  31285. */
  31286. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31287. this._areTexturesDirty = true;
  31288. this._isDirty = true;
  31289. };
  31290. /**
  31291. * Marks the fresnel state as changed.
  31292. */
  31293. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31294. this._areFresnelDirty = true;
  31295. this._isDirty = true;
  31296. };
  31297. /**
  31298. * Marks the misc state as changed.
  31299. */
  31300. MaterialDefines.prototype.markAsMiscDirty = function () {
  31301. this._areMiscDirty = true;
  31302. this._isDirty = true;
  31303. };
  31304. /**
  31305. * Rebuilds the material defines.
  31306. */
  31307. MaterialDefines.prototype.rebuild = function () {
  31308. if (this._keys) {
  31309. delete this._keys;
  31310. }
  31311. this._keys = [];
  31312. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31313. var key = _a[_i];
  31314. if (key[0] === "_") {
  31315. continue;
  31316. }
  31317. this._keys.push(key);
  31318. }
  31319. };
  31320. /**
  31321. * Specifies if two material defines are equal.
  31322. * @param other - A material define instance to compare to.
  31323. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31324. */
  31325. MaterialDefines.prototype.isEqual = function (other) {
  31326. if (this._keys.length !== other._keys.length) {
  31327. return false;
  31328. }
  31329. for (var index = 0; index < this._keys.length; index++) {
  31330. var prop = this._keys[index];
  31331. if (this[prop] !== other[prop]) {
  31332. return false;
  31333. }
  31334. }
  31335. return true;
  31336. };
  31337. /**
  31338. * Clones this instance's defines to another instance.
  31339. * @param other - material defines to clone values to.
  31340. */
  31341. MaterialDefines.prototype.cloneTo = function (other) {
  31342. if (this._keys.length !== other._keys.length) {
  31343. other._keys = this._keys.slice(0);
  31344. }
  31345. for (var index = 0; index < this._keys.length; index++) {
  31346. var prop = this._keys[index];
  31347. other[prop] = this[prop];
  31348. }
  31349. };
  31350. /**
  31351. * Resets the material define values.
  31352. */
  31353. MaterialDefines.prototype.reset = function () {
  31354. for (var index = 0; index < this._keys.length; index++) {
  31355. var prop = this._keys[index];
  31356. if (typeof (this[prop]) === "number") {
  31357. this[prop] = 0;
  31358. }
  31359. else {
  31360. this[prop] = false;
  31361. }
  31362. }
  31363. };
  31364. /**
  31365. * Converts the material define values to a string.
  31366. * @returns - String of material define information.
  31367. */
  31368. MaterialDefines.prototype.toString = function () {
  31369. var result = "";
  31370. for (var index = 0; index < this._keys.length; index++) {
  31371. var prop = this._keys[index];
  31372. var value = this[prop];
  31373. if (typeof (value) === "number") {
  31374. result += "#define " + prop + " " + this[prop] + "\n";
  31375. }
  31376. else if (value) {
  31377. result += "#define " + prop + "\n";
  31378. }
  31379. }
  31380. return result;
  31381. };
  31382. return MaterialDefines;
  31383. }());
  31384. BABYLON.MaterialDefines = MaterialDefines;
  31385. /**
  31386. * This offers the main features of a material in BJS.
  31387. */
  31388. var Material = /** @class */ (function () {
  31389. /**
  31390. * Creates a material instance.
  31391. * @param name - The name of the material.
  31392. * @param scene - The BJS scene to reference.
  31393. * @param doNotAdd - Specifies if the material should be added to the scene.
  31394. */
  31395. function Material(name, scene, doNotAdd) {
  31396. /**
  31397. * Specifies if the ready state should be checked on each call.
  31398. */
  31399. this.checkReadyOnEveryCall = false;
  31400. /**
  31401. * Specifies if the ready state should be checked once.
  31402. */
  31403. this.checkReadyOnlyOnce = false;
  31404. /**
  31405. * The state of the material.
  31406. */
  31407. this.state = "";
  31408. /**
  31409. * The alpha value of the material.
  31410. */
  31411. this._alpha = 1.0;
  31412. /**
  31413. * Specifies if back face culling is enabled.
  31414. */
  31415. this._backFaceCulling = true;
  31416. /**
  31417. * Specifies if the material should be serialized.
  31418. */
  31419. this.doNotSerialize = false;
  31420. /**
  31421. * Specifies if the effect should be stored on sub meshes.
  31422. */
  31423. this.storeEffectOnSubMeshes = false;
  31424. /**
  31425. * An event triggered when the material is disposed.
  31426. * @type {BABYLON.Observable}
  31427. */
  31428. this.onDisposeObservable = new BABYLON.Observable();
  31429. /**
  31430. * An event triggered when the material is bound.
  31431. * @type {BABYLON.Observable}
  31432. */
  31433. this.onBindObservable = new BABYLON.Observable();
  31434. /**
  31435. * An event triggered when the material is unbound.
  31436. * @type {BABYLON.Observable}
  31437. */
  31438. this.onUnBindObservable = new BABYLON.Observable();
  31439. /**
  31440. * Stores the value of the alpha mode.
  31441. */
  31442. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31443. /**
  31444. * Stores the state of the need depth pre-pass value.
  31445. */
  31446. this._needDepthPrePass = false;
  31447. /**
  31448. * Specifies if depth writing should be disabled.
  31449. */
  31450. this.disableDepthWrite = false;
  31451. /**
  31452. * Specifies if depth writing should be forced.
  31453. */
  31454. this.forceDepthWrite = false;
  31455. /**
  31456. * Specifies if there should be a separate pass for culling.
  31457. */
  31458. this.separateCullingPass = false;
  31459. /**
  31460. * Stores the state specifing if fog should be enabled.
  31461. */
  31462. this._fogEnabled = true;
  31463. /**
  31464. * Stores the size of points.
  31465. */
  31466. this.pointSize = 1.0;
  31467. /**
  31468. * Stores the z offset value.
  31469. */
  31470. this.zOffset = 0;
  31471. /**
  31472. * Specifies if the material was previously ready.
  31473. */
  31474. this._wasPreviouslyReady = false;
  31475. /**
  31476. * Stores the fill mode state.
  31477. */
  31478. this._fillMode = Material.TriangleFillMode;
  31479. this.name = name;
  31480. this.id = name || BABYLON.Tools.RandomId();
  31481. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31482. if (this._scene.useRightHandedSystem) {
  31483. this.sideOrientation = Material.ClockWiseSideOrientation;
  31484. }
  31485. else {
  31486. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31487. }
  31488. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31489. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31490. if (!doNotAdd) {
  31491. this._scene.materials.push(this);
  31492. }
  31493. }
  31494. Object.defineProperty(Material, "TriangleFillMode", {
  31495. /**
  31496. * Returns the triangle fill mode.
  31497. */
  31498. get: function () {
  31499. return Material._TriangleFillMode;
  31500. },
  31501. enumerable: true,
  31502. configurable: true
  31503. });
  31504. Object.defineProperty(Material, "WireFrameFillMode", {
  31505. /**
  31506. * Returns the wireframe mode.
  31507. */
  31508. get: function () {
  31509. return Material._WireFrameFillMode;
  31510. },
  31511. enumerable: true,
  31512. configurable: true
  31513. });
  31514. Object.defineProperty(Material, "PointFillMode", {
  31515. /**
  31516. * Returns the point fill mode.
  31517. */
  31518. get: function () {
  31519. return Material._PointFillMode;
  31520. },
  31521. enumerable: true,
  31522. configurable: true
  31523. });
  31524. Object.defineProperty(Material, "PointListDrawMode", {
  31525. /**
  31526. * Returns the point list draw mode.
  31527. */
  31528. get: function () {
  31529. return Material._PointListDrawMode;
  31530. },
  31531. enumerable: true,
  31532. configurable: true
  31533. });
  31534. Object.defineProperty(Material, "LineListDrawMode", {
  31535. /**
  31536. * Returns the line list draw mode.
  31537. */
  31538. get: function () {
  31539. return Material._LineListDrawMode;
  31540. },
  31541. enumerable: true,
  31542. configurable: true
  31543. });
  31544. Object.defineProperty(Material, "LineLoopDrawMode", {
  31545. /**
  31546. * Returns the line loop draw mode.
  31547. */
  31548. get: function () {
  31549. return Material._LineLoopDrawMode;
  31550. },
  31551. enumerable: true,
  31552. configurable: true
  31553. });
  31554. Object.defineProperty(Material, "LineStripDrawMode", {
  31555. /**
  31556. * Returns the line strip draw mode.
  31557. */
  31558. get: function () {
  31559. return Material._LineStripDrawMode;
  31560. },
  31561. enumerable: true,
  31562. configurable: true
  31563. });
  31564. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31565. /**
  31566. * Returns the triangle strip draw mode.
  31567. */
  31568. get: function () {
  31569. return Material._TriangleStripDrawMode;
  31570. },
  31571. enumerable: true,
  31572. configurable: true
  31573. });
  31574. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31575. /**
  31576. * Returns the triangle fan draw mode.
  31577. */
  31578. get: function () {
  31579. return Material._TriangleFanDrawMode;
  31580. },
  31581. enumerable: true,
  31582. configurable: true
  31583. });
  31584. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31585. /**
  31586. * Returns the clock-wise side orientation.
  31587. */
  31588. get: function () {
  31589. return Material._ClockWiseSideOrientation;
  31590. },
  31591. enumerable: true,
  31592. configurable: true
  31593. });
  31594. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31595. /**
  31596. * Returns the counter clock-wise side orientation.
  31597. */
  31598. get: function () {
  31599. return Material._CounterClockWiseSideOrientation;
  31600. },
  31601. enumerable: true,
  31602. configurable: true
  31603. });
  31604. Object.defineProperty(Material, "TextureDirtyFlag", {
  31605. /**
  31606. * Returns the dirty texture flag value.
  31607. */
  31608. get: function () {
  31609. return Material._TextureDirtyFlag;
  31610. },
  31611. enumerable: true,
  31612. configurable: true
  31613. });
  31614. Object.defineProperty(Material, "LightDirtyFlag", {
  31615. /**
  31616. * Returns the dirty light flag value.
  31617. */
  31618. get: function () {
  31619. return Material._LightDirtyFlag;
  31620. },
  31621. enumerable: true,
  31622. configurable: true
  31623. });
  31624. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31625. /**
  31626. * Returns the dirty fresnel flag value.
  31627. */
  31628. get: function () {
  31629. return Material._FresnelDirtyFlag;
  31630. },
  31631. enumerable: true,
  31632. configurable: true
  31633. });
  31634. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31635. /**
  31636. * Returns the dirty attributes flag value.
  31637. */
  31638. get: function () {
  31639. return Material._AttributesDirtyFlag;
  31640. },
  31641. enumerable: true,
  31642. configurable: true
  31643. });
  31644. Object.defineProperty(Material, "MiscDirtyFlag", {
  31645. /**
  31646. * Returns the dirty misc flag value.
  31647. */
  31648. get: function () {
  31649. return Material._MiscDirtyFlag;
  31650. },
  31651. enumerable: true,
  31652. configurable: true
  31653. });
  31654. Object.defineProperty(Material.prototype, "alpha", {
  31655. /**
  31656. * Gets the alpha value of the material.
  31657. */
  31658. get: function () {
  31659. return this._alpha;
  31660. },
  31661. /**
  31662. * Sets the alpha value of the material.
  31663. */
  31664. set: function (value) {
  31665. if (this._alpha === value) {
  31666. return;
  31667. }
  31668. this._alpha = value;
  31669. this.markAsDirty(Material.MiscDirtyFlag);
  31670. },
  31671. enumerable: true,
  31672. configurable: true
  31673. });
  31674. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31675. /**
  31676. * Gets the back-face culling state.
  31677. */
  31678. get: function () {
  31679. return this._backFaceCulling;
  31680. },
  31681. /**
  31682. * Sets the back-face culling state.
  31683. */
  31684. set: function (value) {
  31685. if (this._backFaceCulling === value) {
  31686. return;
  31687. }
  31688. this._backFaceCulling = value;
  31689. this.markAsDirty(Material.TextureDirtyFlag);
  31690. },
  31691. enumerable: true,
  31692. configurable: true
  31693. });
  31694. Object.defineProperty(Material.prototype, "onDispose", {
  31695. /**
  31696. * Called during a dispose event.
  31697. */
  31698. set: function (callback) {
  31699. if (this._onDisposeObserver) {
  31700. this.onDisposeObservable.remove(this._onDisposeObserver);
  31701. }
  31702. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31703. },
  31704. enumerable: true,
  31705. configurable: true
  31706. });
  31707. Object.defineProperty(Material.prototype, "onBind", {
  31708. /**
  31709. * Called during a bind event.
  31710. */
  31711. set: function (callback) {
  31712. if (this._onBindObserver) {
  31713. this.onBindObservable.remove(this._onBindObserver);
  31714. }
  31715. this._onBindObserver = this.onBindObservable.add(callback);
  31716. },
  31717. enumerable: true,
  31718. configurable: true
  31719. });
  31720. Object.defineProperty(Material.prototype, "alphaMode", {
  31721. /**
  31722. * Gets the value of the alpha mode.
  31723. */
  31724. get: function () {
  31725. return this._alphaMode;
  31726. },
  31727. /**
  31728. * Sets the value of the alpha mode.
  31729. */
  31730. set: function (value) {
  31731. if (this._alphaMode === value) {
  31732. return;
  31733. }
  31734. this._alphaMode = value;
  31735. this.markAsDirty(Material.TextureDirtyFlag);
  31736. },
  31737. enumerable: true,
  31738. configurable: true
  31739. });
  31740. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31741. /**
  31742. * Gets the depth pre-pass value.
  31743. */
  31744. get: function () {
  31745. return this._needDepthPrePass;
  31746. },
  31747. /**
  31748. * Sets the need depth pre-pass value.
  31749. */
  31750. set: function (value) {
  31751. if (this._needDepthPrePass === value) {
  31752. return;
  31753. }
  31754. this._needDepthPrePass = value;
  31755. if (this._needDepthPrePass) {
  31756. this.checkReadyOnEveryCall = true;
  31757. }
  31758. },
  31759. enumerable: true,
  31760. configurable: true
  31761. });
  31762. Object.defineProperty(Material.prototype, "fogEnabled", {
  31763. /**
  31764. * Gets the value of the fog enabled state.
  31765. */
  31766. get: function () {
  31767. return this._fogEnabled;
  31768. },
  31769. /**
  31770. * Sets the state for enabling fog.
  31771. */
  31772. set: function (value) {
  31773. if (this._fogEnabled === value) {
  31774. return;
  31775. }
  31776. this._fogEnabled = value;
  31777. this.markAsDirty(Material.MiscDirtyFlag);
  31778. },
  31779. enumerable: true,
  31780. configurable: true
  31781. });
  31782. Object.defineProperty(Material.prototype, "wireframe", {
  31783. /**
  31784. * Gets a value specifying if wireframe mode is enabled.
  31785. */
  31786. get: function () {
  31787. switch (this._fillMode) {
  31788. case Material.WireFrameFillMode:
  31789. case Material.LineListDrawMode:
  31790. case Material.LineLoopDrawMode:
  31791. case Material.LineStripDrawMode:
  31792. return true;
  31793. }
  31794. return this._scene.forceWireframe;
  31795. },
  31796. /**
  31797. * Sets the state of wireframe mode.
  31798. */
  31799. set: function (value) {
  31800. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31801. },
  31802. enumerable: true,
  31803. configurable: true
  31804. });
  31805. Object.defineProperty(Material.prototype, "pointsCloud", {
  31806. /**
  31807. * Gets the value specifying if point clouds are enabled.
  31808. */
  31809. get: function () {
  31810. switch (this._fillMode) {
  31811. case Material.PointFillMode:
  31812. case Material.PointListDrawMode:
  31813. return true;
  31814. }
  31815. return this._scene.forcePointsCloud;
  31816. },
  31817. /**
  31818. * Sets the state of point cloud mode.
  31819. */
  31820. set: function (value) {
  31821. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31822. },
  31823. enumerable: true,
  31824. configurable: true
  31825. });
  31826. Object.defineProperty(Material.prototype, "fillMode", {
  31827. /**
  31828. * Gets the material fill mode.
  31829. */
  31830. get: function () {
  31831. return this._fillMode;
  31832. },
  31833. /**
  31834. * Sets the material fill mode.
  31835. */
  31836. set: function (value) {
  31837. if (this._fillMode === value) {
  31838. return;
  31839. }
  31840. this._fillMode = value;
  31841. this.markAsDirty(Material.MiscDirtyFlag);
  31842. },
  31843. enumerable: true,
  31844. configurable: true
  31845. });
  31846. /**
  31847. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31848. * subclasses should override adding information pertainent to themselves.
  31849. * @returns - String with material information.
  31850. */
  31851. Material.prototype.toString = function (fullDetails) {
  31852. var ret = "Name: " + this.name;
  31853. if (fullDetails) {
  31854. }
  31855. return ret;
  31856. };
  31857. /**
  31858. * Gets the class name of the material.
  31859. * @returns - String with the class name of the material.
  31860. */
  31861. Material.prototype.getClassName = function () {
  31862. return "Material";
  31863. };
  31864. Object.defineProperty(Material.prototype, "isFrozen", {
  31865. /**
  31866. * Specifies if updates for the material been locked.
  31867. */
  31868. get: function () {
  31869. return this.checkReadyOnlyOnce;
  31870. },
  31871. enumerable: true,
  31872. configurable: true
  31873. });
  31874. /**
  31875. * Locks updates for the material.
  31876. */
  31877. Material.prototype.freeze = function () {
  31878. this.checkReadyOnlyOnce = true;
  31879. };
  31880. /**
  31881. * Unlocks updates for the material.
  31882. */
  31883. Material.prototype.unfreeze = function () {
  31884. this.checkReadyOnlyOnce = false;
  31885. };
  31886. /**
  31887. * Specifies if the material is ready to be used.
  31888. * @param mesh - BJS mesh.
  31889. * @param useInstances - Specifies if instances should be used.
  31890. * @returns - Boolean indicating if the material is ready to be used.
  31891. */
  31892. Material.prototype.isReady = function (mesh, useInstances) {
  31893. return true;
  31894. };
  31895. /**
  31896. * Specifies that the submesh is ready to be used.
  31897. * @param mesh - BJS mesh.
  31898. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31899. * @param useInstances - Specifies that instances should be used.
  31900. * @returns - boolean indicating that the submesh is ready or not.
  31901. */
  31902. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31903. return false;
  31904. };
  31905. /**
  31906. * Returns the material effect.
  31907. * @returns - Nullable material effect.
  31908. */
  31909. Material.prototype.getEffect = function () {
  31910. return this._effect;
  31911. };
  31912. /**
  31913. * Returns the BJS scene.
  31914. * @returns - BJS Scene.
  31915. */
  31916. Material.prototype.getScene = function () {
  31917. return this._scene;
  31918. };
  31919. /**
  31920. * Specifies if the material will require alpha blending
  31921. * @returns - Boolean specifying if alpha blending is needed.
  31922. */
  31923. Material.prototype.needAlphaBlending = function () {
  31924. return (this.alpha < 1.0);
  31925. };
  31926. /**
  31927. * Specifies if the mesh will require alpha blending.
  31928. * @param mesh - BJS mesh.
  31929. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31930. */
  31931. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31932. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31933. };
  31934. /**
  31935. * Specifies if this material should be rendered in alpha test mode.
  31936. * @returns - Boolean specifying if an alpha test is needed.
  31937. */
  31938. Material.prototype.needAlphaTesting = function () {
  31939. return false;
  31940. };
  31941. /**
  31942. * Gets the texture used for the alpha test.
  31943. * @returns - Nullable alpha test texture.
  31944. */
  31945. Material.prototype.getAlphaTestTexture = function () {
  31946. return null;
  31947. };
  31948. /**
  31949. * Marks the material to indicate that it needs to be re-calculated.
  31950. */
  31951. Material.prototype.markDirty = function () {
  31952. this._wasPreviouslyReady = false;
  31953. };
  31954. Material.prototype._preBind = function (effect, overrideOrientation) {
  31955. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31956. var engine = this._scene.getEngine();
  31957. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31958. var reverse = orientation === Material.ClockWiseSideOrientation;
  31959. engine.enableEffect(effect ? effect : this._effect);
  31960. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31961. return reverse;
  31962. };
  31963. /**
  31964. * Binds the material to the mesh.
  31965. * @param world - World transformation matrix.
  31966. * @param mesh - Mesh to bind the material to.
  31967. */
  31968. Material.prototype.bind = function (world, mesh) {
  31969. };
  31970. /**
  31971. * Binds the submesh to the material.
  31972. * @param world - World transformation matrix.
  31973. * @param mesh - Mesh containing the submesh.
  31974. * @param subMesh - Submesh to bind the material to.
  31975. */
  31976. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31977. };
  31978. /**
  31979. * Binds the world matrix to the material.
  31980. * @param world - World transformation matrix.
  31981. */
  31982. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31983. };
  31984. /**
  31985. * Binds the scene's uniform buffer to the effect.
  31986. * @param effect - Effect to bind to the scene uniform buffer.
  31987. * @param sceneUbo - Scene uniform buffer.
  31988. */
  31989. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31990. sceneUbo.bindToEffect(effect, "Scene");
  31991. };
  31992. /**
  31993. * Binds the view matrix to the effect.
  31994. * @param effect - Effect to bind the view matrix to.
  31995. */
  31996. Material.prototype.bindView = function (effect) {
  31997. if (!this._useUBO) {
  31998. effect.setMatrix("view", this.getScene().getViewMatrix());
  31999. }
  32000. else {
  32001. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32002. }
  32003. };
  32004. /**
  32005. * Binds the view projection matrix to the effect.
  32006. * @param effect - Effect to bind the view projection matrix to.
  32007. */
  32008. Material.prototype.bindViewProjection = function (effect) {
  32009. if (!this._useUBO) {
  32010. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  32011. }
  32012. else {
  32013. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32014. }
  32015. };
  32016. /**
  32017. * Specifies if material alpha testing should be turned on for the mesh.
  32018. * @param mesh - BJS mesh.
  32019. */
  32020. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  32021. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  32022. };
  32023. /**
  32024. * Processes to execute after binding the material to a mesh.
  32025. * @param mesh - BJS mesh.
  32026. */
  32027. Material.prototype._afterBind = function (mesh) {
  32028. this._scene._cachedMaterial = this;
  32029. if (mesh) {
  32030. this._scene._cachedVisibility = mesh.visibility;
  32031. }
  32032. else {
  32033. this._scene._cachedVisibility = 1;
  32034. }
  32035. if (mesh) {
  32036. this.onBindObservable.notifyObservers(mesh);
  32037. }
  32038. if (this.disableDepthWrite) {
  32039. var engine = this._scene.getEngine();
  32040. this._cachedDepthWriteState = engine.getDepthWrite();
  32041. engine.setDepthWrite(false);
  32042. }
  32043. };
  32044. /**
  32045. * Unbinds the material from the mesh.
  32046. */
  32047. Material.prototype.unbind = function () {
  32048. this.onUnBindObservable.notifyObservers(this);
  32049. if (this.disableDepthWrite) {
  32050. var engine = this._scene.getEngine();
  32051. engine.setDepthWrite(this._cachedDepthWriteState);
  32052. }
  32053. };
  32054. /**
  32055. * Gets the active textures from the material.
  32056. * @returns - Array of textures.
  32057. */
  32058. Material.prototype.getActiveTextures = function () {
  32059. return [];
  32060. };
  32061. /**
  32062. * Specifies if the material uses a texture.
  32063. * @param texture - Texture to check against the material.
  32064. * @returns - Boolean specifying if the material uses the texture.
  32065. */
  32066. Material.prototype.hasTexture = function (texture) {
  32067. return false;
  32068. };
  32069. /**
  32070. * Makes a duplicate of the material, and gives it a new name.
  32071. * @param name - Name to call the duplicated material.
  32072. * @returns - Nullable cloned material
  32073. */
  32074. Material.prototype.clone = function (name) {
  32075. return null;
  32076. };
  32077. /**
  32078. * Gets the meshes bound to the material.
  32079. * @returns - Array of meshes bound to the material.
  32080. */
  32081. Material.prototype.getBindedMeshes = function () {
  32082. var result = new Array();
  32083. for (var index = 0; index < this._scene.meshes.length; index++) {
  32084. var mesh = this._scene.meshes[index];
  32085. if (mesh.material === this) {
  32086. result.push(mesh);
  32087. }
  32088. }
  32089. return result;
  32090. };
  32091. /**
  32092. * Force shader compilation
  32093. * @param mesh - BJS mesh.
  32094. * @param onCompiled - function to execute once the material is compiled.
  32095. * @param options - options to pass to this function.
  32096. */
  32097. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32098. var _this = this;
  32099. var localOptions = __assign({ clipPlane: false }, options);
  32100. var subMesh = new BABYLON.BaseSubMesh();
  32101. var scene = this.getScene();
  32102. var checkReady = function () {
  32103. if (!_this._scene || !_this._scene.getEngine()) {
  32104. return;
  32105. }
  32106. if (subMesh._materialDefines) {
  32107. subMesh._materialDefines._renderId = -1;
  32108. }
  32109. var clipPlaneState = scene.clipPlane;
  32110. if (localOptions.clipPlane) {
  32111. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32112. }
  32113. if (_this.storeEffectOnSubMeshes) {
  32114. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32115. if (onCompiled) {
  32116. onCompiled(_this);
  32117. }
  32118. }
  32119. else {
  32120. setTimeout(checkReady, 16);
  32121. }
  32122. }
  32123. else {
  32124. if (_this.isReady(mesh)) {
  32125. if (onCompiled) {
  32126. onCompiled(_this);
  32127. }
  32128. }
  32129. else {
  32130. setTimeout(checkReady, 16);
  32131. }
  32132. }
  32133. if (localOptions.clipPlane) {
  32134. scene.clipPlane = clipPlaneState;
  32135. }
  32136. };
  32137. checkReady();
  32138. };
  32139. /**
  32140. * Force shader compilation.
  32141. * @param mesh The mesh that will use this material
  32142. * @param options Additional options for compiling the shaders
  32143. * @returns A promise that resolves when the compilation completes
  32144. */
  32145. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32146. var _this = this;
  32147. return new Promise(function (resolve) {
  32148. _this.forceCompilation(mesh, function () {
  32149. resolve();
  32150. }, options);
  32151. });
  32152. };
  32153. /**
  32154. * Marks a define in the material to indicate that it needs to be re-computed.
  32155. * @param flag - Material define flag.
  32156. */
  32157. Material.prototype.markAsDirty = function (flag) {
  32158. if (flag & Material.TextureDirtyFlag) {
  32159. this._markAllSubMeshesAsTexturesDirty();
  32160. }
  32161. if (flag & Material.LightDirtyFlag) {
  32162. this._markAllSubMeshesAsLightsDirty();
  32163. }
  32164. if (flag & Material.FresnelDirtyFlag) {
  32165. this._markAllSubMeshesAsFresnelDirty();
  32166. }
  32167. if (flag & Material.AttributesDirtyFlag) {
  32168. this._markAllSubMeshesAsAttributesDirty();
  32169. }
  32170. if (flag & Material.MiscDirtyFlag) {
  32171. this._markAllSubMeshesAsMiscDirty();
  32172. }
  32173. this.getScene().resetCachedMaterial();
  32174. };
  32175. /**
  32176. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32177. * @param func - function which checks material defines against the submeshes.
  32178. */
  32179. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32180. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32181. var mesh = _a[_i];
  32182. if (!mesh.subMeshes) {
  32183. continue;
  32184. }
  32185. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32186. var subMesh = _c[_b];
  32187. if (subMesh.getMaterial() !== this) {
  32188. continue;
  32189. }
  32190. if (!subMesh._materialDefines) {
  32191. continue;
  32192. }
  32193. func(subMesh._materialDefines);
  32194. }
  32195. }
  32196. };
  32197. /**
  32198. * Indicates that image processing needs to be re-calculated for all submeshes.
  32199. */
  32200. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32201. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32202. };
  32203. /**
  32204. * Indicates that textures need to be re-calculated for all submeshes.
  32205. */
  32206. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32207. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32208. };
  32209. /**
  32210. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32211. */
  32212. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32213. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32214. };
  32215. /**
  32216. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32217. */
  32218. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32219. this._markAllSubMeshesAsDirty(function (defines) {
  32220. defines.markAsFresnelDirty();
  32221. defines.markAsMiscDirty();
  32222. });
  32223. };
  32224. /**
  32225. * Indicates that lights need to be re-calculated for all submeshes.
  32226. */
  32227. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32228. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32229. };
  32230. /**
  32231. * Indicates that attributes need to be re-calculated for all submeshes.
  32232. */
  32233. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32234. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32235. };
  32236. /**
  32237. * Indicates that misc needs to be re-calculated for all submeshes.
  32238. */
  32239. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32240. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32241. };
  32242. /**
  32243. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32244. */
  32245. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32246. this._markAllSubMeshesAsDirty(function (defines) {
  32247. defines.markAsTexturesDirty();
  32248. defines.markAsMiscDirty();
  32249. });
  32250. };
  32251. /**
  32252. * Disposes the material.
  32253. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32254. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32255. */
  32256. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32257. // Animations
  32258. this.getScene().stopAnimation(this);
  32259. this.getScene().freeProcessedMaterials();
  32260. // Remove from scene
  32261. var index = this._scene.materials.indexOf(this);
  32262. if (index >= 0) {
  32263. this._scene.materials.splice(index, 1);
  32264. }
  32265. // Remove from meshes
  32266. for (index = 0; index < this._scene.meshes.length; index++) {
  32267. var mesh = this._scene.meshes[index];
  32268. if (mesh.material === this) {
  32269. mesh.material = null;
  32270. if (mesh.geometry) {
  32271. var geometry = (mesh.geometry);
  32272. if (this.storeEffectOnSubMeshes) {
  32273. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32274. var subMesh = _a[_i];
  32275. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32276. if (forceDisposeEffect && subMesh._materialEffect) {
  32277. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32278. }
  32279. }
  32280. }
  32281. else {
  32282. geometry._releaseVertexArrayObject(this._effect);
  32283. }
  32284. }
  32285. }
  32286. }
  32287. this._uniformBuffer.dispose();
  32288. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32289. if (forceDisposeEffect && this._effect) {
  32290. if (!this.storeEffectOnSubMeshes) {
  32291. this._scene.getEngine()._releaseEffect(this._effect);
  32292. }
  32293. this._effect = null;
  32294. }
  32295. // Callback
  32296. this.onDisposeObservable.notifyObservers(this);
  32297. this.onDisposeObservable.clear();
  32298. this.onBindObservable.clear();
  32299. this.onUnBindObservable.clear();
  32300. };
  32301. /**
  32302. * Serializes this material.
  32303. * @returns - serialized material object.
  32304. */
  32305. Material.prototype.serialize = function () {
  32306. return BABYLON.SerializationHelper.Serialize(this);
  32307. };
  32308. /**
  32309. * Creates a MultiMaterial from parse MultiMaterial data.
  32310. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32311. * @param scene - BJS scene.
  32312. * @returns - MultiMaterial.
  32313. */
  32314. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32315. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32316. multiMaterial.id = parsedMultiMaterial.id;
  32317. if (BABYLON.Tags) {
  32318. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32319. }
  32320. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32321. var subMatId = parsedMultiMaterial.materials[matIndex];
  32322. if (subMatId) {
  32323. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32324. }
  32325. else {
  32326. multiMaterial.subMaterials.push(null);
  32327. }
  32328. }
  32329. return multiMaterial;
  32330. };
  32331. /**
  32332. * Creates a material from parsed material data.
  32333. * @param parsedMaterial - Parsed material data.
  32334. * @param scene - BJS scene.
  32335. * @param rootUrl - Root URL containing the material information.
  32336. * @returns - Parsed material.
  32337. */
  32338. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32339. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32340. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32341. }
  32342. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32343. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32344. if (!BABYLON.LegacyPBRMaterial) {
  32345. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32346. return;
  32347. }
  32348. }
  32349. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32350. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32351. ;
  32352. };
  32353. // Triangle views
  32354. Material._TriangleFillMode = 0;
  32355. Material._WireFrameFillMode = 1;
  32356. Material._PointFillMode = 2;
  32357. // Draw modes
  32358. Material._PointListDrawMode = 3;
  32359. Material._LineListDrawMode = 4;
  32360. Material._LineLoopDrawMode = 5;
  32361. Material._LineStripDrawMode = 6;
  32362. Material._TriangleStripDrawMode = 7;
  32363. Material._TriangleFanDrawMode = 8;
  32364. /**
  32365. * Stores the clock-wise side orientation.
  32366. */
  32367. Material._ClockWiseSideOrientation = 0;
  32368. /**
  32369. * Stores the counter clock-wise side orientation.
  32370. */
  32371. Material._CounterClockWiseSideOrientation = 1;
  32372. /**
  32373. * The dirty texture flag value.
  32374. */
  32375. Material._TextureDirtyFlag = 1;
  32376. /**
  32377. * The dirty light flag value.
  32378. */
  32379. Material._LightDirtyFlag = 2;
  32380. /**
  32381. * The dirty fresnel flag value.
  32382. */
  32383. Material._FresnelDirtyFlag = 4;
  32384. /**
  32385. * The dirty attribute flag value.
  32386. */
  32387. Material._AttributesDirtyFlag = 8;
  32388. /**
  32389. * The dirty misc flag value.
  32390. */
  32391. Material._MiscDirtyFlag = 16;
  32392. __decorate([
  32393. BABYLON.serialize()
  32394. ], Material.prototype, "id", void 0);
  32395. __decorate([
  32396. BABYLON.serialize()
  32397. ], Material.prototype, "name", void 0);
  32398. __decorate([
  32399. BABYLON.serialize()
  32400. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32401. __decorate([
  32402. BABYLON.serialize()
  32403. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32404. __decorate([
  32405. BABYLON.serialize()
  32406. ], Material.prototype, "state", void 0);
  32407. __decorate([
  32408. BABYLON.serialize("alpha")
  32409. ], Material.prototype, "_alpha", void 0);
  32410. __decorate([
  32411. BABYLON.serialize("backFaceCulling")
  32412. ], Material.prototype, "_backFaceCulling", void 0);
  32413. __decorate([
  32414. BABYLON.serialize()
  32415. ], Material.prototype, "sideOrientation", void 0);
  32416. __decorate([
  32417. BABYLON.serialize("alphaMode")
  32418. ], Material.prototype, "_alphaMode", void 0);
  32419. __decorate([
  32420. BABYLON.serialize()
  32421. ], Material.prototype, "_needDepthPrePass", void 0);
  32422. __decorate([
  32423. BABYLON.serialize()
  32424. ], Material.prototype, "disableDepthWrite", void 0);
  32425. __decorate([
  32426. BABYLON.serialize()
  32427. ], Material.prototype, "forceDepthWrite", void 0);
  32428. __decorate([
  32429. BABYLON.serialize()
  32430. ], Material.prototype, "separateCullingPass", void 0);
  32431. __decorate([
  32432. BABYLON.serialize("fogEnabled")
  32433. ], Material.prototype, "_fogEnabled", void 0);
  32434. __decorate([
  32435. BABYLON.serialize()
  32436. ], Material.prototype, "pointSize", void 0);
  32437. __decorate([
  32438. BABYLON.serialize()
  32439. ], Material.prototype, "zOffset", void 0);
  32440. __decorate([
  32441. BABYLON.serialize()
  32442. ], Material.prototype, "wireframe", null);
  32443. __decorate([
  32444. BABYLON.serialize()
  32445. ], Material.prototype, "pointsCloud", null);
  32446. __decorate([
  32447. BABYLON.serialize()
  32448. ], Material.prototype, "fillMode", null);
  32449. return Material;
  32450. }());
  32451. BABYLON.Material = Material;
  32452. })(BABYLON || (BABYLON = {}));
  32453. //# sourceMappingURL=babylon.material.js.map
  32454. "use strict";
  32455. var BABYLON;
  32456. (function (BABYLON) {
  32457. var UniformBuffer = /** @class */ (function () {
  32458. /**
  32459. * Uniform buffer objects.
  32460. *
  32461. * Handles blocks of uniform on the GPU.
  32462. *
  32463. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32464. *
  32465. * For more information, please refer to :
  32466. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32467. */
  32468. function UniformBuffer(engine, data, dynamic) {
  32469. this._engine = engine;
  32470. this._noUBO = !engine.supportsUniformBuffers;
  32471. this._dynamic = dynamic;
  32472. this._data = data || [];
  32473. this._uniformLocations = {};
  32474. this._uniformSizes = {};
  32475. this._uniformLocationPointer = 0;
  32476. this._needSync = false;
  32477. if (this._noUBO) {
  32478. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32479. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32480. this.updateFloat = this._updateFloatForEffect;
  32481. this.updateFloat2 = this._updateFloat2ForEffect;
  32482. this.updateFloat3 = this._updateFloat3ForEffect;
  32483. this.updateFloat4 = this._updateFloat4ForEffect;
  32484. this.updateMatrix = this._updateMatrixForEffect;
  32485. this.updateVector3 = this._updateVector3ForEffect;
  32486. this.updateVector4 = this._updateVector4ForEffect;
  32487. this.updateColor3 = this._updateColor3ForEffect;
  32488. this.updateColor4 = this._updateColor4ForEffect;
  32489. }
  32490. else {
  32491. this._engine._uniformBuffers.push(this);
  32492. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32493. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32494. this.updateFloat = this._updateFloatForUniform;
  32495. this.updateFloat2 = this._updateFloat2ForUniform;
  32496. this.updateFloat3 = this._updateFloat3ForUniform;
  32497. this.updateFloat4 = this._updateFloat4ForUniform;
  32498. this.updateMatrix = this._updateMatrixForUniform;
  32499. this.updateVector3 = this._updateVector3ForUniform;
  32500. this.updateVector4 = this._updateVector4ForUniform;
  32501. this.updateColor3 = this._updateColor3ForUniform;
  32502. this.updateColor4 = this._updateColor4ForUniform;
  32503. }
  32504. }
  32505. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32506. // Properties
  32507. /**
  32508. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32509. * or just falling back on setUniformXXX calls.
  32510. */
  32511. get: function () {
  32512. return !this._noUBO;
  32513. },
  32514. enumerable: true,
  32515. configurable: true
  32516. });
  32517. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32518. /**
  32519. * Indicates if the WebGL underlying uniform buffer is in sync
  32520. * with the javascript cache data.
  32521. */
  32522. get: function () {
  32523. return !this._needSync;
  32524. },
  32525. enumerable: true,
  32526. configurable: true
  32527. });
  32528. /**
  32529. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32530. * Also, a dynamic UniformBuffer will disable cache verification and always
  32531. * update the underlying WebGL uniform buffer to the GPU.
  32532. */
  32533. UniformBuffer.prototype.isDynamic = function () {
  32534. return this._dynamic !== undefined;
  32535. };
  32536. /**
  32537. * The data cache on JS side.
  32538. */
  32539. UniformBuffer.prototype.getData = function () {
  32540. return this._bufferData;
  32541. };
  32542. /**
  32543. * The underlying WebGL Uniform buffer.
  32544. */
  32545. UniformBuffer.prototype.getBuffer = function () {
  32546. return this._buffer;
  32547. };
  32548. /**
  32549. * std140 layout specifies how to align data within an UBO structure.
  32550. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32551. * for specs.
  32552. */
  32553. UniformBuffer.prototype._fillAlignment = function (size) {
  32554. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32555. // and 4x4 matrices
  32556. // TODO : change if other types are used
  32557. var alignment;
  32558. if (size <= 2) {
  32559. alignment = size;
  32560. }
  32561. else {
  32562. alignment = 4;
  32563. }
  32564. if ((this._uniformLocationPointer % alignment) !== 0) {
  32565. var oldPointer = this._uniformLocationPointer;
  32566. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32567. var diff = this._uniformLocationPointer - oldPointer;
  32568. for (var i = 0; i < diff; i++) {
  32569. this._data.push(0);
  32570. }
  32571. }
  32572. };
  32573. /**
  32574. * Adds an uniform in the buffer.
  32575. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32576. * for the layout to be correct !
  32577. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32578. * @param {number|number[]} size Data size, or data directly.
  32579. */
  32580. UniformBuffer.prototype.addUniform = function (name, size) {
  32581. if (this._noUBO) {
  32582. return;
  32583. }
  32584. if (this._uniformLocations[name] !== undefined) {
  32585. // Already existing uniform
  32586. return;
  32587. }
  32588. // This function must be called in the order of the shader layout !
  32589. // size can be the size of the uniform, or data directly
  32590. var data;
  32591. if (size instanceof Array) {
  32592. data = size;
  32593. size = data.length;
  32594. }
  32595. else {
  32596. size = size;
  32597. data = [];
  32598. // Fill with zeros
  32599. for (var i = 0; i < size; i++) {
  32600. data.push(0);
  32601. }
  32602. }
  32603. this._fillAlignment(size);
  32604. this._uniformSizes[name] = size;
  32605. this._uniformLocations[name] = this._uniformLocationPointer;
  32606. this._uniformLocationPointer += size;
  32607. for (var i = 0; i < size; i++) {
  32608. this._data.push(data[i]);
  32609. }
  32610. this._needSync = true;
  32611. };
  32612. /**
  32613. * Wrapper for addUniform.
  32614. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32615. * @param {Matrix} mat A 4x4 matrix.
  32616. */
  32617. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32618. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32619. };
  32620. /**
  32621. * Wrapper for addUniform.
  32622. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32623. * @param {number} x
  32624. * @param {number} y
  32625. */
  32626. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32627. var temp = [x, y];
  32628. this.addUniform(name, temp);
  32629. };
  32630. /**
  32631. * Wrapper for addUniform.
  32632. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32633. * @param {number} x
  32634. * @param {number} y
  32635. * @param {number} z
  32636. */
  32637. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32638. var temp = [x, y, z];
  32639. this.addUniform(name, temp);
  32640. };
  32641. /**
  32642. * Wrapper for addUniform.
  32643. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32644. * @param {Color3} color
  32645. */
  32646. UniformBuffer.prototype.addColor3 = function (name, color) {
  32647. var temp = new Array();
  32648. color.toArray(temp);
  32649. this.addUniform(name, temp);
  32650. };
  32651. /**
  32652. * Wrapper for addUniform.
  32653. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32654. * @param {Color3} color
  32655. * @param {number} alpha
  32656. */
  32657. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32658. var temp = new Array();
  32659. color.toArray(temp);
  32660. temp.push(alpha);
  32661. this.addUniform(name, temp);
  32662. };
  32663. /**
  32664. * Wrapper for addUniform.
  32665. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32666. * @param {Vector3} vector
  32667. */
  32668. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32669. var temp = new Array();
  32670. vector.toArray(temp);
  32671. this.addUniform(name, temp);
  32672. };
  32673. /**
  32674. * Wrapper for addUniform.
  32675. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32676. */
  32677. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32678. this.addUniform(name, 12);
  32679. };
  32680. /**
  32681. * Wrapper for addUniform.
  32682. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32683. */
  32684. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32685. this.addUniform(name, 8);
  32686. };
  32687. /**
  32688. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32689. */
  32690. UniformBuffer.prototype.create = function () {
  32691. if (this._noUBO) {
  32692. return;
  32693. }
  32694. if (this._buffer) {
  32695. return; // nothing to do
  32696. }
  32697. // See spec, alignment must be filled as a vec4
  32698. this._fillAlignment(4);
  32699. this._bufferData = new Float32Array(this._data);
  32700. this._rebuild();
  32701. this._needSync = true;
  32702. };
  32703. UniformBuffer.prototype._rebuild = function () {
  32704. if (this._noUBO) {
  32705. return;
  32706. }
  32707. if (this._dynamic) {
  32708. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32709. }
  32710. else {
  32711. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32712. }
  32713. };
  32714. /**
  32715. * Updates the WebGL Uniform Buffer on the GPU.
  32716. * If the `dynamic` flag is set to true, no cache comparison is done.
  32717. * Otherwise, the buffer will be updated only if the cache differs.
  32718. */
  32719. UniformBuffer.prototype.update = function () {
  32720. if (!this._buffer) {
  32721. this.create();
  32722. return;
  32723. }
  32724. if (!this._dynamic && !this._needSync) {
  32725. return;
  32726. }
  32727. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32728. this._needSync = false;
  32729. };
  32730. /**
  32731. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32732. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32733. * @param {number[]|Float32Array} data Flattened data
  32734. * @param {number} size Size of the data.
  32735. */
  32736. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32737. var location = this._uniformLocations[uniformName];
  32738. if (location === undefined) {
  32739. if (this._buffer) {
  32740. // Cannot add an uniform if the buffer is already created
  32741. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32742. return;
  32743. }
  32744. this.addUniform(uniformName, size);
  32745. location = this._uniformLocations[uniformName];
  32746. }
  32747. if (!this._buffer) {
  32748. this.create();
  32749. }
  32750. if (!this._dynamic) {
  32751. // Cache for static uniform buffers
  32752. var changed = false;
  32753. for (var i = 0; i < size; i++) {
  32754. if (this._bufferData[location + i] !== data[i]) {
  32755. changed = true;
  32756. this._bufferData[location + i] = data[i];
  32757. }
  32758. }
  32759. this._needSync = this._needSync || changed;
  32760. }
  32761. else {
  32762. // No cache for dynamic
  32763. for (var i = 0; i < size; i++) {
  32764. this._bufferData[location + i] = data[i];
  32765. }
  32766. }
  32767. };
  32768. // Update methods
  32769. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32770. // To match std140, matrix must be realigned
  32771. for (var i = 0; i < 3; i++) {
  32772. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32773. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32774. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32775. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32776. }
  32777. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32778. };
  32779. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32780. this._currentEffect.setMatrix3x3(name, matrix);
  32781. };
  32782. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32783. this._currentEffect.setMatrix2x2(name, matrix);
  32784. };
  32785. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32786. // To match std140, matrix must be realigned
  32787. for (var i = 0; i < 2; i++) {
  32788. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32789. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32790. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32791. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32792. }
  32793. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32794. };
  32795. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32796. this._currentEffect.setFloat(name, x);
  32797. };
  32798. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32799. UniformBuffer._tempBuffer[0] = x;
  32800. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32801. };
  32802. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32803. if (suffix === void 0) { suffix = ""; }
  32804. this._currentEffect.setFloat2(name + suffix, x, y);
  32805. };
  32806. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32807. if (suffix === void 0) { suffix = ""; }
  32808. UniformBuffer._tempBuffer[0] = x;
  32809. UniformBuffer._tempBuffer[1] = y;
  32810. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32811. };
  32812. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32813. if (suffix === void 0) { suffix = ""; }
  32814. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32815. };
  32816. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32817. if (suffix === void 0) { suffix = ""; }
  32818. UniformBuffer._tempBuffer[0] = x;
  32819. UniformBuffer._tempBuffer[1] = y;
  32820. UniformBuffer._tempBuffer[2] = z;
  32821. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32822. };
  32823. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32824. if (suffix === void 0) { suffix = ""; }
  32825. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32826. };
  32827. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32828. if (suffix === void 0) { suffix = ""; }
  32829. UniformBuffer._tempBuffer[0] = x;
  32830. UniformBuffer._tempBuffer[1] = y;
  32831. UniformBuffer._tempBuffer[2] = z;
  32832. UniformBuffer._tempBuffer[3] = w;
  32833. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32834. };
  32835. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32836. this._currentEffect.setMatrix(name, mat);
  32837. };
  32838. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32839. this.updateUniform(name, mat.toArray(), 16);
  32840. };
  32841. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32842. this._currentEffect.setVector3(name, vector);
  32843. };
  32844. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32845. vector.toArray(UniformBuffer._tempBuffer);
  32846. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32847. };
  32848. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32849. this._currentEffect.setVector4(name, vector);
  32850. };
  32851. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32852. vector.toArray(UniformBuffer._tempBuffer);
  32853. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32854. };
  32855. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32856. if (suffix === void 0) { suffix = ""; }
  32857. this._currentEffect.setColor3(name + suffix, color);
  32858. };
  32859. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32860. if (suffix === void 0) { suffix = ""; }
  32861. color.toArray(UniformBuffer._tempBuffer);
  32862. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32863. };
  32864. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32865. if (suffix === void 0) { suffix = ""; }
  32866. this._currentEffect.setColor4(name + suffix, color, alpha);
  32867. };
  32868. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32869. if (suffix === void 0) { suffix = ""; }
  32870. color.toArray(UniformBuffer._tempBuffer);
  32871. UniformBuffer._tempBuffer[3] = alpha;
  32872. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32873. };
  32874. /**
  32875. * Sets a sampler uniform on the effect.
  32876. * @param {string} name Name of the sampler.
  32877. * @param {Texture} texture
  32878. */
  32879. UniformBuffer.prototype.setTexture = function (name, texture) {
  32880. this._currentEffect.setTexture(name, texture);
  32881. };
  32882. /**
  32883. * Directly updates the value of the uniform in the cache AND on the GPU.
  32884. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32885. * @param {number[]|Float32Array} data Flattened data
  32886. */
  32887. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32888. this.updateUniform(uniformName, data, data.length);
  32889. this.update();
  32890. };
  32891. /**
  32892. * Binds this uniform buffer to an effect.
  32893. * @param {Effect} effect
  32894. * @param {string} name Name of the uniform block in the shader.
  32895. */
  32896. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32897. this._currentEffect = effect;
  32898. if (this._noUBO || !this._buffer) {
  32899. return;
  32900. }
  32901. effect.bindUniformBuffer(this._buffer, name);
  32902. };
  32903. /**
  32904. * Disposes the uniform buffer.
  32905. */
  32906. UniformBuffer.prototype.dispose = function () {
  32907. if (this._noUBO) {
  32908. return;
  32909. }
  32910. var index = this._engine._uniformBuffers.indexOf(this);
  32911. if (index !== -1) {
  32912. this._engine._uniformBuffers.splice(index, 1);
  32913. }
  32914. if (!this._buffer) {
  32915. return;
  32916. }
  32917. if (this._engine._releaseBuffer(this._buffer)) {
  32918. this._buffer = null;
  32919. }
  32920. };
  32921. // Pool for avoiding memory leaks
  32922. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32923. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32924. return UniformBuffer;
  32925. }());
  32926. BABYLON.UniformBuffer = UniformBuffer;
  32927. })(BABYLON || (BABYLON = {}));
  32928. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32929. "use strict";
  32930. var BABYLON;
  32931. (function (BABYLON) {
  32932. var VertexData = /** @class */ (function () {
  32933. function VertexData() {
  32934. }
  32935. VertexData.prototype.set = function (data, kind) {
  32936. switch (kind) {
  32937. case BABYLON.VertexBuffer.PositionKind:
  32938. this.positions = data;
  32939. break;
  32940. case BABYLON.VertexBuffer.NormalKind:
  32941. this.normals = data;
  32942. break;
  32943. case BABYLON.VertexBuffer.TangentKind:
  32944. this.tangents = data;
  32945. break;
  32946. case BABYLON.VertexBuffer.UVKind:
  32947. this.uvs = data;
  32948. break;
  32949. case BABYLON.VertexBuffer.UV2Kind:
  32950. this.uvs2 = data;
  32951. break;
  32952. case BABYLON.VertexBuffer.UV3Kind:
  32953. this.uvs3 = data;
  32954. break;
  32955. case BABYLON.VertexBuffer.UV4Kind:
  32956. this.uvs4 = data;
  32957. break;
  32958. case BABYLON.VertexBuffer.UV5Kind:
  32959. this.uvs5 = data;
  32960. break;
  32961. case BABYLON.VertexBuffer.UV6Kind:
  32962. this.uvs6 = data;
  32963. break;
  32964. case BABYLON.VertexBuffer.ColorKind:
  32965. this.colors = data;
  32966. break;
  32967. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32968. this.matricesIndices = data;
  32969. break;
  32970. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32971. this.matricesWeights = data;
  32972. break;
  32973. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32974. this.matricesIndicesExtra = data;
  32975. break;
  32976. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32977. this.matricesWeightsExtra = data;
  32978. break;
  32979. }
  32980. };
  32981. /**
  32982. * Associates the vertexData to the passed Mesh.
  32983. * Sets it as updatable or not (default `false`).
  32984. * Returns the VertexData.
  32985. */
  32986. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32987. this._applyTo(mesh, updatable);
  32988. return this;
  32989. };
  32990. /**
  32991. * Associates the vertexData to the passed Geometry.
  32992. * Sets it as updatable or not (default `false`).
  32993. * Returns the VertexData.
  32994. */
  32995. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32996. this._applyTo(geometry, updatable);
  32997. return this;
  32998. };
  32999. /**
  33000. * Updates the associated mesh.
  33001. * Returns the VertexData.
  33002. */
  33003. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33004. this._update(mesh);
  33005. return this;
  33006. };
  33007. /**
  33008. * Updates the associated geometry.
  33009. * Returns the VertexData.
  33010. */
  33011. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33012. this._update(geometry);
  33013. return this;
  33014. };
  33015. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33016. if (updatable === void 0) { updatable = false; }
  33017. if (this.positions) {
  33018. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33019. }
  33020. if (this.normals) {
  33021. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33022. }
  33023. if (this.tangents) {
  33024. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  33025. }
  33026. if (this.uvs) {
  33027. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33028. }
  33029. if (this.uvs2) {
  33030. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33031. }
  33032. if (this.uvs3) {
  33033. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33034. }
  33035. if (this.uvs4) {
  33036. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33037. }
  33038. if (this.uvs5) {
  33039. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33040. }
  33041. if (this.uvs6) {
  33042. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33043. }
  33044. if (this.colors) {
  33045. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33046. }
  33047. if (this.matricesIndices) {
  33048. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33049. }
  33050. if (this.matricesWeights) {
  33051. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33052. }
  33053. if (this.matricesIndicesExtra) {
  33054. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33055. }
  33056. if (this.matricesWeightsExtra) {
  33057. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33058. }
  33059. if (this.indices) {
  33060. meshOrGeometry.setIndices(this.indices, null, updatable);
  33061. }
  33062. return this;
  33063. };
  33064. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33065. if (this.positions) {
  33066. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33067. }
  33068. if (this.normals) {
  33069. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33070. }
  33071. if (this.tangents) {
  33072. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33073. }
  33074. if (this.uvs) {
  33075. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33076. }
  33077. if (this.uvs2) {
  33078. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33079. }
  33080. if (this.uvs3) {
  33081. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33082. }
  33083. if (this.uvs4) {
  33084. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33085. }
  33086. if (this.uvs5) {
  33087. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33088. }
  33089. if (this.uvs6) {
  33090. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33091. }
  33092. if (this.colors) {
  33093. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33094. }
  33095. if (this.matricesIndices) {
  33096. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33097. }
  33098. if (this.matricesWeights) {
  33099. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33100. }
  33101. if (this.matricesIndicesExtra) {
  33102. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33103. }
  33104. if (this.matricesWeightsExtra) {
  33105. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33106. }
  33107. if (this.indices) {
  33108. meshOrGeometry.setIndices(this.indices, null);
  33109. }
  33110. return this;
  33111. };
  33112. /**
  33113. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33114. * Returns the VertexData.
  33115. */
  33116. VertexData.prototype.transform = function (matrix) {
  33117. var transformed = BABYLON.Vector3.Zero();
  33118. var index;
  33119. if (this.positions) {
  33120. var position = BABYLON.Vector3.Zero();
  33121. for (index = 0; index < this.positions.length; index += 3) {
  33122. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33123. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33124. this.positions[index] = transformed.x;
  33125. this.positions[index + 1] = transformed.y;
  33126. this.positions[index + 2] = transformed.z;
  33127. }
  33128. }
  33129. if (this.normals) {
  33130. var normal = BABYLON.Vector3.Zero();
  33131. for (index = 0; index < this.normals.length; index += 3) {
  33132. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33133. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33134. this.normals[index] = transformed.x;
  33135. this.normals[index + 1] = transformed.y;
  33136. this.normals[index + 2] = transformed.z;
  33137. }
  33138. }
  33139. if (this.tangents) {
  33140. var tangent = BABYLON.Vector4.Zero();
  33141. var tangentTransformed = BABYLON.Vector4.Zero();
  33142. for (index = 0; index < this.tangents.length; index += 4) {
  33143. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33144. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33145. this.tangents[index] = tangentTransformed.x;
  33146. this.tangents[index + 1] = tangentTransformed.y;
  33147. this.tangents[index + 2] = tangentTransformed.z;
  33148. this.tangents[index + 3] = tangentTransformed.w;
  33149. }
  33150. }
  33151. return this;
  33152. };
  33153. /**
  33154. * Merges the passed VertexData into the current one.
  33155. * Returns the modified VertexData.
  33156. */
  33157. VertexData.prototype.merge = function (other) {
  33158. this._validate();
  33159. other._validate();
  33160. if (!this.normals !== !other.normals ||
  33161. !this.tangents !== !other.tangents ||
  33162. !this.uvs !== !other.uvs ||
  33163. !this.uvs2 !== !other.uvs2 ||
  33164. !this.uvs3 !== !other.uvs3 ||
  33165. !this.uvs4 !== !other.uvs4 ||
  33166. !this.uvs5 !== !other.uvs5 ||
  33167. !this.uvs6 !== !other.uvs6 ||
  33168. !this.colors !== !other.colors ||
  33169. !this.matricesIndices !== !other.matricesIndices ||
  33170. !this.matricesWeights !== !other.matricesWeights ||
  33171. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33172. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33173. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33174. }
  33175. if (other.indices) {
  33176. if (!this.indices) {
  33177. this.indices = [];
  33178. }
  33179. var offset = this.positions ? this.positions.length / 3 : 0;
  33180. for (var index = 0; index < other.indices.length; index++) {
  33181. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33182. this.indices.push(other.indices[index] + offset);
  33183. }
  33184. }
  33185. this.positions = this._mergeElement(this.positions, other.positions);
  33186. this.normals = this._mergeElement(this.normals, other.normals);
  33187. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33188. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33189. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33190. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33191. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33192. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33193. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33194. this.colors = this._mergeElement(this.colors, other.colors);
  33195. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33196. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33197. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33198. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33199. return this;
  33200. };
  33201. VertexData.prototype._mergeElement = function (source, other) {
  33202. if (!source) {
  33203. return other;
  33204. }
  33205. if (!other) {
  33206. return source;
  33207. }
  33208. var len = other.length + source.length;
  33209. var isSrcTypedArray = source instanceof Float32Array;
  33210. var isOthTypedArray = other instanceof Float32Array;
  33211. // use non-loop method when the source is Float32Array
  33212. if (isSrcTypedArray) {
  33213. var ret32 = new Float32Array(len);
  33214. ret32.set(source);
  33215. ret32.set(other, source.length);
  33216. return ret32;
  33217. // source is number[], when other is also use concat
  33218. }
  33219. else if (!isOthTypedArray) {
  33220. return source.concat(other);
  33221. // source is a number[], but other is a Float32Array, loop required
  33222. }
  33223. else {
  33224. var ret = source.slice(0); // copy source to a separate array
  33225. for (var i = 0, len = other.length; i < len; i++) {
  33226. ret.push(other[i]);
  33227. }
  33228. return ret;
  33229. }
  33230. };
  33231. VertexData.prototype._validate = function () {
  33232. if (!this.positions) {
  33233. throw new Error("Positions are required");
  33234. }
  33235. var getElementCount = function (kind, values) {
  33236. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33237. if ((values.length % stride) !== 0) {
  33238. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33239. }
  33240. return values.length / stride;
  33241. };
  33242. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33243. var validateElementCount = function (kind, values) {
  33244. var elementCount = getElementCount(kind, values);
  33245. if (elementCount !== positionsElementCount) {
  33246. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33247. }
  33248. };
  33249. if (this.normals)
  33250. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33251. if (this.tangents)
  33252. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33253. if (this.uvs)
  33254. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33255. if (this.uvs2)
  33256. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33257. if (this.uvs3)
  33258. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33259. if (this.uvs4)
  33260. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33261. if (this.uvs5)
  33262. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33263. if (this.uvs6)
  33264. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33265. if (this.colors)
  33266. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33267. if (this.matricesIndices)
  33268. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33269. if (this.matricesWeights)
  33270. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33271. if (this.matricesIndicesExtra)
  33272. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33273. if (this.matricesWeightsExtra)
  33274. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33275. };
  33276. /**
  33277. * Serializes the VertexData.
  33278. * Returns a serialized object.
  33279. */
  33280. VertexData.prototype.serialize = function () {
  33281. var serializationObject = this.serialize();
  33282. if (this.positions) {
  33283. serializationObject.positions = this.positions;
  33284. }
  33285. if (this.normals) {
  33286. serializationObject.normals = this.normals;
  33287. }
  33288. if (this.tangents) {
  33289. serializationObject.tangents = this.tangents;
  33290. }
  33291. if (this.uvs) {
  33292. serializationObject.uvs = this.uvs;
  33293. }
  33294. if (this.uvs2) {
  33295. serializationObject.uvs2 = this.uvs2;
  33296. }
  33297. if (this.uvs3) {
  33298. serializationObject.uvs3 = this.uvs3;
  33299. }
  33300. if (this.uvs4) {
  33301. serializationObject.uvs4 = this.uvs4;
  33302. }
  33303. if (this.uvs5) {
  33304. serializationObject.uvs5 = this.uvs5;
  33305. }
  33306. if (this.uvs6) {
  33307. serializationObject.uvs6 = this.uvs6;
  33308. }
  33309. if (this.colors) {
  33310. serializationObject.colors = this.colors;
  33311. }
  33312. if (this.matricesIndices) {
  33313. serializationObject.matricesIndices = this.matricesIndices;
  33314. serializationObject.matricesIndices._isExpanded = true;
  33315. }
  33316. if (this.matricesWeights) {
  33317. serializationObject.matricesWeights = this.matricesWeights;
  33318. }
  33319. if (this.matricesIndicesExtra) {
  33320. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33321. serializationObject.matricesIndicesExtra._isExpanded = true;
  33322. }
  33323. if (this.matricesWeightsExtra) {
  33324. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33325. }
  33326. serializationObject.indices = this.indices;
  33327. return serializationObject;
  33328. };
  33329. // Statics
  33330. /**
  33331. * Returns the object VertexData associated to the passed mesh.
  33332. */
  33333. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33334. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33335. };
  33336. /**
  33337. * Returns the object VertexData associated to the passed geometry.
  33338. */
  33339. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33340. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33341. };
  33342. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33343. var result = new VertexData();
  33344. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33345. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33346. }
  33347. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33348. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33349. }
  33350. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33351. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33352. }
  33353. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33354. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33355. }
  33356. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33357. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33358. }
  33359. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33360. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33361. }
  33362. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33363. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33364. }
  33365. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33366. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33367. }
  33368. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33369. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33370. }
  33371. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33372. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33373. }
  33374. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33375. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33376. }
  33377. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33378. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33379. }
  33380. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33381. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33382. }
  33383. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33384. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33385. }
  33386. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33387. return result;
  33388. };
  33389. /**
  33390. * Creates the vertexData of the Ribbon.
  33391. */
  33392. VertexData.CreateRibbon = function (options) {
  33393. var pathArray = options.pathArray;
  33394. var closeArray = options.closeArray || false;
  33395. var closePath = options.closePath || false;
  33396. var invertUV = options.invertUV || false;
  33397. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33398. var offset = options.offset || defaultOffset;
  33399. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33400. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33401. var customUV = options.uvs;
  33402. var customColors = options.colors;
  33403. var positions = [];
  33404. var indices = [];
  33405. var normals = [];
  33406. var uvs = [];
  33407. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33408. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33409. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33410. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33411. var minlg; // minimal length among all paths from pathArray
  33412. var lg = []; // array of path lengths : nb of vertex per path
  33413. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33414. var p; // path iterator
  33415. var i; // point iterator
  33416. var j; // point iterator
  33417. // if single path in pathArray
  33418. if (pathArray.length < 2) {
  33419. var ar1 = [];
  33420. var ar2 = [];
  33421. for (i = 0; i < pathArray[0].length - offset; i++) {
  33422. ar1.push(pathArray[0][i]);
  33423. ar2.push(pathArray[0][i + offset]);
  33424. }
  33425. pathArray = [ar1, ar2];
  33426. }
  33427. // positions and horizontal distances (u)
  33428. var idc = 0;
  33429. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33430. var path;
  33431. var l;
  33432. minlg = pathArray[0].length;
  33433. var vectlg;
  33434. var dist;
  33435. for (p = 0; p < pathArray.length; p++) {
  33436. uTotalDistance[p] = 0;
  33437. us[p] = [0];
  33438. path = pathArray[p];
  33439. l = path.length;
  33440. minlg = (minlg < l) ? minlg : l;
  33441. j = 0;
  33442. while (j < l) {
  33443. positions.push(path[j].x, path[j].y, path[j].z);
  33444. if (j > 0) {
  33445. vectlg = path[j].subtract(path[j - 1]).length();
  33446. dist = vectlg + uTotalDistance[p];
  33447. us[p].push(dist);
  33448. uTotalDistance[p] = dist;
  33449. }
  33450. j++;
  33451. }
  33452. if (closePath) {
  33453. j--;
  33454. positions.push(path[0].x, path[0].y, path[0].z);
  33455. vectlg = path[j].subtract(path[0]).length();
  33456. dist = vectlg + uTotalDistance[p];
  33457. us[p].push(dist);
  33458. uTotalDistance[p] = dist;
  33459. }
  33460. lg[p] = l + closePathCorr;
  33461. idx[p] = idc;
  33462. idc += (l + closePathCorr);
  33463. }
  33464. // vertical distances (v)
  33465. var path1;
  33466. var path2;
  33467. var vertex1 = null;
  33468. var vertex2 = null;
  33469. for (i = 0; i < minlg + closePathCorr; i++) {
  33470. vTotalDistance[i] = 0;
  33471. vs[i] = [0];
  33472. for (p = 0; p < pathArray.length - 1; p++) {
  33473. path1 = pathArray[p];
  33474. path2 = pathArray[p + 1];
  33475. if (i === minlg) {
  33476. vertex1 = path1[0];
  33477. vertex2 = path2[0];
  33478. }
  33479. else {
  33480. vertex1 = path1[i];
  33481. vertex2 = path2[i];
  33482. }
  33483. vectlg = vertex2.subtract(vertex1).length();
  33484. dist = vectlg + vTotalDistance[i];
  33485. vs[i].push(dist);
  33486. vTotalDistance[i] = dist;
  33487. }
  33488. if (closeArray && vertex2 && vertex1) {
  33489. path1 = pathArray[p];
  33490. path2 = pathArray[0];
  33491. if (i === minlg) {
  33492. vertex2 = path2[0];
  33493. }
  33494. vectlg = vertex2.subtract(vertex1).length();
  33495. dist = vectlg + vTotalDistance[i];
  33496. vTotalDistance[i] = dist;
  33497. }
  33498. }
  33499. // uvs
  33500. var u;
  33501. var v;
  33502. if (customUV) {
  33503. for (p = 0; p < customUV.length; p++) {
  33504. uvs.push(customUV[p].x, customUV[p].y);
  33505. }
  33506. }
  33507. else {
  33508. for (p = 0; p < pathArray.length; p++) {
  33509. for (i = 0; i < minlg + closePathCorr; i++) {
  33510. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33511. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33512. if (invertUV) {
  33513. uvs.push(v, u);
  33514. }
  33515. else {
  33516. uvs.push(u, v);
  33517. }
  33518. }
  33519. }
  33520. }
  33521. // indices
  33522. p = 0; // path index
  33523. var pi = 0; // positions array index
  33524. var l1 = lg[p] - 1; // path1 length
  33525. var l2 = lg[p + 1] - 1; // path2 length
  33526. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33527. var shft = idx[1] - idx[0]; // shift
  33528. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33529. while (pi <= min && p < path1nb) {
  33530. // 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
  33531. indices.push(pi, pi + shft, pi + 1);
  33532. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33533. pi += 1;
  33534. if (pi === min) {
  33535. p++;
  33536. if (p === lg.length - 1) {
  33537. shft = idx[0] - idx[p];
  33538. l1 = lg[p] - 1;
  33539. l2 = lg[0] - 1;
  33540. }
  33541. else {
  33542. shft = idx[p + 1] - idx[p];
  33543. l1 = lg[p] - 1;
  33544. l2 = lg[p + 1] - 1;
  33545. }
  33546. pi = idx[p];
  33547. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33548. }
  33549. }
  33550. // normals
  33551. VertexData.ComputeNormals(positions, indices, normals);
  33552. if (closePath) {
  33553. var indexFirst = 0;
  33554. var indexLast = 0;
  33555. for (p = 0; p < pathArray.length; p++) {
  33556. indexFirst = idx[p] * 3;
  33557. if (p + 1 < pathArray.length) {
  33558. indexLast = (idx[p + 1] - 1) * 3;
  33559. }
  33560. else {
  33561. indexLast = normals.length - 3;
  33562. }
  33563. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33564. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33565. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33566. normals[indexLast] = normals[indexFirst];
  33567. normals[indexLast + 1] = normals[indexFirst + 1];
  33568. normals[indexLast + 2] = normals[indexFirst + 2];
  33569. }
  33570. }
  33571. // sides
  33572. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33573. // Colors
  33574. var colors = null;
  33575. if (customColors) {
  33576. colors = new Float32Array(customColors.length * 4);
  33577. for (var c = 0; c < customColors.length; c++) {
  33578. colors[c * 4] = customColors[c].r;
  33579. colors[c * 4 + 1] = customColors[c].g;
  33580. colors[c * 4 + 2] = customColors[c].b;
  33581. colors[c * 4 + 3] = customColors[c].a;
  33582. }
  33583. }
  33584. // Result
  33585. var vertexData = new VertexData();
  33586. var positions32 = new Float32Array(positions);
  33587. var normals32 = new Float32Array(normals);
  33588. var uvs32 = new Float32Array(uvs);
  33589. vertexData.indices = indices;
  33590. vertexData.positions = positions32;
  33591. vertexData.normals = normals32;
  33592. vertexData.uvs = uvs32;
  33593. if (colors) {
  33594. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33595. }
  33596. if (closePath) {
  33597. vertexData._idx = idx;
  33598. }
  33599. return vertexData;
  33600. };
  33601. /**
  33602. * Creates the VertexData of the Box.
  33603. */
  33604. VertexData.CreateBox = function (options) {
  33605. var normalsSource = [
  33606. new BABYLON.Vector3(0, 0, 1),
  33607. new BABYLON.Vector3(0, 0, -1),
  33608. new BABYLON.Vector3(1, 0, 0),
  33609. new BABYLON.Vector3(-1, 0, 0),
  33610. new BABYLON.Vector3(0, 1, 0),
  33611. new BABYLON.Vector3(0, -1, 0)
  33612. ];
  33613. var indices = [];
  33614. var positions = [];
  33615. var normals = [];
  33616. var uvs = [];
  33617. var width = options.width || options.size || 1;
  33618. var height = options.height || options.size || 1;
  33619. var depth = options.depth || options.size || 1;
  33620. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33621. var faceUV = options.faceUV || new Array(6);
  33622. var faceColors = options.faceColors;
  33623. var colors = [];
  33624. // default face colors and UV if undefined
  33625. for (var f = 0; f < 6; f++) {
  33626. if (faceUV[f] === undefined) {
  33627. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33628. }
  33629. if (faceColors && faceColors[f] === undefined) {
  33630. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33631. }
  33632. }
  33633. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33634. // Create each face in turn.
  33635. for (var index = 0; index < normalsSource.length; index++) {
  33636. var normal = normalsSource[index];
  33637. // Get two vectors perpendicular to the face normal and to each other.
  33638. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33639. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33640. // Six indices (two triangles) per face.
  33641. var verticesLength = positions.length / 3;
  33642. indices.push(verticesLength);
  33643. indices.push(verticesLength + 1);
  33644. indices.push(verticesLength + 2);
  33645. indices.push(verticesLength);
  33646. indices.push(verticesLength + 2);
  33647. indices.push(verticesLength + 3);
  33648. // Four vertices per face.
  33649. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33650. positions.push(vertex.x, vertex.y, vertex.z);
  33651. normals.push(normal.x, normal.y, normal.z);
  33652. uvs.push(faceUV[index].z, faceUV[index].w);
  33653. if (faceColors) {
  33654. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33655. }
  33656. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33657. positions.push(vertex.x, vertex.y, vertex.z);
  33658. normals.push(normal.x, normal.y, normal.z);
  33659. uvs.push(faceUV[index].x, faceUV[index].w);
  33660. if (faceColors) {
  33661. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33662. }
  33663. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33664. positions.push(vertex.x, vertex.y, vertex.z);
  33665. normals.push(normal.x, normal.y, normal.z);
  33666. uvs.push(faceUV[index].x, faceUV[index].y);
  33667. if (faceColors) {
  33668. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33669. }
  33670. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33671. positions.push(vertex.x, vertex.y, vertex.z);
  33672. normals.push(normal.x, normal.y, normal.z);
  33673. uvs.push(faceUV[index].z, faceUV[index].y);
  33674. if (faceColors) {
  33675. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33676. }
  33677. }
  33678. // sides
  33679. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33680. // Result
  33681. var vertexData = new VertexData();
  33682. vertexData.indices = indices;
  33683. vertexData.positions = positions;
  33684. vertexData.normals = normals;
  33685. vertexData.uvs = uvs;
  33686. if (faceColors) {
  33687. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33688. vertexData.colors = totalColors;
  33689. }
  33690. return vertexData;
  33691. };
  33692. /**
  33693. * Creates the VertexData of the Sphere.
  33694. */
  33695. VertexData.CreateSphere = function (options) {
  33696. var segments = options.segments || 32;
  33697. var diameterX = options.diameterX || options.diameter || 1;
  33698. var diameterY = options.diameterY || options.diameter || 1;
  33699. var diameterZ = options.diameterZ || options.diameter || 1;
  33700. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33701. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33702. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33703. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33704. var totalZRotationSteps = 2 + segments;
  33705. var totalYRotationSteps = 2 * totalZRotationSteps;
  33706. var indices = [];
  33707. var positions = [];
  33708. var normals = [];
  33709. var uvs = [];
  33710. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33711. var normalizedZ = zRotationStep / totalZRotationSteps;
  33712. var angleZ = normalizedZ * Math.PI * slice;
  33713. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33714. var normalizedY = yRotationStep / totalYRotationSteps;
  33715. var angleY = normalizedY * Math.PI * 2 * arc;
  33716. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33717. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33718. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33719. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33720. var vertex = complete.multiply(radius);
  33721. var normal = complete.divide(radius).normalize();
  33722. positions.push(vertex.x, vertex.y, vertex.z);
  33723. normals.push(normal.x, normal.y, normal.z);
  33724. uvs.push(normalizedY, normalizedZ);
  33725. }
  33726. if (zRotationStep > 0) {
  33727. var verticesCount = positions.length / 3;
  33728. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33729. indices.push((firstIndex));
  33730. indices.push((firstIndex + 1));
  33731. indices.push(firstIndex + totalYRotationSteps + 1);
  33732. indices.push((firstIndex + totalYRotationSteps + 1));
  33733. indices.push((firstIndex + 1));
  33734. indices.push((firstIndex + totalYRotationSteps + 2));
  33735. }
  33736. }
  33737. }
  33738. // Sides
  33739. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33740. // Result
  33741. var vertexData = new VertexData();
  33742. vertexData.indices = indices;
  33743. vertexData.positions = positions;
  33744. vertexData.normals = normals;
  33745. vertexData.uvs = uvs;
  33746. return vertexData;
  33747. };
  33748. /**
  33749. * Creates the VertexData of the Cylinder or Cone.
  33750. */
  33751. VertexData.CreateCylinder = function (options) {
  33752. var height = options.height || 2;
  33753. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33754. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33755. var tessellation = options.tessellation || 24;
  33756. var subdivisions = options.subdivisions || 1;
  33757. var hasRings = options.hasRings ? true : false;
  33758. var enclose = options.enclose ? true : false;
  33759. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33760. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33761. var faceUV = options.faceUV || new Array(3);
  33762. var faceColors = options.faceColors;
  33763. // default face colors and UV if undefined
  33764. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33765. var ringNb = (hasRings) ? subdivisions : 1;
  33766. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33767. var f;
  33768. for (f = 0; f < surfaceNb; f++) {
  33769. if (faceColors && faceColors[f] === undefined) {
  33770. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33771. }
  33772. }
  33773. for (f = 0; f < surfaceNb; f++) {
  33774. if (faceUV && faceUV[f] === undefined) {
  33775. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33776. }
  33777. }
  33778. var indices = new Array();
  33779. var positions = new Array();
  33780. var normals = new Array();
  33781. var uvs = new Array();
  33782. var colors = new Array();
  33783. var angle_step = Math.PI * 2 * arc / tessellation;
  33784. var angle;
  33785. var h;
  33786. var radius;
  33787. var tan = (diameterBottom - diameterTop) / 2 / height;
  33788. var ringVertex = BABYLON.Vector3.Zero();
  33789. var ringNormal = BABYLON.Vector3.Zero();
  33790. var ringFirstVertex = BABYLON.Vector3.Zero();
  33791. var ringFirstNormal = BABYLON.Vector3.Zero();
  33792. var quadNormal = BABYLON.Vector3.Zero();
  33793. var Y = BABYLON.Axis.Y;
  33794. // positions, normals, uvs
  33795. var i;
  33796. var j;
  33797. var r;
  33798. var ringIdx = 1;
  33799. var s = 1; // surface index
  33800. var cs = 0;
  33801. var v = 0;
  33802. for (i = 0; i <= subdivisions; i++) {
  33803. h = i / subdivisions;
  33804. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33805. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33806. for (r = 0; r < ringIdx; r++) {
  33807. if (hasRings) {
  33808. s += r;
  33809. }
  33810. if (enclose) {
  33811. s += 2 * r;
  33812. }
  33813. for (j = 0; j <= tessellation; j++) {
  33814. angle = j * angle_step;
  33815. // position
  33816. ringVertex.x = Math.cos(-angle) * radius;
  33817. ringVertex.y = -height / 2 + h * height;
  33818. ringVertex.z = Math.sin(-angle) * radius;
  33819. // normal
  33820. if (diameterTop === 0 && i === subdivisions) {
  33821. // if no top cap, reuse former normals
  33822. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33823. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33824. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33825. }
  33826. else {
  33827. ringNormal.x = ringVertex.x;
  33828. ringNormal.z = ringVertex.z;
  33829. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33830. ringNormal.normalize();
  33831. }
  33832. // keep first ring vertex values for enclose
  33833. if (j === 0) {
  33834. ringFirstVertex.copyFrom(ringVertex);
  33835. ringFirstNormal.copyFrom(ringNormal);
  33836. }
  33837. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33838. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33839. if (hasRings) {
  33840. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33841. }
  33842. else {
  33843. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33844. }
  33845. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33846. if (faceColors) {
  33847. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33848. }
  33849. }
  33850. // if enclose, add four vertices and their dedicated normals
  33851. if (arc !== 1 && enclose) {
  33852. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33853. positions.push(0, ringVertex.y, 0);
  33854. positions.push(0, ringVertex.y, 0);
  33855. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33856. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33857. quadNormal.normalize();
  33858. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33859. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33860. quadNormal.normalize();
  33861. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33862. if (hasRings) {
  33863. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33864. }
  33865. else {
  33866. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33867. }
  33868. uvs.push(faceUV[s + 1].x, v);
  33869. uvs.push(faceUV[s + 1].z, v);
  33870. if (hasRings) {
  33871. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33872. }
  33873. else {
  33874. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33875. }
  33876. uvs.push(faceUV[s + 2].x, v);
  33877. uvs.push(faceUV[s + 2].z, v);
  33878. if (faceColors) {
  33879. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33880. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33881. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33882. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33883. }
  33884. }
  33885. if (cs !== s) {
  33886. cs = s;
  33887. }
  33888. }
  33889. }
  33890. // indices
  33891. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33892. var s;
  33893. i = 0;
  33894. for (s = 0; s < subdivisions; s++) {
  33895. var i0 = 0;
  33896. var i1 = 0;
  33897. var i2 = 0;
  33898. var i3 = 0;
  33899. for (j = 0; j < tessellation; j++) {
  33900. i0 = i * (e + 1) + j;
  33901. i1 = (i + 1) * (e + 1) + j;
  33902. i2 = i * (e + 1) + (j + 1);
  33903. i3 = (i + 1) * (e + 1) + (j + 1);
  33904. indices.push(i0, i1, i2);
  33905. indices.push(i3, i2, i1);
  33906. }
  33907. if (arc !== 1 && enclose) {
  33908. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33909. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33910. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33911. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33912. }
  33913. i = (hasRings) ? (i + 2) : (i + 1);
  33914. }
  33915. // Caps
  33916. var createCylinderCap = function (isTop) {
  33917. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33918. if (radius === 0) {
  33919. return;
  33920. }
  33921. // Cap positions, normals & uvs
  33922. var angle;
  33923. var circleVector;
  33924. var i;
  33925. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33926. var c = null;
  33927. if (faceColors) {
  33928. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33929. }
  33930. // cap center
  33931. var vbase = positions.length / 3;
  33932. var offset = isTop ? height / 2 : -height / 2;
  33933. var center = new BABYLON.Vector3(0, offset, 0);
  33934. positions.push(center.x, center.y, center.z);
  33935. normals.push(0, isTop ? 1 : -1, 0);
  33936. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33937. if (c) {
  33938. colors.push(c.r, c.g, c.b, c.a);
  33939. }
  33940. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33941. for (i = 0; i <= tessellation; i++) {
  33942. angle = Math.PI * 2 * i * arc / tessellation;
  33943. var cos = Math.cos(-angle);
  33944. var sin = Math.sin(-angle);
  33945. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33946. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33947. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33948. normals.push(0, isTop ? 1 : -1, 0);
  33949. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33950. if (c) {
  33951. colors.push(c.r, c.g, c.b, c.a);
  33952. }
  33953. }
  33954. // Cap indices
  33955. for (i = 0; i < tessellation; i++) {
  33956. if (!isTop) {
  33957. indices.push(vbase);
  33958. indices.push(vbase + (i + 1));
  33959. indices.push(vbase + (i + 2));
  33960. }
  33961. else {
  33962. indices.push(vbase);
  33963. indices.push(vbase + (i + 2));
  33964. indices.push(vbase + (i + 1));
  33965. }
  33966. }
  33967. };
  33968. // add caps to geometry
  33969. createCylinderCap(false);
  33970. createCylinderCap(true);
  33971. // Sides
  33972. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33973. var vertexData = new VertexData();
  33974. vertexData.indices = indices;
  33975. vertexData.positions = positions;
  33976. vertexData.normals = normals;
  33977. vertexData.uvs = uvs;
  33978. if (faceColors) {
  33979. vertexData.colors = colors;
  33980. }
  33981. return vertexData;
  33982. };
  33983. /**
  33984. * Creates the VertexData of the Torus.
  33985. */
  33986. VertexData.CreateTorus = function (options) {
  33987. var indices = [];
  33988. var positions = [];
  33989. var normals = [];
  33990. var uvs = [];
  33991. var diameter = options.diameter || 1;
  33992. var thickness = options.thickness || 0.5;
  33993. var tessellation = options.tessellation || 16;
  33994. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33995. var stride = tessellation + 1;
  33996. for (var i = 0; i <= tessellation; i++) {
  33997. var u = i / tessellation;
  33998. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33999. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34000. for (var j = 0; j <= tessellation; j++) {
  34001. var v = 1 - j / tessellation;
  34002. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34003. var dx = Math.cos(innerAngle);
  34004. var dy = Math.sin(innerAngle);
  34005. // Create a vertex.
  34006. var normal = new BABYLON.Vector3(dx, dy, 0);
  34007. var position = normal.scale(thickness / 2);
  34008. var textureCoordinate = new BABYLON.Vector2(u, v);
  34009. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34010. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34011. positions.push(position.x, position.y, position.z);
  34012. normals.push(normal.x, normal.y, normal.z);
  34013. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34014. // And create indices for two triangles.
  34015. var nextI = (i + 1) % stride;
  34016. var nextJ = (j + 1) % stride;
  34017. indices.push(i * stride + j);
  34018. indices.push(i * stride + nextJ);
  34019. indices.push(nextI * stride + j);
  34020. indices.push(i * stride + nextJ);
  34021. indices.push(nextI * stride + nextJ);
  34022. indices.push(nextI * stride + j);
  34023. }
  34024. }
  34025. // Sides
  34026. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34027. // Result
  34028. var vertexData = new VertexData();
  34029. vertexData.indices = indices;
  34030. vertexData.positions = positions;
  34031. vertexData.normals = normals;
  34032. vertexData.uvs = uvs;
  34033. return vertexData;
  34034. };
  34035. /**
  34036. * Creates the VertexData of the LineSystem.
  34037. */
  34038. VertexData.CreateLineSystem = function (options) {
  34039. var indices = [];
  34040. var positions = [];
  34041. var lines = options.lines;
  34042. var colors = options.colors;
  34043. var vertexColors = [];
  34044. var idx = 0;
  34045. for (var l = 0; l < lines.length; l++) {
  34046. var points = lines[l];
  34047. for (var index = 0; index < points.length; index++) {
  34048. positions.push(points[index].x, points[index].y, points[index].z);
  34049. if (colors) {
  34050. var color = colors[l];
  34051. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  34052. }
  34053. if (index > 0) {
  34054. indices.push(idx - 1);
  34055. indices.push(idx);
  34056. }
  34057. idx++;
  34058. }
  34059. }
  34060. var vertexData = new VertexData();
  34061. vertexData.indices = indices;
  34062. vertexData.positions = positions;
  34063. if (colors) {
  34064. vertexData.colors = vertexColors;
  34065. }
  34066. return vertexData;
  34067. };
  34068. /**
  34069. * Create the VertexData of the DashedLines.
  34070. */
  34071. VertexData.CreateDashedLines = function (options) {
  34072. var dashSize = options.dashSize || 3;
  34073. var gapSize = options.gapSize || 1;
  34074. var dashNb = options.dashNb || 200;
  34075. var points = options.points;
  34076. var positions = new Array();
  34077. var indices = new Array();
  34078. var curvect = BABYLON.Vector3.Zero();
  34079. var lg = 0;
  34080. var nb = 0;
  34081. var shft = 0;
  34082. var dashshft = 0;
  34083. var curshft = 0;
  34084. var idx = 0;
  34085. var i = 0;
  34086. for (i = 0; i < points.length - 1; i++) {
  34087. points[i + 1].subtractToRef(points[i], curvect);
  34088. lg += curvect.length();
  34089. }
  34090. shft = lg / dashNb;
  34091. dashshft = dashSize * shft / (dashSize + gapSize);
  34092. for (i = 0; i < points.length - 1; i++) {
  34093. points[i + 1].subtractToRef(points[i], curvect);
  34094. nb = Math.floor(curvect.length() / shft);
  34095. curvect.normalize();
  34096. for (var j = 0; j < nb; j++) {
  34097. curshft = shft * j;
  34098. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34099. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34100. indices.push(idx, idx + 1);
  34101. idx += 2;
  34102. }
  34103. }
  34104. // Result
  34105. var vertexData = new VertexData();
  34106. vertexData.positions = positions;
  34107. vertexData.indices = indices;
  34108. return vertexData;
  34109. };
  34110. /**
  34111. * Creates the VertexData of the Ground.
  34112. */
  34113. VertexData.CreateGround = function (options) {
  34114. var indices = [];
  34115. var positions = [];
  34116. var normals = [];
  34117. var uvs = [];
  34118. var row, col;
  34119. var width = options.width || 1;
  34120. var height = options.height || 1;
  34121. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34122. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34123. for (row = 0; row <= subdivisionsY; row++) {
  34124. for (col = 0; col <= subdivisionsX; col++) {
  34125. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34126. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34127. positions.push(position.x, position.y, position.z);
  34128. normals.push(normal.x, normal.y, normal.z);
  34129. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34130. }
  34131. }
  34132. for (row = 0; row < subdivisionsY; row++) {
  34133. for (col = 0; col < subdivisionsX; col++) {
  34134. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34135. indices.push(col + 1 + row * (subdivisionsX + 1));
  34136. indices.push(col + row * (subdivisionsX + 1));
  34137. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34138. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34139. indices.push(col + row * (subdivisionsX + 1));
  34140. }
  34141. }
  34142. // Result
  34143. var vertexData = new VertexData();
  34144. vertexData.indices = indices;
  34145. vertexData.positions = positions;
  34146. vertexData.normals = normals;
  34147. vertexData.uvs = uvs;
  34148. return vertexData;
  34149. };
  34150. /**
  34151. * Creates the VertexData of the TiledGround.
  34152. */
  34153. VertexData.CreateTiledGround = function (options) {
  34154. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34155. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34156. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34157. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34158. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34159. var precision = options.precision || { w: 1, h: 1 };
  34160. var indices = new Array();
  34161. var positions = new Array();
  34162. var normals = new Array();
  34163. var uvs = new Array();
  34164. var row, col, tileRow, tileCol;
  34165. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34166. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34167. precision.w = (precision.w < 1) ? 1 : precision.w;
  34168. precision.h = (precision.h < 1) ? 1 : precision.h;
  34169. var tileSize = {
  34170. 'w': (xmax - xmin) / subdivisions.w,
  34171. 'h': (zmax - zmin) / subdivisions.h
  34172. };
  34173. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34174. // Indices
  34175. var base = positions.length / 3;
  34176. var rowLength = precision.w + 1;
  34177. for (row = 0; row < precision.h; row++) {
  34178. for (col = 0; col < precision.w; col++) {
  34179. var square = [
  34180. base + col + row * rowLength,
  34181. base + (col + 1) + row * rowLength,
  34182. base + (col + 1) + (row + 1) * rowLength,
  34183. base + col + (row + 1) * rowLength
  34184. ];
  34185. indices.push(square[1]);
  34186. indices.push(square[2]);
  34187. indices.push(square[3]);
  34188. indices.push(square[0]);
  34189. indices.push(square[1]);
  34190. indices.push(square[3]);
  34191. }
  34192. }
  34193. // Position, normals and uvs
  34194. var position = BABYLON.Vector3.Zero();
  34195. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34196. for (row = 0; row <= precision.h; row++) {
  34197. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34198. for (col = 0; col <= precision.w; col++) {
  34199. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34200. position.y = 0;
  34201. positions.push(position.x, position.y, position.z);
  34202. normals.push(normal.x, normal.y, normal.z);
  34203. uvs.push(col / precision.w, row / precision.h);
  34204. }
  34205. }
  34206. }
  34207. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34208. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34209. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34210. }
  34211. }
  34212. // Result
  34213. var vertexData = new VertexData();
  34214. vertexData.indices = indices;
  34215. vertexData.positions = positions;
  34216. vertexData.normals = normals;
  34217. vertexData.uvs = uvs;
  34218. return vertexData;
  34219. };
  34220. /**
  34221. * Creates the VertexData of the Ground designed from a heightmap.
  34222. */
  34223. VertexData.CreateGroundFromHeightMap = function (options) {
  34224. var indices = [];
  34225. var positions = [];
  34226. var normals = [];
  34227. var uvs = [];
  34228. var row, col;
  34229. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34230. // Vertices
  34231. for (row = 0; row <= options.subdivisions; row++) {
  34232. for (col = 0; col <= options.subdivisions; col++) {
  34233. 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));
  34234. // Compute height
  34235. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34236. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34237. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34238. var r = options.buffer[pos] / 255.0;
  34239. var g = options.buffer[pos + 1] / 255.0;
  34240. var b = options.buffer[pos + 2] / 255.0;
  34241. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34242. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34243. // Add vertex
  34244. positions.push(position.x, position.y, position.z);
  34245. normals.push(0, 0, 0);
  34246. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34247. }
  34248. }
  34249. // Indices
  34250. for (row = 0; row < options.subdivisions; row++) {
  34251. for (col = 0; col < options.subdivisions; col++) {
  34252. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34253. indices.push(col + 1 + row * (options.subdivisions + 1));
  34254. indices.push(col + row * (options.subdivisions + 1));
  34255. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34256. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34257. indices.push(col + row * (options.subdivisions + 1));
  34258. }
  34259. }
  34260. // Normals
  34261. VertexData.ComputeNormals(positions, indices, normals);
  34262. // Result
  34263. var vertexData = new VertexData();
  34264. vertexData.indices = indices;
  34265. vertexData.positions = positions;
  34266. vertexData.normals = normals;
  34267. vertexData.uvs = uvs;
  34268. return vertexData;
  34269. };
  34270. /**
  34271. * Creates the VertexData of the Plane.
  34272. */
  34273. VertexData.CreatePlane = function (options) {
  34274. var indices = [];
  34275. var positions = [];
  34276. var normals = [];
  34277. var uvs = [];
  34278. var width = options.width || options.size || 1;
  34279. var height = options.height || options.size || 1;
  34280. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34281. // Vertices
  34282. var halfWidth = width / 2.0;
  34283. var halfHeight = height / 2.0;
  34284. positions.push(-halfWidth, -halfHeight, 0);
  34285. normals.push(0, 0, -1.0);
  34286. uvs.push(0.0, 0.0);
  34287. positions.push(halfWidth, -halfHeight, 0);
  34288. normals.push(0, 0, -1.0);
  34289. uvs.push(1.0, 0.0);
  34290. positions.push(halfWidth, halfHeight, 0);
  34291. normals.push(0, 0, -1.0);
  34292. uvs.push(1.0, 1.0);
  34293. positions.push(-halfWidth, halfHeight, 0);
  34294. normals.push(0, 0, -1.0);
  34295. uvs.push(0.0, 1.0);
  34296. // Indices
  34297. indices.push(0);
  34298. indices.push(1);
  34299. indices.push(2);
  34300. indices.push(0);
  34301. indices.push(2);
  34302. indices.push(3);
  34303. // Sides
  34304. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34305. // Result
  34306. var vertexData = new VertexData();
  34307. vertexData.indices = indices;
  34308. vertexData.positions = positions;
  34309. vertexData.normals = normals;
  34310. vertexData.uvs = uvs;
  34311. return vertexData;
  34312. };
  34313. /**
  34314. * Creates the VertexData of the Disc or regular Polygon.
  34315. */
  34316. VertexData.CreateDisc = function (options) {
  34317. var positions = new Array();
  34318. var indices = new Array();
  34319. var normals = new Array();
  34320. var uvs = new Array();
  34321. var radius = options.radius || 0.5;
  34322. var tessellation = options.tessellation || 64;
  34323. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34324. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34325. // positions and uvs
  34326. positions.push(0, 0, 0); // disc center first
  34327. uvs.push(0.5, 0.5);
  34328. var theta = Math.PI * 2 * arc;
  34329. var step = theta / tessellation;
  34330. for (var a = 0; a < theta; a += step) {
  34331. var x = Math.cos(a);
  34332. var y = Math.sin(a);
  34333. var u = (x + 1) / 2;
  34334. var v = (1 - y) / 2;
  34335. positions.push(radius * x, radius * y, 0);
  34336. uvs.push(u, v);
  34337. }
  34338. if (arc === 1) {
  34339. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34340. uvs.push(uvs[2], uvs[3]);
  34341. }
  34342. //indices
  34343. var vertexNb = positions.length / 3;
  34344. for (var i = 1; i < vertexNb - 1; i++) {
  34345. indices.push(i + 1, 0, i);
  34346. }
  34347. // result
  34348. VertexData.ComputeNormals(positions, indices, normals);
  34349. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34350. var vertexData = new VertexData();
  34351. vertexData.indices = indices;
  34352. vertexData.positions = positions;
  34353. vertexData.normals = normals;
  34354. vertexData.uvs = uvs;
  34355. return vertexData;
  34356. };
  34357. /**
  34358. * Re-creates the VertexData of the Polygon for sideOrientation.
  34359. */
  34360. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34361. var faceUV = fUV || new Array(3);
  34362. var faceColors = fColors;
  34363. var colors = [];
  34364. // default face colors and UV if undefined
  34365. for (var f = 0; f < 3; f++) {
  34366. if (faceUV[f] === undefined) {
  34367. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34368. }
  34369. if (faceColors && faceColors[f] === undefined) {
  34370. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34371. }
  34372. }
  34373. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34374. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34375. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34376. var indices = polygon.getIndices();
  34377. // set face colours and textures
  34378. var idx = 0;
  34379. var face = 0;
  34380. for (var index = 0; index < normals.length; index += 3) {
  34381. //Edge Face no. 1
  34382. if (Math.abs(normals[index + 1]) < 0.001) {
  34383. face = 1;
  34384. }
  34385. //Top Face no. 0
  34386. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34387. face = 0;
  34388. }
  34389. //Bottom Face no. 2
  34390. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34391. face = 2;
  34392. }
  34393. idx = index / 3;
  34394. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34395. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34396. if (faceColors) {
  34397. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34398. }
  34399. }
  34400. // sides
  34401. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34402. // Result
  34403. var vertexData = new VertexData();
  34404. vertexData.indices = indices;
  34405. vertexData.positions = positions;
  34406. vertexData.normals = normals;
  34407. vertexData.uvs = uvs;
  34408. if (faceColors) {
  34409. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34410. vertexData.colors = totalColors;
  34411. }
  34412. return vertexData;
  34413. };
  34414. /**
  34415. * Creates the VertexData of the IcoSphere.
  34416. */
  34417. VertexData.CreateIcoSphere = function (options) {
  34418. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34419. var radius = options.radius || 1;
  34420. var flat = (options.flat === undefined) ? true : options.flat;
  34421. var subdivisions = options.subdivisions || 4;
  34422. var radiusX = options.radiusX || radius;
  34423. var radiusY = options.radiusY || radius;
  34424. var radiusZ = options.radiusZ || radius;
  34425. var t = (1 + Math.sqrt(5)) / 2;
  34426. // 12 vertex x,y,z
  34427. var ico_vertices = [
  34428. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34429. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34430. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34431. ];
  34432. // index of 3 vertex makes a face of icopshere
  34433. var ico_indices = [
  34434. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34435. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34436. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34437. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34438. ];
  34439. // vertex for uv have aliased position, not for UV
  34440. var vertices_unalias_id = [
  34441. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34442. // vertex alias
  34443. 0,
  34444. 2,
  34445. 3,
  34446. 3,
  34447. 3,
  34448. 4,
  34449. 7,
  34450. 8,
  34451. 9,
  34452. 9,
  34453. 10,
  34454. 11 // 23: B + 12
  34455. ];
  34456. // uv as integer step (not pixels !)
  34457. var ico_vertexuv = [
  34458. 5, 1, 3, 1, 6, 4, 0, 0,
  34459. 5, 3, 4, 2, 2, 2, 4, 0,
  34460. 2, 0, 1, 1, 6, 0, 6, 2,
  34461. // vertex alias (for same vertex on different faces)
  34462. 0, 4,
  34463. 3, 3,
  34464. 4, 4,
  34465. 3, 1,
  34466. 4, 2,
  34467. 4, 4,
  34468. 0, 2,
  34469. 1, 1,
  34470. 2, 2,
  34471. 3, 3,
  34472. 1, 3,
  34473. 2, 4 // 23: B + 12
  34474. ];
  34475. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34476. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34477. // First island of uv mapping
  34478. // v = 4h 3+ 2
  34479. // v = 3h 9+ 4
  34480. // v = 2h 9+ 5 B
  34481. // v = 1h 9 1 0
  34482. // v = 0h 3 8 7 A
  34483. // u = 0 1 2 3 4 5 6 *a
  34484. // Second island of uv mapping
  34485. // v = 4h 0+ B+ 4+
  34486. // v = 3h A+ 2+
  34487. // v = 2h 7+ 6 3+
  34488. // v = 1h 8+ 3+
  34489. // v = 0h
  34490. // u = 0 1 2 3 4 5 6 *a
  34491. // Face layout on texture UV mapping
  34492. // ============
  34493. // \ 4 /\ 16 / ======
  34494. // \ / \ / /\ 11 /
  34495. // \/ 7 \/ / \ /
  34496. // ======= / 10 \/
  34497. // /\ 17 /\ =======
  34498. // / \ / \ \ 15 /\
  34499. // / 8 \/ 12 \ \ / \
  34500. // ============ \/ 6 \
  34501. // \ 18 /\ ============
  34502. // \ / \ \ 5 /\ 0 /
  34503. // \/ 13 \ \ / \ /
  34504. // ======= \/ 1 \/
  34505. // =============
  34506. // /\ 19 /\ 2 /\
  34507. // / \ / \ / \
  34508. // / 14 \/ 9 \/ 3 \
  34509. // ===================
  34510. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34511. var ustep = 138 / 1024;
  34512. var vstep = 239 / 1024;
  34513. var uoffset = 60 / 1024;
  34514. var voffset = 26 / 1024;
  34515. // Second island should have margin, not to touch the first island
  34516. // avoid any borderline artefact in pixel rounding
  34517. var island_u_offset = -40 / 1024;
  34518. var island_v_offset = +20 / 1024;
  34519. // face is either island 0 or 1 :
  34520. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34521. var island = [
  34522. 0, 0, 0, 0, 1,
  34523. 0, 0, 1, 1, 0,
  34524. 0, 0, 1, 1, 0,
  34525. 0, 1, 1, 1, 0 // 15 - 19
  34526. ];
  34527. var indices = new Array();
  34528. var positions = new Array();
  34529. var normals = new Array();
  34530. var uvs = new Array();
  34531. var current_indice = 0;
  34532. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34533. var face_vertex_pos = new Array(3);
  34534. var face_vertex_uv = new Array(3);
  34535. var v012;
  34536. for (v012 = 0; v012 < 3; v012++) {
  34537. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34538. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34539. }
  34540. // create all with normals
  34541. for (var face = 0; face < 20; face++) {
  34542. // 3 vertex per face
  34543. for (v012 = 0; v012 < 3; v012++) {
  34544. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34545. var v_id = ico_indices[3 * face + v012];
  34546. // vertex have 3D position (x,y,z)
  34547. 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]);
  34548. // Normalize to get normal, then scale to radius
  34549. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34550. // uv Coordinates from vertex ID
  34551. 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);
  34552. }
  34553. // Subdivide the face (interpolate pos, norm, uv)
  34554. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34555. // - norm is linear interpolation of vertex corner normal
  34556. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34557. // - uv is linear interpolation
  34558. //
  34559. // Topology is as below for sub-divide by 2
  34560. // vertex shown as v0,v1,v2
  34561. // interp index is i1 to progress in range [v0,v1[
  34562. // interp index is i2 to progress in range [v0,v2[
  34563. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34564. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34565. //
  34566. //
  34567. // i2 v2
  34568. // ^ ^
  34569. // / / \
  34570. // / / \
  34571. // / / \
  34572. // / / (0,1) \
  34573. // / #---------\
  34574. // / / \ (0,0)'/ \
  34575. // / / \ / \
  34576. // / / \ / \
  34577. // / / (0,0) \ / (1,0) \
  34578. // / #---------#---------\
  34579. // v0 v1
  34580. //
  34581. // --------------------> i1
  34582. //
  34583. // interp of (i1,i2):
  34584. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34585. // along i1 : lerp(x0,x1, i1/(S-i2))
  34586. //
  34587. // centroid of triangle is needed to get help normal computation
  34588. // (c1,c2) are used for centroid location
  34589. var interp_vertex = function (i1, i2, c1, c2) {
  34590. // vertex is interpolated from
  34591. // - face_vertex_pos[0..2]
  34592. // - face_vertex_uv[0..2]
  34593. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34594. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34595. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34596. pos_interp.normalize();
  34597. var vertex_normal;
  34598. if (flat) {
  34599. // in flat mode, recalculate normal as face centroid normal
  34600. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34601. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34602. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34603. }
  34604. else {
  34605. // in smooth mode, recalculate normal from each single vertex position
  34606. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34607. }
  34608. // Vertex normal need correction due to X,Y,Z radius scaling
  34609. vertex_normal.x /= radiusX;
  34610. vertex_normal.y /= radiusY;
  34611. vertex_normal.z /= radiusZ;
  34612. vertex_normal.normalize();
  34613. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34614. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34615. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34616. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34617. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34618. uvs.push(uv_interp.x, uv_interp.y);
  34619. // push each vertex has member of a face
  34620. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34621. indices.push(current_indice);
  34622. current_indice++;
  34623. };
  34624. for (var i2 = 0; i2 < subdivisions; i2++) {
  34625. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34626. // face : (i1,i2) for /\ :
  34627. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34628. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34629. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34630. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34631. if (i1 + i2 + 1 < subdivisions) {
  34632. // face : (i1,i2)' for \/ :
  34633. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34634. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34635. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34636. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34637. }
  34638. }
  34639. }
  34640. }
  34641. // Sides
  34642. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34643. // Result
  34644. var vertexData = new VertexData();
  34645. vertexData.indices = indices;
  34646. vertexData.positions = positions;
  34647. vertexData.normals = normals;
  34648. vertexData.uvs = uvs;
  34649. return vertexData;
  34650. };
  34651. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34652. /**
  34653. * Creates the VertexData of the Polyhedron.
  34654. */
  34655. VertexData.CreatePolyhedron = function (options) {
  34656. // provided polyhedron types :
  34657. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34658. // 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)
  34659. var polyhedra = [];
  34660. 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]] };
  34661. 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]] };
  34662. polyhedra[2] = {
  34663. 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]],
  34664. 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]]
  34665. };
  34666. polyhedra[3] = {
  34667. 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]],
  34668. 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]]
  34669. };
  34670. polyhedra[4] = {
  34671. 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]],
  34672. 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]]
  34673. };
  34674. 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]] };
  34675. 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]] };
  34676. 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]] };
  34677. 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]] };
  34678. 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]] };
  34679. 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]] };
  34680. 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]] };
  34681. 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]] };
  34682. 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]] };
  34683. polyhedra[14] = {
  34684. 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]],
  34685. 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]]
  34686. };
  34687. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34688. var size = options.size;
  34689. var sizeX = options.sizeX || size || 1;
  34690. var sizeY = options.sizeY || size || 1;
  34691. var sizeZ = options.sizeZ || size || 1;
  34692. var data = options.custom || polyhedra[type];
  34693. var nbfaces = data.face.length;
  34694. var faceUV = options.faceUV || new Array(nbfaces);
  34695. var faceColors = options.faceColors;
  34696. var flat = (options.flat === undefined) ? true : options.flat;
  34697. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34698. var positions = new Array();
  34699. var indices = new Array();
  34700. var normals = new Array();
  34701. var uvs = new Array();
  34702. var colors = new Array();
  34703. var index = 0;
  34704. var faceIdx = 0; // face cursor in the array "indexes"
  34705. var indexes = new Array();
  34706. var i = 0;
  34707. var f = 0;
  34708. var u, v, ang, x, y, tmp;
  34709. // default face colors and UV if undefined
  34710. if (flat) {
  34711. for (f = 0; f < nbfaces; f++) {
  34712. if (faceColors && faceColors[f] === undefined) {
  34713. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34714. }
  34715. if (faceUV && faceUV[f] === undefined) {
  34716. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34717. }
  34718. }
  34719. }
  34720. if (!flat) {
  34721. for (i = 0; i < data.vertex.length; i++) {
  34722. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34723. uvs.push(0, 0);
  34724. }
  34725. for (f = 0; f < nbfaces; f++) {
  34726. for (i = 0; i < data.face[f].length - 2; i++) {
  34727. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34728. }
  34729. }
  34730. }
  34731. else {
  34732. for (f = 0; f < nbfaces; f++) {
  34733. var fl = data.face[f].length; // number of vertices of the current face
  34734. ang = 2 * Math.PI / fl;
  34735. x = 0.5 * Math.tan(ang / 2);
  34736. y = 0.5;
  34737. // positions, uvs, colors
  34738. for (i = 0; i < fl; i++) {
  34739. // positions
  34740. 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);
  34741. indexes.push(index);
  34742. index++;
  34743. // uvs
  34744. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34745. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34746. uvs.push(u, v);
  34747. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34748. y = x * Math.sin(ang) + y * Math.cos(ang);
  34749. x = tmp;
  34750. // colors
  34751. if (faceColors) {
  34752. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34753. }
  34754. }
  34755. // indices from indexes
  34756. for (i = 0; i < fl - 2; i++) {
  34757. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34758. }
  34759. faceIdx += fl;
  34760. }
  34761. }
  34762. VertexData.ComputeNormals(positions, indices, normals);
  34763. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34764. var vertexData = new VertexData();
  34765. vertexData.positions = positions;
  34766. vertexData.indices = indices;
  34767. vertexData.normals = normals;
  34768. vertexData.uvs = uvs;
  34769. if (faceColors && flat) {
  34770. vertexData.colors = colors;
  34771. }
  34772. return vertexData;
  34773. };
  34774. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34775. /**
  34776. * Creates the VertexData of the Torus Knot.
  34777. */
  34778. VertexData.CreateTorusKnot = function (options) {
  34779. var indices = new Array();
  34780. var positions = new Array();
  34781. var normals = new Array();
  34782. var uvs = new Array();
  34783. var radius = options.radius || 2;
  34784. var tube = options.tube || 0.5;
  34785. var radialSegments = options.radialSegments || 32;
  34786. var tubularSegments = options.tubularSegments || 32;
  34787. var p = options.p || 2;
  34788. var q = options.q || 3;
  34789. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34790. // Helper
  34791. var getPos = function (angle) {
  34792. var cu = Math.cos(angle);
  34793. var su = Math.sin(angle);
  34794. var quOverP = q / p * angle;
  34795. var cs = Math.cos(quOverP);
  34796. var tx = radius * (2 + cs) * 0.5 * cu;
  34797. var ty = radius * (2 + cs) * su * 0.5;
  34798. var tz = radius * Math.sin(quOverP) * 0.5;
  34799. return new BABYLON.Vector3(tx, ty, tz);
  34800. };
  34801. // Vertices
  34802. var i;
  34803. var j;
  34804. for (i = 0; i <= radialSegments; i++) {
  34805. var modI = i % radialSegments;
  34806. var u = modI / radialSegments * 2 * p * Math.PI;
  34807. var p1 = getPos(u);
  34808. var p2 = getPos(u + 0.01);
  34809. var tang = p2.subtract(p1);
  34810. var n = p2.add(p1);
  34811. var bitan = BABYLON.Vector3.Cross(tang, n);
  34812. n = BABYLON.Vector3.Cross(bitan, tang);
  34813. bitan.normalize();
  34814. n.normalize();
  34815. for (j = 0; j < tubularSegments; j++) {
  34816. var modJ = j % tubularSegments;
  34817. var v = modJ / tubularSegments * 2 * Math.PI;
  34818. var cx = -tube * Math.cos(v);
  34819. var cy = tube * Math.sin(v);
  34820. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34821. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34822. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34823. uvs.push(i / radialSegments);
  34824. uvs.push(j / tubularSegments);
  34825. }
  34826. }
  34827. for (i = 0; i < radialSegments; i++) {
  34828. for (j = 0; j < tubularSegments; j++) {
  34829. var jNext = (j + 1) % tubularSegments;
  34830. var a = i * tubularSegments + j;
  34831. var b = (i + 1) * tubularSegments + j;
  34832. var c = (i + 1) * tubularSegments + jNext;
  34833. var d = i * tubularSegments + jNext;
  34834. indices.push(d);
  34835. indices.push(b);
  34836. indices.push(a);
  34837. indices.push(d);
  34838. indices.push(c);
  34839. indices.push(b);
  34840. }
  34841. }
  34842. // Normals
  34843. VertexData.ComputeNormals(positions, indices, normals);
  34844. // Sides
  34845. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34846. // Result
  34847. var vertexData = new VertexData();
  34848. vertexData.indices = indices;
  34849. vertexData.positions = positions;
  34850. vertexData.normals = normals;
  34851. vertexData.uvs = uvs;
  34852. return vertexData;
  34853. };
  34854. // Tools
  34855. /**
  34856. * @param {any} - positions (number[] or Float32Array)
  34857. * @param {any} - indices (number[] or Uint16Array)
  34858. * @param {any} - normals (number[] or Float32Array)
  34859. * options (optional) :
  34860. * facetPositions : optional array of facet positions (vector3)
  34861. * facetNormals : optional array of facet normals (vector3)
  34862. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34863. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34864. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34865. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34866. * bInfo : optional bounding info, required for facetPartitioning computation
  34867. * useRightHandedSystem: optional boolean to for right handed system computation
  34868. * depthSort : optional boolean to enable the facet depth sort computation
  34869. * distanceTo : optional Vector3 to compute the facet depth from this location
  34870. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34871. */
  34872. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34873. // temporary scalar variables
  34874. var index = 0; // facet index
  34875. var p1p2x = 0.0; // p1p2 vector x coordinate
  34876. var p1p2y = 0.0; // p1p2 vector y coordinate
  34877. var p1p2z = 0.0; // p1p2 vector z coordinate
  34878. var p3p2x = 0.0; // p3p2 vector x coordinate
  34879. var p3p2y = 0.0; // p3p2 vector y coordinate
  34880. var p3p2z = 0.0; // p3p2 vector z coordinate
  34881. var faceNormalx = 0.0; // facet normal x coordinate
  34882. var faceNormaly = 0.0; // facet normal y coordinate
  34883. var faceNormalz = 0.0; // facet normal z coordinate
  34884. var length = 0.0; // facet normal length before normalization
  34885. var v1x = 0; // vector1 x index in the positions array
  34886. var v1y = 0; // vector1 y index in the positions array
  34887. var v1z = 0; // vector1 z index in the positions array
  34888. var v2x = 0; // vector2 x index in the positions array
  34889. var v2y = 0; // vector2 y index in the positions array
  34890. var v2z = 0; // vector2 z index in the positions array
  34891. var v3x = 0; // vector3 x index in the positions array
  34892. var v3y = 0; // vector3 y index in the positions array
  34893. var v3z = 0; // vector3 z index in the positions array
  34894. var computeFacetNormals = false;
  34895. var computeFacetPositions = false;
  34896. var computeFacetPartitioning = false;
  34897. var computeDepthSort = false;
  34898. var faceNormalSign = 1;
  34899. var ratio = 0;
  34900. var distanceTo = null;
  34901. if (options) {
  34902. computeFacetNormals = (options.facetNormals) ? true : false;
  34903. computeFacetPositions = (options.facetPositions) ? true : false;
  34904. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34905. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34906. ratio = options.ratio || 0;
  34907. computeDepthSort = (options.depthSort) ? true : false;
  34908. distanceTo = (options.distanceTo);
  34909. if (computeDepthSort) {
  34910. if (distanceTo === undefined) {
  34911. distanceTo = BABYLON.Vector3.Zero();
  34912. }
  34913. var depthSortedFacets = options.depthSortedFacets;
  34914. }
  34915. }
  34916. // facetPartitioning reinit if needed
  34917. var xSubRatio = 0;
  34918. var ySubRatio = 0;
  34919. var zSubRatio = 0;
  34920. var subSq = 0;
  34921. if (computeFacetPartitioning && options && options.bbSize) {
  34922. var ox = 0; // X partitioning index for facet position
  34923. var oy = 0; // Y partinioning index for facet position
  34924. var oz = 0; // Z partinioning index for facet position
  34925. var b1x = 0; // X partitioning index for facet v1 vertex
  34926. var b1y = 0; // Y partitioning index for facet v1 vertex
  34927. var b1z = 0; // z partitioning index for facet v1 vertex
  34928. var b2x = 0; // X partitioning index for facet v2 vertex
  34929. var b2y = 0; // Y partitioning index for facet v2 vertex
  34930. var b2z = 0; // Z partitioning index for facet v2 vertex
  34931. var b3x = 0; // X partitioning index for facet v3 vertex
  34932. var b3y = 0; // Y partitioning index for facet v3 vertex
  34933. var b3z = 0; // Z partitioning index for facet v3 vertex
  34934. var block_idx_o = 0; // facet barycenter block index
  34935. var block_idx_v1 = 0; // v1 vertex block index
  34936. var block_idx_v2 = 0; // v2 vertex block index
  34937. var block_idx_v3 = 0; // v3 vertex block index
  34938. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34939. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34940. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34941. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34942. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34943. subSq = options.subDiv.max * options.subDiv.max;
  34944. options.facetPartitioning.length = 0;
  34945. }
  34946. // reset the normals
  34947. for (index = 0; index < positions.length; index++) {
  34948. normals[index] = 0.0;
  34949. }
  34950. // Loop : 1 indice triplet = 1 facet
  34951. var nbFaces = (indices.length / 3) | 0;
  34952. for (index = 0; index < nbFaces; index++) {
  34953. // get the indexes of the coordinates of each vertex of the facet
  34954. v1x = indices[index * 3] * 3;
  34955. v1y = v1x + 1;
  34956. v1z = v1x + 2;
  34957. v2x = indices[index * 3 + 1] * 3;
  34958. v2y = v2x + 1;
  34959. v2z = v2x + 2;
  34960. v3x = indices[index * 3 + 2] * 3;
  34961. v3y = v3x + 1;
  34962. v3z = v3x + 2;
  34963. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34964. p1p2y = positions[v1y] - positions[v2y];
  34965. p1p2z = positions[v1z] - positions[v2z];
  34966. p3p2x = positions[v3x] - positions[v2x];
  34967. p3p2y = positions[v3y] - positions[v2y];
  34968. p3p2z = positions[v3z] - positions[v2z];
  34969. // compute the face normal with the cross product
  34970. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34971. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34972. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34973. // normalize this normal and store it in the array facetData
  34974. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34975. length = (length === 0) ? 1.0 : length;
  34976. faceNormalx /= length;
  34977. faceNormaly /= length;
  34978. faceNormalz /= length;
  34979. if (computeFacetNormals && options) {
  34980. options.facetNormals[index].x = faceNormalx;
  34981. options.facetNormals[index].y = faceNormaly;
  34982. options.facetNormals[index].z = faceNormalz;
  34983. }
  34984. if (computeFacetPositions && options) {
  34985. // compute and the facet barycenter coordinates in the array facetPositions
  34986. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34987. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34988. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34989. }
  34990. if (computeFacetPartitioning && options) {
  34991. // store the facet indexes in arrays in the main facetPartitioning array :
  34992. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34993. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34994. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34995. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34996. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34997. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34998. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34999. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35000. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35001. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35002. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35003. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35004. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35005. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  35006. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  35007. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  35008. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  35009. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  35010. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  35011. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  35012. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  35013. // push each facet index in each block containing the vertex
  35014. options.facetPartitioning[block_idx_v1].push(index);
  35015. if (block_idx_v2 != block_idx_v1) {
  35016. options.facetPartitioning[block_idx_v2].push(index);
  35017. }
  35018. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  35019. options.facetPartitioning[block_idx_v3].push(index);
  35020. }
  35021. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  35022. options.facetPartitioning[block_idx_o].push(index);
  35023. }
  35024. }
  35025. if (computeDepthSort && options && options.facetPositions) {
  35026. var dsf = depthSortedFacets[index];
  35027. dsf.ind = index * 3;
  35028. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  35029. }
  35030. // compute the normals anyway
  35031. normals[v1x] += faceNormalx; // accumulate all the normals per face
  35032. normals[v1y] += faceNormaly;
  35033. normals[v1z] += faceNormalz;
  35034. normals[v2x] += faceNormalx;
  35035. normals[v2y] += faceNormaly;
  35036. normals[v2z] += faceNormalz;
  35037. normals[v3x] += faceNormalx;
  35038. normals[v3y] += faceNormaly;
  35039. normals[v3z] += faceNormalz;
  35040. }
  35041. // last normalization of each normal
  35042. for (index = 0; index < normals.length / 3; index++) {
  35043. faceNormalx = normals[index * 3];
  35044. faceNormaly = normals[index * 3 + 1];
  35045. faceNormalz = normals[index * 3 + 2];
  35046. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35047. length = (length === 0) ? 1.0 : length;
  35048. faceNormalx /= length;
  35049. faceNormaly /= length;
  35050. faceNormalz /= length;
  35051. normals[index * 3] = faceNormalx;
  35052. normals[index * 3 + 1] = faceNormaly;
  35053. normals[index * 3 + 2] = faceNormalz;
  35054. }
  35055. };
  35056. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  35057. var li = indices.length;
  35058. var ln = normals.length;
  35059. var i;
  35060. var n;
  35061. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35062. switch (sideOrientation) {
  35063. case BABYLON.Mesh.FRONTSIDE:
  35064. // nothing changed
  35065. break;
  35066. case BABYLON.Mesh.BACKSIDE:
  35067. var tmp;
  35068. // indices
  35069. for (i = 0; i < li; i += 3) {
  35070. tmp = indices[i];
  35071. indices[i] = indices[i + 2];
  35072. indices[i + 2] = tmp;
  35073. }
  35074. // normals
  35075. for (n = 0; n < ln; n++) {
  35076. normals[n] = -normals[n];
  35077. }
  35078. break;
  35079. case BABYLON.Mesh.DOUBLESIDE:
  35080. // positions
  35081. var lp = positions.length;
  35082. var l = lp / 3;
  35083. for (var p = 0; p < lp; p++) {
  35084. positions[lp + p] = positions[p];
  35085. }
  35086. // indices
  35087. for (i = 0; i < li; i += 3) {
  35088. indices[i + li] = indices[i + 2] + l;
  35089. indices[i + 1 + li] = indices[i + 1] + l;
  35090. indices[i + 2 + li] = indices[i] + l;
  35091. }
  35092. // normals
  35093. for (n = 0; n < ln; n++) {
  35094. normals[ln + n] = -normals[n];
  35095. }
  35096. // uvs
  35097. var lu = uvs.length;
  35098. var u = 0;
  35099. for (u = 0; u < lu; u++) {
  35100. uvs[u + lu] = uvs[u];
  35101. }
  35102. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35103. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35104. u = 0;
  35105. for (i = 0; i < lu / 2; i++) {
  35106. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35107. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35108. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35109. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35110. u += 2;
  35111. }
  35112. break;
  35113. }
  35114. };
  35115. /**
  35116. * Creates a new VertexData from the imported parameters.
  35117. */
  35118. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35119. var vertexData = new VertexData();
  35120. // positions
  35121. var positions = parsedVertexData.positions;
  35122. if (positions) {
  35123. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35124. }
  35125. // normals
  35126. var normals = parsedVertexData.normals;
  35127. if (normals) {
  35128. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35129. }
  35130. // tangents
  35131. var tangents = parsedVertexData.tangents;
  35132. if (tangents) {
  35133. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35134. }
  35135. // uvs
  35136. var uvs = parsedVertexData.uvs;
  35137. if (uvs) {
  35138. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35139. }
  35140. // uv2s
  35141. var uv2s = parsedVertexData.uv2s;
  35142. if (uv2s) {
  35143. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35144. }
  35145. // uv3s
  35146. var uv3s = parsedVertexData.uv3s;
  35147. if (uv3s) {
  35148. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35149. }
  35150. // uv4s
  35151. var uv4s = parsedVertexData.uv4s;
  35152. if (uv4s) {
  35153. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35154. }
  35155. // uv5s
  35156. var uv5s = parsedVertexData.uv5s;
  35157. if (uv5s) {
  35158. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35159. }
  35160. // uv6s
  35161. var uv6s = parsedVertexData.uv6s;
  35162. if (uv6s) {
  35163. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35164. }
  35165. // colors
  35166. var colors = parsedVertexData.colors;
  35167. if (colors) {
  35168. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35169. }
  35170. // matricesIndices
  35171. var matricesIndices = parsedVertexData.matricesIndices;
  35172. if (matricesIndices) {
  35173. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35174. }
  35175. // matricesWeights
  35176. var matricesWeights = parsedVertexData.matricesWeights;
  35177. if (matricesWeights) {
  35178. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35179. }
  35180. // indices
  35181. var indices = parsedVertexData.indices;
  35182. if (indices) {
  35183. vertexData.indices = indices;
  35184. }
  35185. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35186. };
  35187. return VertexData;
  35188. }());
  35189. BABYLON.VertexData = VertexData;
  35190. })(BABYLON || (BABYLON = {}));
  35191. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35192. "use strict";
  35193. var BABYLON;
  35194. (function (BABYLON) {
  35195. /**
  35196. * Class used to store geometry data (vertex buffers + index buffer)
  35197. */
  35198. var Geometry = /** @class */ (function () {
  35199. /**
  35200. * Creates a new geometry
  35201. * @param id defines the unique ID
  35202. * @param scene defines the hosting scene
  35203. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35204. * @param updatable defines if geometry must be updatable (false by default)
  35205. * @param mesh defines the mesh that will be associated with the geometry
  35206. */
  35207. function Geometry(id, scene, vertexData, updatable, mesh) {
  35208. if (updatable === void 0) { updatable = false; }
  35209. if (mesh === void 0) { mesh = null; }
  35210. /**
  35211. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35212. */
  35213. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35214. this._totalVertices = 0;
  35215. this._isDisposed = false;
  35216. this._indexBufferIsUpdatable = false;
  35217. this.id = id;
  35218. this._engine = scene.getEngine();
  35219. this._meshes = [];
  35220. this._scene = scene;
  35221. //Init vertex buffer cache
  35222. this._vertexBuffers = {};
  35223. this._indices = [];
  35224. this._updatable = updatable;
  35225. // vertexData
  35226. if (vertexData) {
  35227. this.setAllVerticesData(vertexData, updatable);
  35228. }
  35229. else {
  35230. this._totalVertices = 0;
  35231. this._indices = [];
  35232. }
  35233. if (this._engine.getCaps().vertexArrayObject) {
  35234. this._vertexArrayObjects = {};
  35235. }
  35236. // applyToMesh
  35237. if (mesh) {
  35238. if (mesh.getClassName() === "LinesMesh") {
  35239. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35240. this.updateExtend();
  35241. }
  35242. this.applyToMesh(mesh);
  35243. mesh.computeWorldMatrix(true);
  35244. }
  35245. }
  35246. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35247. /**
  35248. * 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
  35249. */
  35250. get: function () {
  35251. return this._boundingBias;
  35252. },
  35253. /**
  35254. * 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
  35255. */
  35256. set: function (value) {
  35257. if (this._boundingBias && this._boundingBias.equals(value)) {
  35258. return;
  35259. }
  35260. this._boundingBias = value.clone();
  35261. this.updateBoundingInfo(true, null);
  35262. },
  35263. enumerable: true,
  35264. configurable: true
  35265. });
  35266. /**
  35267. * Static function used to attach a new empty geometry to a mesh
  35268. * @param mesh defines the mesh to attach the geometry to
  35269. * @returns the new {BABYLON.Geometry}
  35270. */
  35271. Geometry.CreateGeometryForMesh = function (mesh) {
  35272. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35273. geometry.applyToMesh(mesh);
  35274. return geometry;
  35275. };
  35276. Object.defineProperty(Geometry.prototype, "extend", {
  35277. /**
  35278. * Gets the current extend of the geometry
  35279. */
  35280. get: function () {
  35281. return this._extend;
  35282. },
  35283. enumerable: true,
  35284. configurable: true
  35285. });
  35286. /**
  35287. * Gets the hosting scene
  35288. * @returns the hosting {BABYLON.Scene}
  35289. */
  35290. Geometry.prototype.getScene = function () {
  35291. return this._scene;
  35292. };
  35293. /**
  35294. * Gets the hosting engine
  35295. * @returns the hosting {BABYLON.Engine}
  35296. */
  35297. Geometry.prototype.getEngine = function () {
  35298. return this._engine;
  35299. };
  35300. /**
  35301. * Defines if the geometry is ready to use
  35302. * @returns true if the geometry is ready to be used
  35303. */
  35304. Geometry.prototype.isReady = function () {
  35305. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35306. };
  35307. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35308. /**
  35309. * Gets a value indicating that the geometry should not be serialized
  35310. */
  35311. get: function () {
  35312. for (var index = 0; index < this._meshes.length; index++) {
  35313. if (!this._meshes[index].doNotSerialize) {
  35314. return false;
  35315. }
  35316. }
  35317. return true;
  35318. },
  35319. enumerable: true,
  35320. configurable: true
  35321. });
  35322. /** @ignore */
  35323. Geometry.prototype._rebuild = function () {
  35324. if (this._vertexArrayObjects) {
  35325. this._vertexArrayObjects = {};
  35326. }
  35327. // Index buffer
  35328. if (this._meshes.length !== 0 && this._indices) {
  35329. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35330. }
  35331. // Vertex buffers
  35332. for (var key in this._vertexBuffers) {
  35333. var vertexBuffer = this._vertexBuffers[key];
  35334. vertexBuffer._rebuild();
  35335. }
  35336. };
  35337. /**
  35338. * Affects all gemetry data in one call
  35339. * @param vertexData defines the geometry data
  35340. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35341. */
  35342. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35343. vertexData.applyToGeometry(this, updatable);
  35344. this.notifyUpdate();
  35345. };
  35346. /**
  35347. * Set specific vertex data
  35348. * @param kind defines the data kind (Position, normal, etc...)
  35349. * @param data defines the vertex data to use
  35350. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35351. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35352. */
  35353. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35354. if (updatable === void 0) { updatable = false; }
  35355. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35356. this.setVerticesBuffer(buffer);
  35357. };
  35358. /**
  35359. * Removes a specific vertex data
  35360. * @param kind defines the data kind (Position, normal, etc...)
  35361. */
  35362. Geometry.prototype.removeVerticesData = function (kind) {
  35363. if (this._vertexBuffers[kind]) {
  35364. this._vertexBuffers[kind].dispose();
  35365. delete this._vertexBuffers[kind];
  35366. }
  35367. };
  35368. /**
  35369. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35370. * @param buffer defines the vertex buffer to use
  35371. */
  35372. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35373. var kind = buffer.getKind();
  35374. if (this._vertexBuffers[kind]) {
  35375. this._vertexBuffers[kind].dispose();
  35376. }
  35377. this._vertexBuffers[kind] = buffer;
  35378. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35379. var data = buffer.getData();
  35380. var stride = buffer.getStrideSize();
  35381. this._totalVertices = data.length / stride;
  35382. this.updateExtend(data, stride);
  35383. this._resetPointsArrayCache();
  35384. var meshes = this._meshes;
  35385. var numOfMeshes = meshes.length;
  35386. for (var index = 0; index < numOfMeshes; index++) {
  35387. var mesh = meshes[index];
  35388. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35389. mesh._createGlobalSubMesh(false);
  35390. mesh.computeWorldMatrix(true);
  35391. }
  35392. }
  35393. this.notifyUpdate(kind);
  35394. if (this._vertexArrayObjects) {
  35395. this._disposeVertexArrayObjects();
  35396. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35397. }
  35398. };
  35399. /**
  35400. * Update a specific vertex buffer
  35401. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35402. * It will do nothing if the buffer is not updatable
  35403. * @param kind defines the data kind (Position, normal, etc...)
  35404. * @param data defines the data to use
  35405. * @param offset defines the offset in the target buffer where to store the data
  35406. */
  35407. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35408. var vertexBuffer = this.getVertexBuffer(kind);
  35409. if (!vertexBuffer) {
  35410. return;
  35411. }
  35412. vertexBuffer.updateDirectly(data, offset);
  35413. this.notifyUpdate(kind);
  35414. };
  35415. /**
  35416. * Update a specific vertex buffer
  35417. * This function will create a new buffer if the current one is not updatable
  35418. * @param kind defines the data kind (Position, normal, etc...)
  35419. * @param data defines the data to use
  35420. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35421. */
  35422. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35423. if (updateExtends === void 0) { updateExtends = false; }
  35424. var vertexBuffer = this.getVertexBuffer(kind);
  35425. if (!vertexBuffer) {
  35426. return;
  35427. }
  35428. vertexBuffer.update(data);
  35429. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35430. var stride = vertexBuffer.getStrideSize();
  35431. this._totalVertices = data.length / stride;
  35432. this.updateBoundingInfo(updateExtends, data);
  35433. }
  35434. this.notifyUpdate(kind);
  35435. };
  35436. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35437. if (updateExtends) {
  35438. this.updateExtend(data);
  35439. }
  35440. var meshes = this._meshes;
  35441. var numOfMeshes = meshes.length;
  35442. this._resetPointsArrayCache();
  35443. for (var index = 0; index < numOfMeshes; index++) {
  35444. var mesh = meshes[index];
  35445. if (updateExtends) {
  35446. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35447. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35448. var subMesh = mesh.subMeshes[subIndex];
  35449. subMesh.refreshBoundingInfo();
  35450. }
  35451. }
  35452. }
  35453. };
  35454. /** @ignore */
  35455. Geometry.prototype._bind = function (effect, indexToBind) {
  35456. if (!effect) {
  35457. return;
  35458. }
  35459. if (indexToBind === undefined) {
  35460. indexToBind = this._indexBuffer;
  35461. }
  35462. var vbs = this.getVertexBuffers();
  35463. if (!vbs) {
  35464. return;
  35465. }
  35466. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35467. this._engine.bindBuffers(vbs, indexToBind, effect);
  35468. return;
  35469. }
  35470. // Using VAO
  35471. if (!this._vertexArrayObjects[effect.key]) {
  35472. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35473. }
  35474. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35475. };
  35476. /**
  35477. * Gets total number of vertices
  35478. * @returns the total number of vertices
  35479. */
  35480. Geometry.prototype.getTotalVertices = function () {
  35481. if (!this.isReady()) {
  35482. return 0;
  35483. }
  35484. return this._totalVertices;
  35485. };
  35486. /**
  35487. * Gets a specific vertex data attached to this geometry
  35488. * @param kind defines the data kind (Position, normal, etc...)
  35489. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35490. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35491. * @returns a float array containing vertex data
  35492. */
  35493. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35494. var vertexBuffer = this.getVertexBuffer(kind);
  35495. if (!vertexBuffer) {
  35496. return null;
  35497. }
  35498. var orig = vertexBuffer.getData();
  35499. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35500. return orig;
  35501. }
  35502. else {
  35503. var len = orig.length;
  35504. var copy = [];
  35505. for (var i = 0; i < len; i++) {
  35506. copy.push(orig[i]);
  35507. }
  35508. return copy;
  35509. }
  35510. };
  35511. /**
  35512. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35513. * @param kind defines the data kind (Position, normal, etc...)
  35514. * @returns true if the vertex buffer with the specified kind is updatable
  35515. */
  35516. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35517. var vb = this._vertexBuffers[kind];
  35518. if (!vb) {
  35519. return false;
  35520. }
  35521. return vb.isUpdatable();
  35522. };
  35523. /**
  35524. * Gets a specific vertex buffer
  35525. * @param kind defines the data kind (Position, normal, etc...)
  35526. * @returns a {BABYLON.VertexBuffer}
  35527. */
  35528. Geometry.prototype.getVertexBuffer = function (kind) {
  35529. if (!this.isReady()) {
  35530. return null;
  35531. }
  35532. return this._vertexBuffers[kind];
  35533. };
  35534. /**
  35535. * Returns all vertex buffers
  35536. * @return an object holding all vertex buffers indexed by kind
  35537. */
  35538. Geometry.prototype.getVertexBuffers = function () {
  35539. if (!this.isReady()) {
  35540. return null;
  35541. }
  35542. return this._vertexBuffers;
  35543. };
  35544. /**
  35545. * Gets a boolean indicating if specific vertex buffer is present
  35546. * @param kind defines the data kind (Position, normal, etc...)
  35547. * @returns true if data is present
  35548. */
  35549. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35550. if (!this._vertexBuffers) {
  35551. if (this._delayInfo) {
  35552. return this._delayInfo.indexOf(kind) !== -1;
  35553. }
  35554. return false;
  35555. }
  35556. return this._vertexBuffers[kind] !== undefined;
  35557. };
  35558. /**
  35559. * Gets a list of all attached data kinds (Position, normal, etc...)
  35560. * @returns a list of string containing all kinds
  35561. */
  35562. Geometry.prototype.getVerticesDataKinds = function () {
  35563. var result = [];
  35564. var kind;
  35565. if (!this._vertexBuffers && this._delayInfo) {
  35566. for (kind in this._delayInfo) {
  35567. result.push(kind);
  35568. }
  35569. }
  35570. else {
  35571. for (kind in this._vertexBuffers) {
  35572. result.push(kind);
  35573. }
  35574. }
  35575. return result;
  35576. };
  35577. /**
  35578. * Update index buffer
  35579. * @param indices defines the indices to store in the index buffer
  35580. * @param offset defines the offset in the target buffer where to store the data
  35581. */
  35582. Geometry.prototype.updateIndices = function (indices, offset) {
  35583. if (!this._indexBuffer) {
  35584. return;
  35585. }
  35586. if (!this._indexBufferIsUpdatable) {
  35587. this.setIndices(indices, null, true);
  35588. }
  35589. else {
  35590. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35591. }
  35592. };
  35593. /**
  35594. * Creates a new index buffer
  35595. * @param indices defines the indices to store in the index buffer
  35596. * @param totalVertices defines the total number of vertices (could be null)
  35597. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35598. */
  35599. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35600. if (totalVertices === void 0) { totalVertices = null; }
  35601. if (updatable === void 0) { updatable = false; }
  35602. if (this._indexBuffer) {
  35603. this._engine._releaseBuffer(this._indexBuffer);
  35604. }
  35605. this._disposeVertexArrayObjects();
  35606. this._indices = indices;
  35607. this._indexBufferIsUpdatable = updatable;
  35608. if (this._meshes.length !== 0 && this._indices) {
  35609. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35610. }
  35611. if (totalVertices != undefined) {
  35612. this._totalVertices = totalVertices;
  35613. }
  35614. var meshes = this._meshes;
  35615. var numOfMeshes = meshes.length;
  35616. for (var index = 0; index < numOfMeshes; index++) {
  35617. meshes[index]._createGlobalSubMesh(true);
  35618. }
  35619. this.notifyUpdate();
  35620. };
  35621. /**
  35622. * Return the total number of indices
  35623. * @returns the total number of indices
  35624. */
  35625. Geometry.prototype.getTotalIndices = function () {
  35626. if (!this.isReady()) {
  35627. return 0;
  35628. }
  35629. return this._indices.length;
  35630. };
  35631. /**
  35632. * Gets the index buffer array
  35633. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35634. * @returns the index buffer array
  35635. */
  35636. Geometry.prototype.getIndices = function (copyWhenShared) {
  35637. if (!this.isReady()) {
  35638. return null;
  35639. }
  35640. var orig = this._indices;
  35641. if (!copyWhenShared || this._meshes.length === 1) {
  35642. return orig;
  35643. }
  35644. else {
  35645. var len = orig.length;
  35646. var copy = [];
  35647. for (var i = 0; i < len; i++) {
  35648. copy.push(orig[i]);
  35649. }
  35650. return copy;
  35651. }
  35652. };
  35653. /**
  35654. * Gets the index buffer
  35655. * @return the index buffer
  35656. */
  35657. Geometry.prototype.getIndexBuffer = function () {
  35658. if (!this.isReady()) {
  35659. return null;
  35660. }
  35661. return this._indexBuffer;
  35662. };
  35663. /** @ignore */
  35664. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35665. if (effect === void 0) { effect = null; }
  35666. if (!effect || !this._vertexArrayObjects) {
  35667. return;
  35668. }
  35669. if (this._vertexArrayObjects[effect.key]) {
  35670. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35671. delete this._vertexArrayObjects[effect.key];
  35672. }
  35673. };
  35674. /**
  35675. * Release the associated resources for a specific mesh
  35676. * @param mesh defines the source mesh
  35677. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35678. */
  35679. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35680. var meshes = this._meshes;
  35681. var index = meshes.indexOf(mesh);
  35682. if (index === -1) {
  35683. return;
  35684. }
  35685. meshes.splice(index, 1);
  35686. mesh._geometry = null;
  35687. if (meshes.length === 0 && shouldDispose) {
  35688. this.dispose();
  35689. }
  35690. };
  35691. /**
  35692. * Apply current geometry to a given mesh
  35693. * @param mesh defines the mesh to apply geometry to
  35694. */
  35695. Geometry.prototype.applyToMesh = function (mesh) {
  35696. if (mesh._geometry === this) {
  35697. return;
  35698. }
  35699. var previousGeometry = mesh._geometry;
  35700. if (previousGeometry) {
  35701. previousGeometry.releaseForMesh(mesh);
  35702. }
  35703. var meshes = this._meshes;
  35704. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35705. mesh._geometry = this;
  35706. this._scene.pushGeometry(this);
  35707. meshes.push(mesh);
  35708. if (this.isReady()) {
  35709. this._applyToMesh(mesh);
  35710. }
  35711. else {
  35712. mesh._boundingInfo = this._boundingInfo;
  35713. }
  35714. };
  35715. Geometry.prototype.updateExtend = function (data, stride) {
  35716. if (data === void 0) { data = null; }
  35717. if (!data) {
  35718. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35719. }
  35720. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35721. };
  35722. Geometry.prototype._applyToMesh = function (mesh) {
  35723. var numOfMeshes = this._meshes.length;
  35724. // vertexBuffers
  35725. for (var kind in this._vertexBuffers) {
  35726. if (numOfMeshes === 1) {
  35727. this._vertexBuffers[kind].create();
  35728. }
  35729. var buffer = this._vertexBuffers[kind].getBuffer();
  35730. if (buffer)
  35731. buffer.references = numOfMeshes;
  35732. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35733. if (!this._extend) {
  35734. this.updateExtend(this._vertexBuffers[kind].getData());
  35735. }
  35736. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35737. mesh._createGlobalSubMesh(false);
  35738. //bounding info was just created again, world matrix should be applied again.
  35739. mesh._updateBoundingInfo();
  35740. }
  35741. }
  35742. // indexBuffer
  35743. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35744. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35745. }
  35746. if (this._indexBuffer) {
  35747. this._indexBuffer.references = numOfMeshes;
  35748. }
  35749. };
  35750. Geometry.prototype.notifyUpdate = function (kind) {
  35751. if (this.onGeometryUpdated) {
  35752. this.onGeometryUpdated(this, kind);
  35753. }
  35754. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35755. var mesh = _a[_i];
  35756. mesh._markSubMeshesAsAttributesDirty();
  35757. }
  35758. };
  35759. /**
  35760. * Load the geometry if it was flagged as delay loaded
  35761. * @param scene defines the hosting scene
  35762. * @param onLoaded defines a callback called when the geometry is loaded
  35763. */
  35764. Geometry.prototype.load = function (scene, onLoaded) {
  35765. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35766. return;
  35767. }
  35768. if (this.isReady()) {
  35769. if (onLoaded) {
  35770. onLoaded();
  35771. }
  35772. return;
  35773. }
  35774. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35775. this._queueLoad(scene, onLoaded);
  35776. };
  35777. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35778. var _this = this;
  35779. if (!this.delayLoadingFile) {
  35780. return;
  35781. }
  35782. scene._addPendingData(this);
  35783. scene._loadFile(this.delayLoadingFile, function (data) {
  35784. if (!_this._delayLoadingFunction) {
  35785. return;
  35786. }
  35787. _this._delayLoadingFunction(JSON.parse(data), _this);
  35788. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35789. _this._delayInfo = [];
  35790. scene._removePendingData(_this);
  35791. var meshes = _this._meshes;
  35792. var numOfMeshes = meshes.length;
  35793. for (var index = 0; index < numOfMeshes; index++) {
  35794. _this._applyToMesh(meshes[index]);
  35795. }
  35796. if (onLoaded) {
  35797. onLoaded();
  35798. }
  35799. }, undefined, true);
  35800. };
  35801. /**
  35802. * Invert the geometry to move from a right handed system to a left handed one.
  35803. */
  35804. Geometry.prototype.toLeftHanded = function () {
  35805. // Flip faces
  35806. var tIndices = this.getIndices(false);
  35807. if (tIndices != null && tIndices.length > 0) {
  35808. for (var i = 0; i < tIndices.length; i += 3) {
  35809. var tTemp = tIndices[i + 0];
  35810. tIndices[i + 0] = tIndices[i + 2];
  35811. tIndices[i + 2] = tTemp;
  35812. }
  35813. this.setIndices(tIndices);
  35814. }
  35815. // Negate position.z
  35816. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35817. if (tPositions != null && tPositions.length > 0) {
  35818. for (var i = 0; i < tPositions.length; i += 3) {
  35819. tPositions[i + 2] = -tPositions[i + 2];
  35820. }
  35821. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35822. }
  35823. // Negate normal.z
  35824. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35825. if (tNormals != null && tNormals.length > 0) {
  35826. for (var i = 0; i < tNormals.length; i += 3) {
  35827. tNormals[i + 2] = -tNormals[i + 2];
  35828. }
  35829. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35830. }
  35831. };
  35832. // Cache
  35833. /** @ignore */
  35834. Geometry.prototype._resetPointsArrayCache = function () {
  35835. this._positions = null;
  35836. };
  35837. /** @ignore */
  35838. Geometry.prototype._generatePointsArray = function () {
  35839. if (this._positions)
  35840. return true;
  35841. this._positions = [];
  35842. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35843. if (!data) {
  35844. return false;
  35845. }
  35846. for (var index = 0; index < data.length; index += 3) {
  35847. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35848. }
  35849. return true;
  35850. };
  35851. /**
  35852. * Gets a value indicating if the geometry is disposed
  35853. * @returns true if the geometry was disposed
  35854. */
  35855. Geometry.prototype.isDisposed = function () {
  35856. return this._isDisposed;
  35857. };
  35858. Geometry.prototype._disposeVertexArrayObjects = function () {
  35859. if (this._vertexArrayObjects) {
  35860. for (var kind in this._vertexArrayObjects) {
  35861. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35862. }
  35863. this._vertexArrayObjects = {};
  35864. }
  35865. };
  35866. /**
  35867. * Free all associated resources
  35868. */
  35869. Geometry.prototype.dispose = function () {
  35870. var meshes = this._meshes;
  35871. var numOfMeshes = meshes.length;
  35872. var index;
  35873. for (index = 0; index < numOfMeshes; index++) {
  35874. this.releaseForMesh(meshes[index]);
  35875. }
  35876. this._meshes = [];
  35877. this._disposeVertexArrayObjects();
  35878. for (var kind in this._vertexBuffers) {
  35879. this._vertexBuffers[kind].dispose();
  35880. }
  35881. this._vertexBuffers = {};
  35882. this._totalVertices = 0;
  35883. if (this._indexBuffer) {
  35884. this._engine._releaseBuffer(this._indexBuffer);
  35885. }
  35886. this._indexBuffer = null;
  35887. this._indices = [];
  35888. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35889. this.delayLoadingFile = null;
  35890. this._delayLoadingFunction = null;
  35891. this._delayInfo = [];
  35892. this._boundingInfo = null;
  35893. this._scene.removeGeometry(this);
  35894. this._isDisposed = true;
  35895. };
  35896. /**
  35897. * Clone the current geometry into a new geometry
  35898. * @param id defines the unique ID of the new geometry
  35899. * @returns a new geometry object
  35900. */
  35901. Geometry.prototype.copy = function (id) {
  35902. var vertexData = new BABYLON.VertexData();
  35903. vertexData.indices = [];
  35904. var indices = this.getIndices();
  35905. if (indices) {
  35906. for (var index = 0; index < indices.length; index++) {
  35907. vertexData.indices.push(indices[index]);
  35908. }
  35909. }
  35910. var updatable = false;
  35911. var stopChecking = false;
  35912. var kind;
  35913. for (kind in this._vertexBuffers) {
  35914. // using slice() to make a copy of the array and not just reference it
  35915. var data = this.getVerticesData(kind);
  35916. if (data instanceof Float32Array) {
  35917. vertexData.set(new Float32Array(data), kind);
  35918. }
  35919. else {
  35920. vertexData.set(data.slice(0), kind);
  35921. }
  35922. if (!stopChecking) {
  35923. var vb = this.getVertexBuffer(kind);
  35924. if (vb) {
  35925. updatable = vb.isUpdatable();
  35926. stopChecking = !updatable;
  35927. }
  35928. }
  35929. }
  35930. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35931. geometry.delayLoadState = this.delayLoadState;
  35932. geometry.delayLoadingFile = this.delayLoadingFile;
  35933. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35934. for (kind in this._delayInfo) {
  35935. geometry._delayInfo = geometry._delayInfo || [];
  35936. geometry._delayInfo.push(kind);
  35937. }
  35938. // Bounding info
  35939. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35940. return geometry;
  35941. };
  35942. /**
  35943. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35944. * @return a JSON representation of the current geometry data (without the vertices data)
  35945. */
  35946. Geometry.prototype.serialize = function () {
  35947. var serializationObject = {};
  35948. serializationObject.id = this.id;
  35949. serializationObject.updatable = this._updatable;
  35950. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35951. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35952. }
  35953. return serializationObject;
  35954. };
  35955. Geometry.prototype.toNumberArray = function (origin) {
  35956. if (Array.isArray(origin)) {
  35957. return origin;
  35958. }
  35959. else {
  35960. return Array.prototype.slice.call(origin);
  35961. }
  35962. };
  35963. /**
  35964. * Serialize all vertices data into a JSON oject
  35965. * @returns a JSON representation of the current geometry data
  35966. */
  35967. Geometry.prototype.serializeVerticeData = function () {
  35968. var serializationObject = this.serialize();
  35969. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35970. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35971. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35972. serializationObject.positions._updatable = true;
  35973. }
  35974. }
  35975. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35976. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35977. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35978. serializationObject.normals._updatable = true;
  35979. }
  35980. }
  35981. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35982. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35983. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35984. serializationObject.tangets._updatable = true;
  35985. }
  35986. }
  35987. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35988. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35989. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35990. serializationObject.uvs._updatable = true;
  35991. }
  35992. }
  35993. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35994. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35995. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35996. serializationObject.uv2s._updatable = true;
  35997. }
  35998. }
  35999. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36000. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  36001. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  36002. serializationObject.uv3s._updatable = true;
  36003. }
  36004. }
  36005. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36006. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  36007. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  36008. serializationObject.uv4s._updatable = true;
  36009. }
  36010. }
  36011. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36012. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  36013. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  36014. serializationObject.uv5s._updatable = true;
  36015. }
  36016. }
  36017. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36018. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  36019. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  36020. serializationObject.uv6s._updatable = true;
  36021. }
  36022. }
  36023. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36024. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  36025. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  36026. serializationObject.colors._updatable = true;
  36027. }
  36028. }
  36029. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36030. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  36031. serializationObject.matricesIndices._isExpanded = true;
  36032. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36033. serializationObject.matricesIndices._updatable = true;
  36034. }
  36035. }
  36036. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36037. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  36038. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36039. serializationObject.matricesWeights._updatable = true;
  36040. }
  36041. }
  36042. serializationObject.indices = this.toNumberArray(this.getIndices());
  36043. return serializationObject;
  36044. };
  36045. // Statics
  36046. /**
  36047. * Extracts a clone of a mesh geometry
  36048. * @param mesh defines the source mesh
  36049. * @param id defines the unique ID of the new geometry object
  36050. * @returns the new geometry object
  36051. */
  36052. Geometry.ExtractFromMesh = function (mesh, id) {
  36053. var geometry = mesh._geometry;
  36054. if (!geometry) {
  36055. return null;
  36056. }
  36057. return geometry.copy(id);
  36058. };
  36059. /**
  36060. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36061. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36062. * Be aware Math.random() could cause collisions, but:
  36063. * "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"
  36064. * @returns a string containing a new GUID
  36065. */
  36066. Geometry.RandomId = function () {
  36067. return BABYLON.Tools.RandomId();
  36068. };
  36069. /** @ignore */
  36070. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36071. var scene = mesh.getScene();
  36072. // Geometry
  36073. var geometryId = parsedGeometry.geometryId;
  36074. if (geometryId) {
  36075. var geometry = scene.getGeometryByID(geometryId);
  36076. if (geometry) {
  36077. geometry.applyToMesh(mesh);
  36078. }
  36079. }
  36080. else if (parsedGeometry instanceof ArrayBuffer) {
  36081. var binaryInfo = mesh._binaryInfo;
  36082. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36083. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36084. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36085. }
  36086. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36087. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36088. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36089. }
  36090. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36091. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36092. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36093. }
  36094. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36095. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36096. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36097. }
  36098. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36099. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36100. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36101. }
  36102. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36103. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36104. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36105. }
  36106. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36107. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36108. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36109. }
  36110. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36111. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36112. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36113. }
  36114. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36115. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36116. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36117. }
  36118. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36119. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36120. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36121. }
  36122. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36123. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36124. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36125. }
  36126. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36127. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36128. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36129. }
  36130. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36131. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36132. mesh.setIndices(indicesData, null);
  36133. }
  36134. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36135. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36136. mesh.subMeshes = [];
  36137. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36138. var materialIndex = subMeshesData[(i * 5) + 0];
  36139. var verticesStart = subMeshesData[(i * 5) + 1];
  36140. var verticesCount = subMeshesData[(i * 5) + 2];
  36141. var indexStart = subMeshesData[(i * 5) + 3];
  36142. var indexCount = subMeshesData[(i * 5) + 4];
  36143. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36144. }
  36145. }
  36146. }
  36147. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36148. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36149. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36150. if (parsedGeometry.tangents) {
  36151. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36152. }
  36153. if (parsedGeometry.uvs) {
  36154. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36155. }
  36156. if (parsedGeometry.uvs2) {
  36157. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36158. }
  36159. if (parsedGeometry.uvs3) {
  36160. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36161. }
  36162. if (parsedGeometry.uvs4) {
  36163. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36164. }
  36165. if (parsedGeometry.uvs5) {
  36166. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36167. }
  36168. if (parsedGeometry.uvs6) {
  36169. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36170. }
  36171. if (parsedGeometry.colors) {
  36172. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36173. }
  36174. if (parsedGeometry.matricesIndices) {
  36175. if (!parsedGeometry.matricesIndices._isExpanded) {
  36176. var floatIndices = [];
  36177. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36178. var matricesIndex = parsedGeometry.matricesIndices[i];
  36179. floatIndices.push(matricesIndex & 0x000000FF);
  36180. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36181. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36182. floatIndices.push(matricesIndex >> 24);
  36183. }
  36184. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36185. }
  36186. else {
  36187. delete parsedGeometry.matricesIndices._isExpanded;
  36188. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36189. }
  36190. }
  36191. if (parsedGeometry.matricesIndicesExtra) {
  36192. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36193. var floatIndices = [];
  36194. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36195. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36196. floatIndices.push(matricesIndex & 0x000000FF);
  36197. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36198. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36199. floatIndices.push(matricesIndex >> 24);
  36200. }
  36201. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36202. }
  36203. else {
  36204. delete parsedGeometry.matricesIndices._isExpanded;
  36205. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36206. }
  36207. }
  36208. if (parsedGeometry.matricesWeights) {
  36209. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36210. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36211. }
  36212. if (parsedGeometry.matricesWeightsExtra) {
  36213. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36214. }
  36215. mesh.setIndices(parsedGeometry.indices, null);
  36216. }
  36217. // SubMeshes
  36218. if (parsedGeometry.subMeshes) {
  36219. mesh.subMeshes = [];
  36220. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36221. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36222. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36223. }
  36224. }
  36225. // Flat shading
  36226. if (mesh._shouldGenerateFlatShading) {
  36227. mesh.convertToFlatShadedMesh();
  36228. delete mesh._shouldGenerateFlatShading;
  36229. }
  36230. // Update
  36231. mesh.computeWorldMatrix(true);
  36232. // Octree
  36233. var sceneOctree = scene.selectionOctree;
  36234. if (sceneOctree !== undefined && sceneOctree !== null) {
  36235. sceneOctree.addMesh(mesh);
  36236. }
  36237. };
  36238. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36239. var epsilon = 1e-3;
  36240. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36241. return;
  36242. }
  36243. var noInfluenceBoneIndex = 0.0;
  36244. if (parsedGeometry.skeletonId > -1) {
  36245. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36246. if (!skeleton) {
  36247. return;
  36248. }
  36249. noInfluenceBoneIndex = skeleton.bones.length;
  36250. }
  36251. else {
  36252. return;
  36253. }
  36254. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36255. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36256. var matricesWeights = parsedGeometry.matricesWeights;
  36257. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36258. var influencers = parsedGeometry.numBoneInfluencer;
  36259. var size = matricesWeights.length;
  36260. for (var i = 0; i < size; i += 4) {
  36261. var weight = 0.0;
  36262. var firstZeroWeight = -1;
  36263. for (var j = 0; j < 4; j++) {
  36264. var w = matricesWeights[i + j];
  36265. weight += w;
  36266. if (w < epsilon && firstZeroWeight < 0) {
  36267. firstZeroWeight = j;
  36268. }
  36269. }
  36270. if (matricesWeightsExtra) {
  36271. for (var j = 0; j < 4; j++) {
  36272. var w = matricesWeightsExtra[i + j];
  36273. weight += w;
  36274. if (w < epsilon && firstZeroWeight < 0) {
  36275. firstZeroWeight = j + 4;
  36276. }
  36277. }
  36278. }
  36279. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36280. firstZeroWeight = influencers - 1;
  36281. }
  36282. if (weight > epsilon) {
  36283. var mweight = 1.0 / weight;
  36284. for (var j = 0; j < 4; j++) {
  36285. matricesWeights[i + j] *= mweight;
  36286. }
  36287. if (matricesWeightsExtra) {
  36288. for (var j = 0; j < 4; j++) {
  36289. matricesWeightsExtra[i + j] *= mweight;
  36290. }
  36291. }
  36292. }
  36293. else {
  36294. if (firstZeroWeight >= 4) {
  36295. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36296. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36297. }
  36298. else {
  36299. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36300. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36301. }
  36302. }
  36303. }
  36304. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36305. if (parsedGeometry.matricesWeightsExtra) {
  36306. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36307. }
  36308. };
  36309. /**
  36310. * Create a new geometry from persisted data (Using .babylon file format)
  36311. * @param parsedVertexData defines the persisted data
  36312. * @param scene defines the hosting scene
  36313. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36314. * @returns the new geometry object
  36315. */
  36316. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36317. if (scene.getGeometryByID(parsedVertexData.id)) {
  36318. return null; // null since geometry could be something else than a box...
  36319. }
  36320. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36321. if (BABYLON.Tags) {
  36322. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36323. }
  36324. if (parsedVertexData.delayLoadingFile) {
  36325. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36326. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36327. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36328. geometry._delayInfo = [];
  36329. if (parsedVertexData.hasUVs) {
  36330. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36331. }
  36332. if (parsedVertexData.hasUVs2) {
  36333. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36334. }
  36335. if (parsedVertexData.hasUVs3) {
  36336. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36337. }
  36338. if (parsedVertexData.hasUVs4) {
  36339. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36340. }
  36341. if (parsedVertexData.hasUVs5) {
  36342. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36343. }
  36344. if (parsedVertexData.hasUVs6) {
  36345. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36346. }
  36347. if (parsedVertexData.hasColors) {
  36348. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36349. }
  36350. if (parsedVertexData.hasMatricesIndices) {
  36351. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36352. }
  36353. if (parsedVertexData.hasMatricesWeights) {
  36354. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36355. }
  36356. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36357. }
  36358. else {
  36359. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36360. }
  36361. scene.pushGeometry(geometry, true);
  36362. return geometry;
  36363. };
  36364. return Geometry;
  36365. }());
  36366. BABYLON.Geometry = Geometry;
  36367. // Primitives
  36368. /// Abstract class
  36369. /**
  36370. * Abstract class used to provide common services for all typed geometries
  36371. */
  36372. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36373. __extends(_PrimitiveGeometry, _super);
  36374. /**
  36375. * Creates a new typed geometry
  36376. * @param id defines the unique ID of the geometry
  36377. * @param scene defines the hosting scene
  36378. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36379. * @param mesh defines the hosting mesh (can be null)
  36380. */
  36381. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36382. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36383. if (mesh === void 0) { mesh = null; }
  36384. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36385. _this._canBeRegenerated = _canBeRegenerated;
  36386. _this._beingRegenerated = true;
  36387. _this.regenerate();
  36388. _this._beingRegenerated = false;
  36389. return _this;
  36390. }
  36391. /**
  36392. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36393. * @returns true if the geometry can be regenerated
  36394. */
  36395. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36396. return this._canBeRegenerated;
  36397. };
  36398. /**
  36399. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36400. */
  36401. _PrimitiveGeometry.prototype.regenerate = function () {
  36402. if (!this._canBeRegenerated) {
  36403. return;
  36404. }
  36405. this._beingRegenerated = true;
  36406. this.setAllVerticesData(this._regenerateVertexData(), false);
  36407. this._beingRegenerated = false;
  36408. };
  36409. /**
  36410. * Clone the geometry
  36411. * @param id defines the unique ID of the new geometry
  36412. * @returns the new geometry
  36413. */
  36414. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36415. return _super.prototype.copy.call(this, id);
  36416. };
  36417. // overrides
  36418. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36419. if (!this._beingRegenerated) {
  36420. return;
  36421. }
  36422. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36423. };
  36424. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36425. if (!this._beingRegenerated) {
  36426. return;
  36427. }
  36428. _super.prototype.setVerticesData.call(this, kind, data, false);
  36429. };
  36430. // to override
  36431. /** @ignore */
  36432. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36433. throw new Error("Abstract method");
  36434. };
  36435. _PrimitiveGeometry.prototype.copy = function (id) {
  36436. throw new Error("Must be overriden in sub-classes.");
  36437. };
  36438. _PrimitiveGeometry.prototype.serialize = function () {
  36439. var serializationObject = _super.prototype.serialize.call(this);
  36440. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36441. return serializationObject;
  36442. };
  36443. return _PrimitiveGeometry;
  36444. }(Geometry));
  36445. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36446. /**
  36447. * Creates a ribbon geometry
  36448. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36449. */
  36450. var RibbonGeometry = /** @class */ (function (_super) {
  36451. __extends(RibbonGeometry, _super);
  36452. /**
  36453. * Creates a ribbon geometry
  36454. * @param id defines the unique ID of the geometry
  36455. * @param scene defines the hosting scene
  36456. * @param pathArray defines the array of paths to use
  36457. * @param closeArray defines if the last path and the first path must be joined
  36458. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36459. * @param offset defines the offset between points
  36460. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36461. * @param mesh defines the hosting mesh (can be null)
  36462. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36463. */
  36464. function RibbonGeometry(id, scene,
  36465. /**
  36466. * Defines the array of paths to use
  36467. */
  36468. pathArray,
  36469. /**
  36470. * Defines if the last and first points of each path in your pathArray must be joined
  36471. */
  36472. closeArray,
  36473. /**
  36474. * Defines if the last and first points of each path in your pathArray must be joined
  36475. */
  36476. closePath,
  36477. /**
  36478. * Defines the offset between points
  36479. */
  36480. offset, canBeRegenerated, mesh,
  36481. /**
  36482. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36483. */
  36484. side) {
  36485. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36486. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36487. _this.pathArray = pathArray;
  36488. _this.closeArray = closeArray;
  36489. _this.closePath = closePath;
  36490. _this.offset = offset;
  36491. _this.side = side;
  36492. return _this;
  36493. }
  36494. /** @ignore */
  36495. RibbonGeometry.prototype._regenerateVertexData = function () {
  36496. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36497. };
  36498. RibbonGeometry.prototype.copy = function (id) {
  36499. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36500. };
  36501. return RibbonGeometry;
  36502. }(_PrimitiveGeometry));
  36503. BABYLON.RibbonGeometry = RibbonGeometry;
  36504. /**
  36505. * Creates a box geometry
  36506. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36507. */
  36508. var BoxGeometry = /** @class */ (function (_super) {
  36509. __extends(BoxGeometry, _super);
  36510. /**
  36511. * Creates a box geometry
  36512. * @param id defines the unique ID of the geometry
  36513. * @param scene defines the hosting scene
  36514. * @param size defines the zise of the box (width, height and depth are the same)
  36515. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36516. * @param mesh defines the hosting mesh (can be null)
  36517. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36518. */
  36519. function BoxGeometry(id, scene,
  36520. /**
  36521. * Defines the zise of the box (width, height and depth are the same)
  36522. */
  36523. size, canBeRegenerated, mesh,
  36524. /**
  36525. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36526. */
  36527. side) {
  36528. if (mesh === void 0) { mesh = null; }
  36529. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36530. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36531. _this.size = size;
  36532. _this.side = side;
  36533. return _this;
  36534. }
  36535. BoxGeometry.prototype._regenerateVertexData = function () {
  36536. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36537. };
  36538. BoxGeometry.prototype.copy = function (id) {
  36539. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36540. };
  36541. BoxGeometry.prototype.serialize = function () {
  36542. var serializationObject = _super.prototype.serialize.call(this);
  36543. serializationObject.size = this.size;
  36544. return serializationObject;
  36545. };
  36546. BoxGeometry.Parse = function (parsedBox, scene) {
  36547. if (scene.getGeometryByID(parsedBox.id)) {
  36548. return null; // null since geometry could be something else than a box...
  36549. }
  36550. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36551. if (BABYLON.Tags) {
  36552. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36553. }
  36554. scene.pushGeometry(box, true);
  36555. return box;
  36556. };
  36557. return BoxGeometry;
  36558. }(_PrimitiveGeometry));
  36559. BABYLON.BoxGeometry = BoxGeometry;
  36560. /**
  36561. * Creates a sphere geometry
  36562. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36563. */
  36564. var SphereGeometry = /** @class */ (function (_super) {
  36565. __extends(SphereGeometry, _super);
  36566. /**
  36567. * Create a new sphere geometry
  36568. * @param id defines the unique ID of the geometry
  36569. * @param scene defines the hosting scene
  36570. * @param segments defines the number of segments to use to create the sphere
  36571. * @param diameter defines the diameter of the sphere
  36572. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36573. * @param mesh defines the hosting mesh (can be null)
  36574. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36575. */
  36576. function SphereGeometry(id, scene,
  36577. /**
  36578. * Defines the number of segments to use to create the sphere
  36579. */
  36580. segments,
  36581. /**
  36582. * Defines the diameter of the sphere
  36583. */
  36584. diameter, canBeRegenerated, mesh,
  36585. /**
  36586. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36587. */
  36588. side) {
  36589. if (mesh === void 0) { mesh = null; }
  36590. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36591. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36592. _this.segments = segments;
  36593. _this.diameter = diameter;
  36594. _this.side = side;
  36595. return _this;
  36596. }
  36597. SphereGeometry.prototype._regenerateVertexData = function () {
  36598. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36599. };
  36600. SphereGeometry.prototype.copy = function (id) {
  36601. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36602. };
  36603. SphereGeometry.prototype.serialize = function () {
  36604. var serializationObject = _super.prototype.serialize.call(this);
  36605. serializationObject.segments = this.segments;
  36606. serializationObject.diameter = this.diameter;
  36607. return serializationObject;
  36608. };
  36609. SphereGeometry.Parse = function (parsedSphere, scene) {
  36610. if (scene.getGeometryByID(parsedSphere.id)) {
  36611. return null; // null since geometry could be something else than a sphere...
  36612. }
  36613. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36614. if (BABYLON.Tags) {
  36615. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36616. }
  36617. scene.pushGeometry(sphere, true);
  36618. return sphere;
  36619. };
  36620. return SphereGeometry;
  36621. }(_PrimitiveGeometry));
  36622. BABYLON.SphereGeometry = SphereGeometry;
  36623. /**
  36624. * Creates a disc geometry
  36625. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36626. */
  36627. var DiscGeometry = /** @class */ (function (_super) {
  36628. __extends(DiscGeometry, _super);
  36629. /**
  36630. * Creates a new disc geometry
  36631. * @param id defines the unique ID of the geometry
  36632. * @param scene defines the hosting scene
  36633. * @param radius defines the radius of the disc
  36634. * @param tessellation defines the tesselation factor to apply to the disc
  36635. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36636. * @param mesh defines the hosting mesh (can be null)
  36637. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36638. */
  36639. function DiscGeometry(id, scene,
  36640. /**
  36641. * Defines the radius of the disc
  36642. */
  36643. radius,
  36644. /**
  36645. * Defines the tesselation factor to apply to the disc
  36646. */
  36647. tessellation, canBeRegenerated, mesh,
  36648. /**
  36649. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36650. */
  36651. side) {
  36652. if (mesh === void 0) { mesh = null; }
  36653. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36654. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36655. _this.radius = radius;
  36656. _this.tessellation = tessellation;
  36657. _this.side = side;
  36658. return _this;
  36659. }
  36660. DiscGeometry.prototype._regenerateVertexData = function () {
  36661. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36662. };
  36663. DiscGeometry.prototype.copy = function (id) {
  36664. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36665. };
  36666. return DiscGeometry;
  36667. }(_PrimitiveGeometry));
  36668. BABYLON.DiscGeometry = DiscGeometry;
  36669. /**
  36670. * Creates a new cylinder geometry
  36671. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36672. */
  36673. var CylinderGeometry = /** @class */ (function (_super) {
  36674. __extends(CylinderGeometry, _super);
  36675. /**
  36676. * Creates a new cylinder geometry
  36677. * @param id defines the unique ID of the geometry
  36678. * @param scene defines the hosting scene
  36679. * @param height defines the height of the cylinder
  36680. * @param diameterTop defines the diameter of the cylinder's top cap
  36681. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36682. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36683. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36684. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36685. * @param mesh defines the hosting mesh (can be null)
  36686. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36687. */
  36688. function CylinderGeometry(id, scene,
  36689. /**
  36690. * Defines the height of the cylinder
  36691. */
  36692. height,
  36693. /**
  36694. * Defines the diameter of the cylinder's top cap
  36695. */
  36696. diameterTop,
  36697. /**
  36698. * Defines the diameter of the cylinder's bottom cap
  36699. */
  36700. diameterBottom,
  36701. /**
  36702. * Defines the tessellation factor to apply to the cylinder
  36703. */
  36704. tessellation,
  36705. /**
  36706. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36707. */
  36708. subdivisions, canBeRegenerated, mesh,
  36709. /**
  36710. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36711. */
  36712. side) {
  36713. if (subdivisions === void 0) { subdivisions = 1; }
  36714. if (mesh === void 0) { mesh = null; }
  36715. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36716. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36717. _this.height = height;
  36718. _this.diameterTop = diameterTop;
  36719. _this.diameterBottom = diameterBottom;
  36720. _this.tessellation = tessellation;
  36721. _this.subdivisions = subdivisions;
  36722. _this.side = side;
  36723. return _this;
  36724. }
  36725. CylinderGeometry.prototype._regenerateVertexData = function () {
  36726. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36727. };
  36728. CylinderGeometry.prototype.copy = function (id) {
  36729. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36730. };
  36731. CylinderGeometry.prototype.serialize = function () {
  36732. var serializationObject = _super.prototype.serialize.call(this);
  36733. serializationObject.height = this.height;
  36734. serializationObject.diameterTop = this.diameterTop;
  36735. serializationObject.diameterBottom = this.diameterBottom;
  36736. serializationObject.tessellation = this.tessellation;
  36737. return serializationObject;
  36738. };
  36739. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36740. if (scene.getGeometryByID(parsedCylinder.id)) {
  36741. return null; // null since geometry could be something else than a cylinder...
  36742. }
  36743. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36744. if (BABYLON.Tags) {
  36745. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36746. }
  36747. scene.pushGeometry(cylinder, true);
  36748. return cylinder;
  36749. };
  36750. return CylinderGeometry;
  36751. }(_PrimitiveGeometry));
  36752. BABYLON.CylinderGeometry = CylinderGeometry;
  36753. /**
  36754. * Creates a new torus geometry
  36755. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36756. */
  36757. var TorusGeometry = /** @class */ (function (_super) {
  36758. __extends(TorusGeometry, _super);
  36759. /**
  36760. * Creates a new torus geometry
  36761. * @param id defines the unique ID of the geometry
  36762. * @param scene defines the hosting scene
  36763. * @param diameter defines the diameter of the torus
  36764. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36765. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36766. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36767. * @param mesh defines the hosting mesh (can be null)
  36768. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36769. */
  36770. function TorusGeometry(id, scene,
  36771. /**
  36772. * Defines the diameter of the torus
  36773. */
  36774. diameter,
  36775. /**
  36776. * Defines the thickness of the torus (ie. internal diameter)
  36777. */
  36778. thickness,
  36779. /**
  36780. * Defines the tesselation factor to apply to the torus
  36781. */
  36782. tessellation, canBeRegenerated, mesh,
  36783. /**
  36784. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36785. */
  36786. side) {
  36787. if (mesh === void 0) { mesh = null; }
  36788. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36789. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36790. _this.diameter = diameter;
  36791. _this.thickness = thickness;
  36792. _this.tessellation = tessellation;
  36793. _this.side = side;
  36794. return _this;
  36795. }
  36796. TorusGeometry.prototype._regenerateVertexData = function () {
  36797. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36798. };
  36799. TorusGeometry.prototype.copy = function (id) {
  36800. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36801. };
  36802. TorusGeometry.prototype.serialize = function () {
  36803. var serializationObject = _super.prototype.serialize.call(this);
  36804. serializationObject.diameter = this.diameter;
  36805. serializationObject.thickness = this.thickness;
  36806. serializationObject.tessellation = this.tessellation;
  36807. return serializationObject;
  36808. };
  36809. TorusGeometry.Parse = function (parsedTorus, scene) {
  36810. if (scene.getGeometryByID(parsedTorus.id)) {
  36811. return null; // null since geometry could be something else than a torus...
  36812. }
  36813. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36814. if (BABYLON.Tags) {
  36815. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36816. }
  36817. scene.pushGeometry(torus, true);
  36818. return torus;
  36819. };
  36820. return TorusGeometry;
  36821. }(_PrimitiveGeometry));
  36822. BABYLON.TorusGeometry = TorusGeometry;
  36823. /**
  36824. * Creates a new ground geometry
  36825. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36826. */
  36827. var GroundGeometry = /** @class */ (function (_super) {
  36828. __extends(GroundGeometry, _super);
  36829. /**
  36830. * Creates a new ground geometry
  36831. * @param id defines the unique ID of the geometry
  36832. * @param scene defines the hosting scene
  36833. * @param width defines the width of the ground
  36834. * @param height defines the height of the ground
  36835. * @param subdivisions defines the subdivisions to apply to the ground
  36836. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36837. * @param mesh defines the hosting mesh (can be null)
  36838. */
  36839. function GroundGeometry(id, scene,
  36840. /**
  36841. * Defines the width of the ground
  36842. */
  36843. width,
  36844. /**
  36845. * Defines the height of the ground
  36846. */
  36847. height,
  36848. /**
  36849. * Defines the subdivisions to apply to the ground
  36850. */
  36851. subdivisions, canBeRegenerated, mesh) {
  36852. if (mesh === void 0) { mesh = null; }
  36853. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36854. _this.width = width;
  36855. _this.height = height;
  36856. _this.subdivisions = subdivisions;
  36857. return _this;
  36858. }
  36859. GroundGeometry.prototype._regenerateVertexData = function () {
  36860. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36861. };
  36862. GroundGeometry.prototype.copy = function (id) {
  36863. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36864. };
  36865. GroundGeometry.prototype.serialize = function () {
  36866. var serializationObject = _super.prototype.serialize.call(this);
  36867. serializationObject.width = this.width;
  36868. serializationObject.height = this.height;
  36869. serializationObject.subdivisions = this.subdivisions;
  36870. return serializationObject;
  36871. };
  36872. GroundGeometry.Parse = function (parsedGround, scene) {
  36873. if (scene.getGeometryByID(parsedGround.id)) {
  36874. return null; // null since geometry could be something else than a ground...
  36875. }
  36876. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36877. if (BABYLON.Tags) {
  36878. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36879. }
  36880. scene.pushGeometry(ground, true);
  36881. return ground;
  36882. };
  36883. return GroundGeometry;
  36884. }(_PrimitiveGeometry));
  36885. BABYLON.GroundGeometry = GroundGeometry;
  36886. /**
  36887. * Creates a tiled ground geometry
  36888. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36889. */
  36890. var TiledGroundGeometry = /** @class */ (function (_super) {
  36891. __extends(TiledGroundGeometry, _super);
  36892. /**
  36893. * Creates a tiled ground geometry
  36894. * @param id defines the unique ID of the geometry
  36895. * @param scene defines the hosting scene
  36896. * @param xmin defines the minimum value on X axis
  36897. * @param zmin defines the minimum value on Z axis
  36898. * @param xmax defines the maximum value on X axis
  36899. * @param zmax defines the maximum value on Z axis
  36900. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36901. * @param precision defines the precision to use when computing the tiles
  36902. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36903. * @param mesh defines the hosting mesh (can be null)
  36904. */
  36905. function TiledGroundGeometry(id, scene,
  36906. /**
  36907. * Defines the minimum value on X axis
  36908. */
  36909. xmin,
  36910. /**
  36911. * Defines the minimum value on Z axis
  36912. */
  36913. zmin,
  36914. /**
  36915. * Defines the maximum value on X axis
  36916. */
  36917. xmax,
  36918. /**
  36919. * Defines the maximum value on Z axis
  36920. */
  36921. zmax,
  36922. /**
  36923. * Defines the subdivisions to apply to the ground
  36924. */
  36925. subdivisions,
  36926. /**
  36927. * Defines the precision to use when computing the tiles
  36928. */
  36929. precision, canBeRegenerated, mesh) {
  36930. if (mesh === void 0) { mesh = null; }
  36931. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36932. _this.xmin = xmin;
  36933. _this.zmin = zmin;
  36934. _this.xmax = xmax;
  36935. _this.zmax = zmax;
  36936. _this.subdivisions = subdivisions;
  36937. _this.precision = precision;
  36938. return _this;
  36939. }
  36940. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36941. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36942. };
  36943. TiledGroundGeometry.prototype.copy = function (id) {
  36944. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36945. };
  36946. return TiledGroundGeometry;
  36947. }(_PrimitiveGeometry));
  36948. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36949. /**
  36950. * Creates a plane geometry
  36951. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36952. */
  36953. var PlaneGeometry = /** @class */ (function (_super) {
  36954. __extends(PlaneGeometry, _super);
  36955. /**
  36956. * Creates a plane geometry
  36957. * @param id defines the unique ID of the geometry
  36958. * @param scene defines the hosting scene
  36959. * @param size defines the size of the plane (width === height)
  36960. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36961. * @param mesh defines the hosting mesh (can be null)
  36962. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36963. */
  36964. function PlaneGeometry(id, scene,
  36965. /**
  36966. * Defines the size of the plane (width === height)
  36967. */
  36968. size, canBeRegenerated, mesh,
  36969. /**
  36970. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36971. */
  36972. side) {
  36973. if (mesh === void 0) { mesh = null; }
  36974. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36975. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36976. _this.size = size;
  36977. _this.side = side;
  36978. return _this;
  36979. }
  36980. PlaneGeometry.prototype._regenerateVertexData = function () {
  36981. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36982. };
  36983. PlaneGeometry.prototype.copy = function (id) {
  36984. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36985. };
  36986. PlaneGeometry.prototype.serialize = function () {
  36987. var serializationObject = _super.prototype.serialize.call(this);
  36988. serializationObject.size = this.size;
  36989. return serializationObject;
  36990. };
  36991. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36992. if (scene.getGeometryByID(parsedPlane.id)) {
  36993. return null; // null since geometry could be something else than a ground...
  36994. }
  36995. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36996. if (BABYLON.Tags) {
  36997. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36998. }
  36999. scene.pushGeometry(plane, true);
  37000. return plane;
  37001. };
  37002. return PlaneGeometry;
  37003. }(_PrimitiveGeometry));
  37004. BABYLON.PlaneGeometry = PlaneGeometry;
  37005. /**
  37006. * Creates a torus knot geometry
  37007. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  37008. */
  37009. var TorusKnotGeometry = /** @class */ (function (_super) {
  37010. __extends(TorusKnotGeometry, _super);
  37011. /**
  37012. * Creates a torus knot geometry
  37013. * @param id defines the unique ID of the geometry
  37014. * @param scene defines the hosting scene
  37015. * @param radius defines the radius of the torus knot
  37016. * @param tube defines the thickness of the torus knot tube
  37017. * @param radialSegments defines the number of radial segments
  37018. * @param tubularSegments defines the number of tubular segments
  37019. * @param p defines the first number of windings
  37020. * @param q defines the second number of windings
  37021. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37022. * @param mesh defines the hosting mesh (can be null)
  37023. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37024. */
  37025. function TorusKnotGeometry(id, scene,
  37026. /**
  37027. * Defines the radius of the torus knot
  37028. */
  37029. radius,
  37030. /**
  37031. * Defines the thickness of the torus knot tube
  37032. */
  37033. tube,
  37034. /**
  37035. * Defines the number of radial segments
  37036. */
  37037. radialSegments,
  37038. /**
  37039. * Defines the number of tubular segments
  37040. */
  37041. tubularSegments,
  37042. /**
  37043. * Defines the first number of windings
  37044. */
  37045. p,
  37046. /**
  37047. * Defines the second number of windings
  37048. */
  37049. q, canBeRegenerated, mesh,
  37050. /**
  37051. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37052. */
  37053. side) {
  37054. if (mesh === void 0) { mesh = null; }
  37055. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37056. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37057. _this.radius = radius;
  37058. _this.tube = tube;
  37059. _this.radialSegments = radialSegments;
  37060. _this.tubularSegments = tubularSegments;
  37061. _this.p = p;
  37062. _this.q = q;
  37063. _this.side = side;
  37064. return _this;
  37065. }
  37066. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37067. 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 });
  37068. };
  37069. TorusKnotGeometry.prototype.copy = function (id) {
  37070. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37071. };
  37072. TorusKnotGeometry.prototype.serialize = function () {
  37073. var serializationObject = _super.prototype.serialize.call(this);
  37074. serializationObject.radius = this.radius;
  37075. serializationObject.tube = this.tube;
  37076. serializationObject.radialSegments = this.radialSegments;
  37077. serializationObject.tubularSegments = this.tubularSegments;
  37078. serializationObject.p = this.p;
  37079. serializationObject.q = this.q;
  37080. return serializationObject;
  37081. };
  37082. ;
  37083. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37084. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37085. return null; // null since geometry could be something else than a ground...
  37086. }
  37087. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37088. if (BABYLON.Tags) {
  37089. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37090. }
  37091. scene.pushGeometry(torusKnot, true);
  37092. return torusKnot;
  37093. };
  37094. return TorusKnotGeometry;
  37095. }(_PrimitiveGeometry));
  37096. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37097. //}
  37098. })(BABYLON || (BABYLON = {}));
  37099. //# sourceMappingURL=babylon.geometry.js.map
  37100. "use strict";
  37101. var BABYLON;
  37102. (function (BABYLON) {
  37103. /**
  37104. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37105. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37106. */
  37107. var PostProcessManager = /** @class */ (function () {
  37108. /**
  37109. * Creates a new instance of @see PostProcess
  37110. * @param scene The scene that the post process is associated with.
  37111. */
  37112. function PostProcessManager(scene) {
  37113. this._vertexBuffers = {};
  37114. this._scene = scene;
  37115. }
  37116. PostProcessManager.prototype._prepareBuffers = function () {
  37117. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37118. return;
  37119. }
  37120. // VBO
  37121. var vertices = [];
  37122. vertices.push(1, 1);
  37123. vertices.push(-1, 1);
  37124. vertices.push(-1, -1);
  37125. vertices.push(1, -1);
  37126. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37127. this._buildIndexBuffer();
  37128. };
  37129. PostProcessManager.prototype._buildIndexBuffer = function () {
  37130. // Indices
  37131. var indices = [];
  37132. indices.push(0);
  37133. indices.push(1);
  37134. indices.push(2);
  37135. indices.push(0);
  37136. indices.push(2);
  37137. indices.push(3);
  37138. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37139. };
  37140. /**
  37141. * Rebuilds the vertex buffers of the manager.
  37142. */
  37143. PostProcessManager.prototype._rebuild = function () {
  37144. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37145. if (!vb) {
  37146. return;
  37147. }
  37148. vb._rebuild();
  37149. this._buildIndexBuffer();
  37150. };
  37151. // Methods
  37152. /**
  37153. * Prepares a frame to be run through a post process.
  37154. * @param sourceTexture The input texture to the post procesess. (default: null)
  37155. * @param postProcesses An array of post processes to be run. (default: null)
  37156. * @returns True if the post processes were able to be run.
  37157. */
  37158. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37159. if (sourceTexture === void 0) { sourceTexture = null; }
  37160. if (postProcesses === void 0) { postProcesses = null; }
  37161. var camera = this._scene.activeCamera;
  37162. if (!camera) {
  37163. return false;
  37164. }
  37165. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37166. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37167. return false;
  37168. }
  37169. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37170. return true;
  37171. };
  37172. /**
  37173. * Manually render a set of post processes to a texture.
  37174. * @param postProcesses An array of post processes to be run.
  37175. * @param targetTexture The target texture to render to.
  37176. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37177. */
  37178. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37179. if (targetTexture === void 0) { targetTexture = null; }
  37180. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37181. var engine = this._scene.getEngine();
  37182. for (var index = 0; index < postProcesses.length; index++) {
  37183. if (index < postProcesses.length - 1) {
  37184. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37185. }
  37186. else {
  37187. if (targetTexture) {
  37188. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37189. }
  37190. else {
  37191. engine.restoreDefaultFramebuffer();
  37192. }
  37193. }
  37194. var pp = postProcesses[index];
  37195. var effect = pp.apply();
  37196. if (effect) {
  37197. pp.onBeforeRenderObservable.notifyObservers(effect);
  37198. // VBOs
  37199. this._prepareBuffers();
  37200. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37201. // Draw order
  37202. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37203. pp.onAfterRenderObservable.notifyObservers(effect);
  37204. }
  37205. }
  37206. // Restore depth buffer
  37207. engine.setDepthBuffer(true);
  37208. engine.setDepthWrite(true);
  37209. };
  37210. /**
  37211. * Finalize the result of the output of the postprocesses.
  37212. * @param doNotPresent If true the result will not be displayed to the screen.
  37213. * @param targetTexture The target texture to render to.
  37214. * @param faceIndex The index of the face to bind the target texture to.
  37215. * @param postProcesses The array of post processes to render.
  37216. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37217. */
  37218. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37219. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37220. var camera = this._scene.activeCamera;
  37221. if (!camera) {
  37222. return;
  37223. }
  37224. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37225. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37226. return;
  37227. }
  37228. var engine = this._scene.getEngine();
  37229. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37230. var pp = postProcesses[index];
  37231. if (index < len - 1) {
  37232. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37233. }
  37234. else {
  37235. if (targetTexture) {
  37236. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37237. }
  37238. else {
  37239. engine.restoreDefaultFramebuffer();
  37240. }
  37241. }
  37242. if (doNotPresent) {
  37243. break;
  37244. }
  37245. var effect = pp.apply();
  37246. if (effect) {
  37247. pp.onBeforeRenderObservable.notifyObservers(effect);
  37248. // VBOs
  37249. this._prepareBuffers();
  37250. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37251. // Draw order
  37252. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37253. pp.onAfterRenderObservable.notifyObservers(effect);
  37254. }
  37255. }
  37256. // Restore states
  37257. engine.setDepthBuffer(true);
  37258. engine.setDepthWrite(true);
  37259. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37260. };
  37261. /**
  37262. * Disposes of the post process manager.
  37263. */
  37264. PostProcessManager.prototype.dispose = function () {
  37265. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37266. if (buffer) {
  37267. buffer.dispose();
  37268. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37269. }
  37270. if (this._indexBuffer) {
  37271. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37272. this._indexBuffer = null;
  37273. }
  37274. };
  37275. return PostProcessManager;
  37276. }());
  37277. BABYLON.PostProcessManager = PostProcessManager;
  37278. })(BABYLON || (BABYLON = {}));
  37279. //# sourceMappingURL=babylon.postProcessManager.js.map
  37280. "use strict";
  37281. var BABYLON;
  37282. (function (BABYLON) {
  37283. /**
  37284. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37285. */
  37286. var PerformanceMonitor = /** @class */ (function () {
  37287. /**
  37288. * constructor
  37289. * @param frameSampleSize The number of samples required to saturate the sliding window
  37290. */
  37291. function PerformanceMonitor(frameSampleSize) {
  37292. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37293. this._enabled = true;
  37294. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37295. }
  37296. /**
  37297. * Samples current frame
  37298. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37299. */
  37300. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37301. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37302. if (!this._enabled)
  37303. return;
  37304. if (this._lastFrameTimeMs != null) {
  37305. var dt = timeMs - this._lastFrameTimeMs;
  37306. this._rollingFrameTime.add(dt);
  37307. }
  37308. this._lastFrameTimeMs = timeMs;
  37309. };
  37310. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37311. /**
  37312. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37313. * @return Average frame time in milliseconds
  37314. */
  37315. get: function () {
  37316. return this._rollingFrameTime.average;
  37317. },
  37318. enumerable: true,
  37319. configurable: true
  37320. });
  37321. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37322. /**
  37323. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37324. * @return Frame time variance in milliseconds squared
  37325. */
  37326. get: function () {
  37327. return this._rollingFrameTime.variance;
  37328. },
  37329. enumerable: true,
  37330. configurable: true
  37331. });
  37332. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37333. /**
  37334. * Returns the frame time of the most recent frame
  37335. * @return Frame time in milliseconds
  37336. */
  37337. get: function () {
  37338. return this._rollingFrameTime.history(0);
  37339. },
  37340. enumerable: true,
  37341. configurable: true
  37342. });
  37343. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37344. /**
  37345. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37346. * @return Framerate in frames per second
  37347. */
  37348. get: function () {
  37349. return 1000.0 / this._rollingFrameTime.average;
  37350. },
  37351. enumerable: true,
  37352. configurable: true
  37353. });
  37354. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37355. /**
  37356. * Returns the average framerate in frames per second using the most recent frame time
  37357. * @return Framerate in frames per second
  37358. */
  37359. get: function () {
  37360. var history = this._rollingFrameTime.history(0);
  37361. if (history === 0) {
  37362. return 0;
  37363. }
  37364. return 1000.0 / history;
  37365. },
  37366. enumerable: true,
  37367. configurable: true
  37368. });
  37369. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37370. /**
  37371. * Returns true if enough samples have been taken to completely fill the sliding window
  37372. * @return true if saturated
  37373. */
  37374. get: function () {
  37375. return this._rollingFrameTime.isSaturated();
  37376. },
  37377. enumerable: true,
  37378. configurable: true
  37379. });
  37380. /**
  37381. * Enables contributions to the sliding window sample set
  37382. */
  37383. PerformanceMonitor.prototype.enable = function () {
  37384. this._enabled = true;
  37385. };
  37386. /**
  37387. * Disables contributions to the sliding window sample set
  37388. * Samples will not be interpolated over the disabled period
  37389. */
  37390. PerformanceMonitor.prototype.disable = function () {
  37391. this._enabled = false;
  37392. //clear last sample to avoid interpolating over the disabled period when next enabled
  37393. this._lastFrameTimeMs = null;
  37394. };
  37395. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37396. /**
  37397. * Returns true if sampling is enabled
  37398. * @return true if enabled
  37399. */
  37400. get: function () {
  37401. return this._enabled;
  37402. },
  37403. enumerable: true,
  37404. configurable: true
  37405. });
  37406. /**
  37407. * Resets performance monitor
  37408. */
  37409. PerformanceMonitor.prototype.reset = function () {
  37410. //clear last sample to avoid interpolating over the disabled period when next enabled
  37411. this._lastFrameTimeMs = null;
  37412. //wipe record
  37413. this._rollingFrameTime.reset();
  37414. };
  37415. return PerformanceMonitor;
  37416. }());
  37417. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37418. /**
  37419. * RollingAverage
  37420. *
  37421. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37422. */
  37423. var RollingAverage = /** @class */ (function () {
  37424. /**
  37425. * constructor
  37426. * @param length The number of samples required to saturate the sliding window
  37427. */
  37428. function RollingAverage(length) {
  37429. this._samples = new Array(length);
  37430. this.reset();
  37431. }
  37432. /**
  37433. * Adds a sample to the sample set
  37434. * @param v The sample value
  37435. */
  37436. RollingAverage.prototype.add = function (v) {
  37437. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37438. var delta;
  37439. //we need to check if we've already wrapped round
  37440. if (this.isSaturated()) {
  37441. //remove bottom of stack from mean
  37442. var bottomValue = this._samples[this._pos];
  37443. delta = bottomValue - this.average;
  37444. this.average -= delta / (this._sampleCount - 1);
  37445. this._m2 -= delta * (bottomValue - this.average);
  37446. }
  37447. else {
  37448. this._sampleCount++;
  37449. }
  37450. //add new value to mean
  37451. delta = v - this.average;
  37452. this.average += delta / (this._sampleCount);
  37453. this._m2 += delta * (v - this.average);
  37454. //set the new variance
  37455. this.variance = this._m2 / (this._sampleCount - 1);
  37456. this._samples[this._pos] = v;
  37457. this._pos++;
  37458. this._pos %= this._samples.length; //positive wrap around
  37459. };
  37460. /**
  37461. * Returns previously added values or null if outside of history or outside the sliding window domain
  37462. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37463. * @return Value previously recorded with add() or null if outside of range
  37464. */
  37465. RollingAverage.prototype.history = function (i) {
  37466. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37467. return 0;
  37468. }
  37469. var i0 = this._wrapPosition(this._pos - 1.0);
  37470. return this._samples[this._wrapPosition(i0 - i)];
  37471. };
  37472. /**
  37473. * Returns true if enough samples have been taken to completely fill the sliding window
  37474. * @return true if sample-set saturated
  37475. */
  37476. RollingAverage.prototype.isSaturated = function () {
  37477. return this._sampleCount >= this._samples.length;
  37478. };
  37479. /**
  37480. * Resets the rolling average (equivalent to 0 samples taken so far)
  37481. */
  37482. RollingAverage.prototype.reset = function () {
  37483. this.average = 0;
  37484. this.variance = 0;
  37485. this._sampleCount = 0;
  37486. this._pos = 0;
  37487. this._m2 = 0;
  37488. };
  37489. /**
  37490. * Wraps a value around the sample range boundaries
  37491. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37492. * @return Wrapped position in sample range
  37493. */
  37494. RollingAverage.prototype._wrapPosition = function (i) {
  37495. var max = this._samples.length;
  37496. return ((i % max) + max) % max;
  37497. };
  37498. return RollingAverage;
  37499. }());
  37500. BABYLON.RollingAverage = RollingAverage;
  37501. })(BABYLON || (BABYLON = {}));
  37502. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37503. "use strict";
  37504. var BABYLON;
  37505. (function (BABYLON) {
  37506. /**
  37507. * This groups together the common properties used for image processing either in direct forward pass
  37508. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37509. * or not.
  37510. */
  37511. var ImageProcessingConfiguration = /** @class */ (function () {
  37512. function ImageProcessingConfiguration() {
  37513. /**
  37514. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37515. */
  37516. this.colorCurves = new BABYLON.ColorCurves();
  37517. this._colorCurvesEnabled = false;
  37518. this._colorGradingEnabled = false;
  37519. this._colorGradingWithGreenDepth = true;
  37520. this._colorGradingBGR = true;
  37521. this._exposure = 1.0;
  37522. this._toneMappingEnabled = false;
  37523. this._contrast = 1.0;
  37524. /**
  37525. * Vignette stretch size.
  37526. */
  37527. this.vignetteStretch = 0;
  37528. /**
  37529. * Vignette centre X Offset.
  37530. */
  37531. this.vignetteCentreX = 0;
  37532. /**
  37533. * Vignette centre Y Offset.
  37534. */
  37535. this.vignetteCentreY = 0;
  37536. /**
  37537. * Vignette weight or intensity of the vignette effect.
  37538. */
  37539. this.vignetteWeight = 1.5;
  37540. /**
  37541. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37542. * if vignetteEnabled is set to true.
  37543. */
  37544. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37545. /**
  37546. * Camera field of view used by the Vignette effect.
  37547. */
  37548. this.vignetteCameraFov = 0.5;
  37549. this._grainEnabled = false;
  37550. this._grainIntensity = 30;
  37551. this._grainAnimated = false;
  37552. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37553. this._vignetteEnabled = false;
  37554. this._applyByPostProcess = false;
  37555. this._isEnabled = true;
  37556. /**
  37557. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37558. * @type {BABYLON.Observable}
  37559. */
  37560. this.onUpdateParameters = new BABYLON.Observable();
  37561. }
  37562. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37563. /**
  37564. * Gets wether the color curves effect is enabled.
  37565. */
  37566. get: function () {
  37567. return this._colorCurvesEnabled;
  37568. },
  37569. /**
  37570. * Sets wether the color curves effect is enabled.
  37571. */
  37572. set: function (value) {
  37573. if (this._colorCurvesEnabled === value) {
  37574. return;
  37575. }
  37576. this._colorCurvesEnabled = value;
  37577. this._updateParameters();
  37578. },
  37579. enumerable: true,
  37580. configurable: true
  37581. });
  37582. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37583. /**
  37584. * Gets wether the color grading effect is enabled.
  37585. */
  37586. get: function () {
  37587. return this._colorGradingEnabled;
  37588. },
  37589. /**
  37590. * Sets wether the color grading effect is enabled.
  37591. */
  37592. set: function (value) {
  37593. if (this._colorGradingEnabled === value) {
  37594. return;
  37595. }
  37596. this._colorGradingEnabled = value;
  37597. this._updateParameters();
  37598. },
  37599. enumerable: true,
  37600. configurable: true
  37601. });
  37602. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37603. /**
  37604. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37605. */
  37606. get: function () {
  37607. return this._colorGradingWithGreenDepth;
  37608. },
  37609. /**
  37610. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37611. */
  37612. set: function (value) {
  37613. if (this._colorGradingWithGreenDepth === value) {
  37614. return;
  37615. }
  37616. this._colorGradingWithGreenDepth = value;
  37617. this._updateParameters();
  37618. },
  37619. enumerable: true,
  37620. configurable: true
  37621. });
  37622. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37623. /**
  37624. * Gets wether the color grading texture contains BGR values.
  37625. */
  37626. get: function () {
  37627. return this._colorGradingBGR;
  37628. },
  37629. /**
  37630. * Sets wether the color grading texture contains BGR values.
  37631. */
  37632. set: function (value) {
  37633. if (this._colorGradingBGR === value) {
  37634. return;
  37635. }
  37636. this._colorGradingBGR = value;
  37637. this._updateParameters();
  37638. },
  37639. enumerable: true,
  37640. configurable: true
  37641. });
  37642. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37643. /**
  37644. * Gets the Exposure used in the effect.
  37645. */
  37646. get: function () {
  37647. return this._exposure;
  37648. },
  37649. /**
  37650. * Sets the Exposure used in the effect.
  37651. */
  37652. set: function (value) {
  37653. if (this._exposure === value) {
  37654. return;
  37655. }
  37656. this._exposure = value;
  37657. this._updateParameters();
  37658. },
  37659. enumerable: true,
  37660. configurable: true
  37661. });
  37662. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37663. /**
  37664. * Gets wether the tone mapping effect is enabled.
  37665. */
  37666. get: function () {
  37667. return this._toneMappingEnabled;
  37668. },
  37669. /**
  37670. * Sets wether the tone mapping effect is enabled.
  37671. */
  37672. set: function (value) {
  37673. if (this._toneMappingEnabled === value) {
  37674. return;
  37675. }
  37676. this._toneMappingEnabled = value;
  37677. this._updateParameters();
  37678. },
  37679. enumerable: true,
  37680. configurable: true
  37681. });
  37682. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37683. /**
  37684. * Gets the contrast used in the effect.
  37685. */
  37686. get: function () {
  37687. return this._contrast;
  37688. },
  37689. /**
  37690. * Sets the contrast used in the effect.
  37691. */
  37692. set: function (value) {
  37693. if (this._contrast === value) {
  37694. return;
  37695. }
  37696. this._contrast = value;
  37697. this._updateParameters();
  37698. },
  37699. enumerable: true,
  37700. configurable: true
  37701. });
  37702. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37703. /**
  37704. * If the grain effect should be enabled.
  37705. */
  37706. get: function () {
  37707. return this._grainEnabled;
  37708. },
  37709. set: function (value) {
  37710. if (this._grainEnabled === value) {
  37711. return;
  37712. }
  37713. this._grainEnabled = value;
  37714. this._updateParameters();
  37715. },
  37716. enumerable: true,
  37717. configurable: true
  37718. });
  37719. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37720. /**
  37721. * Amount of grain to be applied by the grain effect.
  37722. */
  37723. get: function () {
  37724. return this._grainIntensity;
  37725. },
  37726. set: function (value) {
  37727. if (this._grainIntensity === value) {
  37728. return;
  37729. }
  37730. this._grainIntensity = value;
  37731. },
  37732. enumerable: true,
  37733. configurable: true
  37734. });
  37735. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37736. /**
  37737. * If the grain effect should be animated.
  37738. */
  37739. get: function () {
  37740. return this._grainAnimated;
  37741. },
  37742. set: function (value) {
  37743. if (this._grainAnimated === value) {
  37744. return;
  37745. }
  37746. this._grainAnimated = value;
  37747. this._updateParameters();
  37748. },
  37749. enumerable: true,
  37750. configurable: true
  37751. });
  37752. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37753. /**
  37754. * Gets the vignette blend mode allowing different kind of effect.
  37755. */
  37756. get: function () {
  37757. return this._vignetteBlendMode;
  37758. },
  37759. /**
  37760. * Sets the vignette blend mode allowing different kind of effect.
  37761. */
  37762. set: function (value) {
  37763. if (this._vignetteBlendMode === value) {
  37764. return;
  37765. }
  37766. this._vignetteBlendMode = value;
  37767. this._updateParameters();
  37768. },
  37769. enumerable: true,
  37770. configurable: true
  37771. });
  37772. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37773. /**
  37774. * Gets wether the vignette effect is enabled.
  37775. */
  37776. get: function () {
  37777. return this._vignetteEnabled;
  37778. },
  37779. /**
  37780. * Sets wether the vignette effect is enabled.
  37781. */
  37782. set: function (value) {
  37783. if (this._vignetteEnabled === value) {
  37784. return;
  37785. }
  37786. this._vignetteEnabled = value;
  37787. this._updateParameters();
  37788. },
  37789. enumerable: true,
  37790. configurable: true
  37791. });
  37792. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37793. /**
  37794. * Gets wether the image processing is applied through a post process or not.
  37795. */
  37796. get: function () {
  37797. return this._applyByPostProcess;
  37798. },
  37799. /**
  37800. * Sets wether the image processing is applied through a post process or not.
  37801. */
  37802. set: function (value) {
  37803. if (this._applyByPostProcess === value) {
  37804. return;
  37805. }
  37806. this._applyByPostProcess = value;
  37807. this._updateParameters();
  37808. },
  37809. enumerable: true,
  37810. configurable: true
  37811. });
  37812. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37813. /**
  37814. * Gets wether the image processing is enabled or not.
  37815. */
  37816. get: function () {
  37817. return this._isEnabled;
  37818. },
  37819. /**
  37820. * Sets wether the image processing is enabled or not.
  37821. */
  37822. set: function (value) {
  37823. if (this._isEnabled === value) {
  37824. return;
  37825. }
  37826. this._isEnabled = value;
  37827. this._updateParameters();
  37828. },
  37829. enumerable: true,
  37830. configurable: true
  37831. });
  37832. /**
  37833. * Method called each time the image processing information changes requires to recompile the effect.
  37834. */
  37835. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37836. this.onUpdateParameters.notifyObservers(this);
  37837. };
  37838. ImageProcessingConfiguration.prototype.getClassName = function () {
  37839. return "ImageProcessingConfiguration";
  37840. };
  37841. /**
  37842. * Prepare the list of uniforms associated with the Image Processing effects.
  37843. * @param uniformsList The list of uniforms used in the effect
  37844. * @param defines the list of defines currently in use
  37845. */
  37846. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37847. if (defines.EXPOSURE) {
  37848. uniforms.push("exposureLinear");
  37849. }
  37850. if (defines.CONTRAST) {
  37851. uniforms.push("contrast");
  37852. }
  37853. if (defines.COLORGRADING) {
  37854. uniforms.push("colorTransformSettings");
  37855. }
  37856. if (defines.VIGNETTE) {
  37857. uniforms.push("vInverseScreenSize");
  37858. uniforms.push("vignetteSettings1");
  37859. uniforms.push("vignetteSettings2");
  37860. }
  37861. if (defines.COLORCURVES) {
  37862. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37863. }
  37864. if (defines.GRAIN) {
  37865. uniforms.push("grainVarianceAmount");
  37866. uniforms.push("grainAnimatedSeed");
  37867. }
  37868. };
  37869. /**
  37870. * Prepare the list of samplers associated with the Image Processing effects.
  37871. * @param uniformsList The list of uniforms used in the effect
  37872. * @param defines the list of defines currently in use
  37873. */
  37874. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37875. if (defines.COLORGRADING) {
  37876. samplersList.push("txColorTransform");
  37877. }
  37878. };
  37879. /**
  37880. * Prepare the list of defines associated to the shader.
  37881. * @param defines the list of defines to complete
  37882. */
  37883. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37884. if (forPostProcess === void 0) { forPostProcess = false; }
  37885. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37886. defines.VIGNETTE = false;
  37887. defines.TONEMAPPING = false;
  37888. defines.CONTRAST = false;
  37889. defines.EXPOSURE = false;
  37890. defines.COLORCURVES = false;
  37891. defines.COLORGRADING = false;
  37892. defines.COLORGRADING3D = false;
  37893. defines.IMAGEPROCESSING = false;
  37894. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37895. return;
  37896. }
  37897. defines.VIGNETTE = this.vignetteEnabled;
  37898. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37899. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37900. defines.TONEMAPPING = this.toneMappingEnabled;
  37901. defines.CONTRAST = (this.contrast !== 1.0);
  37902. defines.EXPOSURE = (this.exposure !== 1.0);
  37903. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37904. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37905. if (defines.COLORGRADING) {
  37906. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37907. }
  37908. else {
  37909. defines.COLORGRADING3D = false;
  37910. }
  37911. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37912. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37913. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37914. defines.GRAIN = this.grainEnabled;
  37915. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37916. };
  37917. /**
  37918. * Returns true if all the image processing information are ready.
  37919. */
  37920. ImageProcessingConfiguration.prototype.isReady = function () {
  37921. // Color Grading texure can not be none blocking.
  37922. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37923. };
  37924. /**
  37925. * Binds the image processing to the shader.
  37926. * @param effect The effect to bind to
  37927. */
  37928. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37929. if (aspectRatio === void 0) { aspectRatio = 1; }
  37930. // Color Curves
  37931. if (this._colorCurvesEnabled && this.colorCurves) {
  37932. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37933. }
  37934. // Vignette
  37935. if (this._vignetteEnabled) {
  37936. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37937. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37938. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37939. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37940. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37941. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37942. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37943. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37944. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37945. var vignettePower = -2.0 * this.vignetteWeight;
  37946. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37947. }
  37948. // Exposure
  37949. effect.setFloat("exposureLinear", this.exposure);
  37950. // Contrast
  37951. effect.setFloat("contrast", this.contrast);
  37952. // Color transform settings
  37953. if (this.colorGradingTexture) {
  37954. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37955. var textureSize = this.colorGradingTexture.getSize().height;
  37956. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37957. 0.5 / textureSize, // textureOffset
  37958. textureSize, // textureSize
  37959. this.colorGradingTexture.level // weight
  37960. );
  37961. }
  37962. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37963. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37964. };
  37965. /**
  37966. * Clones the current image processing instance.
  37967. * @return The cloned image processing
  37968. */
  37969. ImageProcessingConfiguration.prototype.clone = function () {
  37970. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37971. };
  37972. /**
  37973. * Serializes the current image processing instance to a json representation.
  37974. * @return a JSON representation
  37975. */
  37976. ImageProcessingConfiguration.prototype.serialize = function () {
  37977. return BABYLON.SerializationHelper.Serialize(this);
  37978. };
  37979. /**
  37980. * Parses the image processing from a json representation.
  37981. * @param source the JSON source to parse
  37982. * @return The parsed image processing
  37983. */
  37984. ImageProcessingConfiguration.Parse = function (source) {
  37985. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37986. };
  37987. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37988. /**
  37989. * Used to apply the vignette as a mix with the pixel color.
  37990. */
  37991. get: function () {
  37992. return this._VIGNETTEMODE_MULTIPLY;
  37993. },
  37994. enumerable: true,
  37995. configurable: true
  37996. });
  37997. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37998. /**
  37999. * Used to apply the vignette as a replacement of the pixel color.
  38000. */
  38001. get: function () {
  38002. return this._VIGNETTEMODE_OPAQUE;
  38003. },
  38004. enumerable: true,
  38005. configurable: true
  38006. });
  38007. // Static constants associated to the image processing.
  38008. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  38009. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  38010. __decorate([
  38011. BABYLON.serializeAsColorCurves()
  38012. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  38013. __decorate([
  38014. BABYLON.serialize()
  38015. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  38016. __decorate([
  38017. BABYLON.serializeAsTexture()
  38018. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  38019. __decorate([
  38020. BABYLON.serialize()
  38021. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  38022. __decorate([
  38023. BABYLON.serialize()
  38024. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  38025. __decorate([
  38026. BABYLON.serialize()
  38027. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  38028. __decorate([
  38029. BABYLON.serialize()
  38030. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  38031. __decorate([
  38032. BABYLON.serialize()
  38033. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  38034. __decorate([
  38035. BABYLON.serialize()
  38036. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  38037. __decorate([
  38038. BABYLON.serialize()
  38039. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  38040. __decorate([
  38041. BABYLON.serialize()
  38042. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  38043. __decorate([
  38044. BABYLON.serialize()
  38045. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  38046. __decorate([
  38047. BABYLON.serialize()
  38048. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  38049. __decorate([
  38050. BABYLON.serializeAsColor4()
  38051. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  38052. __decorate([
  38053. BABYLON.serialize()
  38054. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  38055. __decorate([
  38056. BABYLON.serialize()
  38057. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  38058. __decorate([
  38059. BABYLON.serialize()
  38060. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  38061. __decorate([
  38062. BABYLON.serialize()
  38063. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  38064. __decorate([
  38065. BABYLON.serialize()
  38066. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38067. __decorate([
  38068. BABYLON.serialize()
  38069. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38070. __decorate([
  38071. BABYLON.serialize()
  38072. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38073. __decorate([
  38074. BABYLON.serialize()
  38075. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38076. return ImageProcessingConfiguration;
  38077. }());
  38078. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38079. })(BABYLON || (BABYLON = {}));
  38080. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38081. "use strict";
  38082. var BABYLON;
  38083. (function (BABYLON) {
  38084. /**
  38085. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38086. * It can help converting any input color in a desired output one. This can then be used to create effects
  38087. * from sepia, black and white to sixties or futuristic rendering...
  38088. *
  38089. * The only supported format is currently 3dl.
  38090. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38091. */
  38092. var ColorGradingTexture = /** @class */ (function (_super) {
  38093. __extends(ColorGradingTexture, _super);
  38094. /**
  38095. * Instantiates a ColorGradingTexture from the following parameters.
  38096. *
  38097. * @param url The location of the color gradind data (currently only supporting 3dl)
  38098. * @param scene The scene the texture will be used in
  38099. */
  38100. function ColorGradingTexture(url, scene) {
  38101. var _this = _super.call(this, scene) || this;
  38102. if (!url) {
  38103. return _this;
  38104. }
  38105. _this._engine = scene.getEngine();
  38106. _this._textureMatrix = BABYLON.Matrix.Identity();
  38107. _this.name = url;
  38108. _this.url = url;
  38109. _this.hasAlpha = false;
  38110. _this.isCube = false;
  38111. _this.is3D = _this._engine.webGLVersion > 1;
  38112. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38113. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38114. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38115. _this.anisotropicFilteringLevel = 1;
  38116. _this._texture = _this._getFromCache(url, true);
  38117. if (!_this._texture) {
  38118. if (!scene.useDelayedTextureLoading) {
  38119. _this.loadTexture();
  38120. }
  38121. else {
  38122. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38123. }
  38124. }
  38125. return _this;
  38126. }
  38127. /**
  38128. * Returns the texture matrix used in most of the material.
  38129. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38130. */
  38131. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38132. return this._textureMatrix;
  38133. };
  38134. /**
  38135. * Occurs when the file being loaded is a .3dl LUT file.
  38136. */
  38137. ColorGradingTexture.prototype.load3dlTexture = function () {
  38138. var engine = this._engine;
  38139. var texture;
  38140. if (engine.webGLVersion === 1) {
  38141. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38142. }
  38143. else {
  38144. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38145. }
  38146. this._texture = texture;
  38147. var callback = function (text) {
  38148. if (typeof text !== "string") {
  38149. return;
  38150. }
  38151. var data = null;
  38152. var tempData = null;
  38153. var line;
  38154. var lines = text.split('\n');
  38155. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38156. var maxColor = 0;
  38157. for (var i = 0; i < lines.length; i++) {
  38158. line = lines[i];
  38159. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38160. continue;
  38161. if (line.indexOf('#') === 0)
  38162. continue;
  38163. var words = line.split(" ");
  38164. if (size === 0) {
  38165. // Number of space + one
  38166. size = words.length;
  38167. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38168. tempData = new Float32Array(size * size * size * 4);
  38169. continue;
  38170. }
  38171. if (size != 0) {
  38172. var r = Math.max(parseInt(words[0]), 0);
  38173. var g = Math.max(parseInt(words[1]), 0);
  38174. var b = Math.max(parseInt(words[2]), 0);
  38175. maxColor = Math.max(r, maxColor);
  38176. maxColor = Math.max(g, maxColor);
  38177. maxColor = Math.max(b, maxColor);
  38178. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38179. if (tempData) {
  38180. tempData[pixelStorageIndex + 0] = r;
  38181. tempData[pixelStorageIndex + 1] = g;
  38182. tempData[pixelStorageIndex + 2] = b;
  38183. }
  38184. pixelIndexSlice++;
  38185. if (pixelIndexSlice % size == 0) {
  38186. pixelIndexH++;
  38187. pixelIndexSlice = 0;
  38188. if (pixelIndexH % size == 0) {
  38189. pixelIndexW++;
  38190. pixelIndexH = 0;
  38191. }
  38192. }
  38193. }
  38194. }
  38195. if (tempData && data) {
  38196. for (var i = 0; i < tempData.length; i++) {
  38197. if (i > 0 && (i + 1) % 4 === 0) {
  38198. data[i] = 255;
  38199. }
  38200. else {
  38201. var value = tempData[i];
  38202. data[i] = (value / maxColor * 255);
  38203. }
  38204. }
  38205. }
  38206. if (texture.is3D) {
  38207. texture.updateSize(size, size, size);
  38208. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38209. }
  38210. else {
  38211. texture.updateSize(size * size, size);
  38212. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38213. }
  38214. };
  38215. var scene = this.getScene();
  38216. if (scene) {
  38217. scene._loadFile(this.url, callback);
  38218. }
  38219. else {
  38220. this._engine._loadFile(this.url, callback);
  38221. }
  38222. return this._texture;
  38223. };
  38224. /**
  38225. * Starts the loading process of the texture.
  38226. */
  38227. ColorGradingTexture.prototype.loadTexture = function () {
  38228. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38229. this.load3dlTexture();
  38230. }
  38231. };
  38232. /**
  38233. * Clones the color gradind texture.
  38234. */
  38235. ColorGradingTexture.prototype.clone = function () {
  38236. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38237. // Base texture
  38238. newTexture.level = this.level;
  38239. return newTexture;
  38240. };
  38241. /**
  38242. * Called during delayed load for textures.
  38243. */
  38244. ColorGradingTexture.prototype.delayLoad = function () {
  38245. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38246. return;
  38247. }
  38248. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38249. this._texture = this._getFromCache(this.url, true);
  38250. if (!this._texture) {
  38251. this.loadTexture();
  38252. }
  38253. };
  38254. /**
  38255. * Parses a color grading texture serialized by Babylon.
  38256. * @param parsedTexture The texture information being parsedTexture
  38257. * @param scene The scene to load the texture in
  38258. * @param rootUrl The root url of the data assets to load
  38259. * @return A color gradind texture
  38260. */
  38261. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38262. var texture = null;
  38263. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38264. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38265. texture.name = parsedTexture.name;
  38266. texture.level = parsedTexture.level;
  38267. }
  38268. return texture;
  38269. };
  38270. /**
  38271. * Serializes the LUT texture to json format.
  38272. */
  38273. ColorGradingTexture.prototype.serialize = function () {
  38274. if (!this.name) {
  38275. return null;
  38276. }
  38277. var serializationObject = {};
  38278. serializationObject.name = this.name;
  38279. serializationObject.level = this.level;
  38280. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38281. return serializationObject;
  38282. };
  38283. /**
  38284. * Empty line regex stored for GC.
  38285. */
  38286. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38287. return ColorGradingTexture;
  38288. }(BABYLON.BaseTexture));
  38289. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38290. })(BABYLON || (BABYLON = {}));
  38291. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38292. "use strict";
  38293. var BABYLON;
  38294. (function (BABYLON) {
  38295. /**
  38296. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38297. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38298. * 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;
  38299. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38300. */
  38301. var ColorCurves = /** @class */ (function () {
  38302. function ColorCurves() {
  38303. this._dirty = true;
  38304. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38305. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38306. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38307. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38308. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38309. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38310. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38311. this._globalHue = 30;
  38312. this._globalDensity = 0;
  38313. this._globalSaturation = 0;
  38314. this._globalExposure = 0;
  38315. this._highlightsHue = 30;
  38316. this._highlightsDensity = 0;
  38317. this._highlightsSaturation = 0;
  38318. this._highlightsExposure = 0;
  38319. this._midtonesHue = 30;
  38320. this._midtonesDensity = 0;
  38321. this._midtonesSaturation = 0;
  38322. this._midtonesExposure = 0;
  38323. this._shadowsHue = 30;
  38324. this._shadowsDensity = 0;
  38325. this._shadowsSaturation = 0;
  38326. this._shadowsExposure = 0;
  38327. }
  38328. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38329. /**
  38330. * Gets the global Hue value.
  38331. * 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).
  38332. */
  38333. get: function () {
  38334. return this._globalHue;
  38335. },
  38336. /**
  38337. * Sets the global Hue value.
  38338. * 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).
  38339. */
  38340. set: function (value) {
  38341. this._globalHue = value;
  38342. this._dirty = true;
  38343. },
  38344. enumerable: true,
  38345. configurable: true
  38346. });
  38347. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38348. /**
  38349. * Gets the global Density value.
  38350. * 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.
  38351. * Values less than zero provide a filter of opposite hue.
  38352. */
  38353. get: function () {
  38354. return this._globalDensity;
  38355. },
  38356. /**
  38357. * Sets the global Density value.
  38358. * 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.
  38359. * Values less than zero provide a filter of opposite hue.
  38360. */
  38361. set: function (value) {
  38362. this._globalDensity = value;
  38363. this._dirty = true;
  38364. },
  38365. enumerable: true,
  38366. configurable: true
  38367. });
  38368. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38369. /**
  38370. * Gets the global Saturation value.
  38371. * 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.
  38372. */
  38373. get: function () {
  38374. return this._globalSaturation;
  38375. },
  38376. /**
  38377. * Sets the global Saturation value.
  38378. * 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.
  38379. */
  38380. set: function (value) {
  38381. this._globalSaturation = value;
  38382. this._dirty = true;
  38383. },
  38384. enumerable: true,
  38385. configurable: true
  38386. });
  38387. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38388. /**
  38389. * Gets the highlights Hue value.
  38390. * 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).
  38391. */
  38392. get: function () {
  38393. return this._highlightsHue;
  38394. },
  38395. /**
  38396. * Sets the highlights Hue value.
  38397. * 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).
  38398. */
  38399. set: function (value) {
  38400. this._highlightsHue = value;
  38401. this._dirty = true;
  38402. },
  38403. enumerable: true,
  38404. configurable: true
  38405. });
  38406. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38407. /**
  38408. * Gets the highlights Density value.
  38409. * 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.
  38410. * Values less than zero provide a filter of opposite hue.
  38411. */
  38412. get: function () {
  38413. return this._highlightsDensity;
  38414. },
  38415. /**
  38416. * Sets the highlights Density value.
  38417. * 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.
  38418. * Values less than zero provide a filter of opposite hue.
  38419. */
  38420. set: function (value) {
  38421. this._highlightsDensity = value;
  38422. this._dirty = true;
  38423. },
  38424. enumerable: true,
  38425. configurable: true
  38426. });
  38427. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38428. /**
  38429. * Gets the highlights Saturation value.
  38430. * 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.
  38431. */
  38432. get: function () {
  38433. return this._highlightsSaturation;
  38434. },
  38435. /**
  38436. * Sets the highlights Saturation value.
  38437. * 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.
  38438. */
  38439. set: function (value) {
  38440. this._highlightsSaturation = value;
  38441. this._dirty = true;
  38442. },
  38443. enumerable: true,
  38444. configurable: true
  38445. });
  38446. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38447. /**
  38448. * Gets the highlights Exposure value.
  38449. * 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.
  38450. */
  38451. get: function () {
  38452. return this._highlightsExposure;
  38453. },
  38454. /**
  38455. * Sets the highlights Exposure value.
  38456. * 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.
  38457. */
  38458. set: function (value) {
  38459. this._highlightsExposure = value;
  38460. this._dirty = true;
  38461. },
  38462. enumerable: true,
  38463. configurable: true
  38464. });
  38465. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38466. /**
  38467. * Gets the midtones Hue value.
  38468. * 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).
  38469. */
  38470. get: function () {
  38471. return this._midtonesHue;
  38472. },
  38473. /**
  38474. * Sets the midtones Hue value.
  38475. * 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).
  38476. */
  38477. set: function (value) {
  38478. this._midtonesHue = value;
  38479. this._dirty = true;
  38480. },
  38481. enumerable: true,
  38482. configurable: true
  38483. });
  38484. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38485. /**
  38486. * Gets the midtones Density value.
  38487. * 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.
  38488. * Values less than zero provide a filter of opposite hue.
  38489. */
  38490. get: function () {
  38491. return this._midtonesDensity;
  38492. },
  38493. /**
  38494. * Sets the midtones Density value.
  38495. * 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.
  38496. * Values less than zero provide a filter of opposite hue.
  38497. */
  38498. set: function (value) {
  38499. this._midtonesDensity = value;
  38500. this._dirty = true;
  38501. },
  38502. enumerable: true,
  38503. configurable: true
  38504. });
  38505. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38506. /**
  38507. * Gets the midtones Saturation value.
  38508. * 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.
  38509. */
  38510. get: function () {
  38511. return this._midtonesSaturation;
  38512. },
  38513. /**
  38514. * Sets the midtones Saturation value.
  38515. * 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.
  38516. */
  38517. set: function (value) {
  38518. this._midtonesSaturation = value;
  38519. this._dirty = true;
  38520. },
  38521. enumerable: true,
  38522. configurable: true
  38523. });
  38524. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38525. /**
  38526. * Gets the midtones Exposure value.
  38527. * 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.
  38528. */
  38529. get: function () {
  38530. return this._midtonesExposure;
  38531. },
  38532. /**
  38533. * Sets the midtones Exposure value.
  38534. * 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.
  38535. */
  38536. set: function (value) {
  38537. this._midtonesExposure = value;
  38538. this._dirty = true;
  38539. },
  38540. enumerable: true,
  38541. configurable: true
  38542. });
  38543. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38544. /**
  38545. * Gets the shadows Hue value.
  38546. * 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).
  38547. */
  38548. get: function () {
  38549. return this._shadowsHue;
  38550. },
  38551. /**
  38552. * Sets the shadows Hue value.
  38553. * 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).
  38554. */
  38555. set: function (value) {
  38556. this._shadowsHue = value;
  38557. this._dirty = true;
  38558. },
  38559. enumerable: true,
  38560. configurable: true
  38561. });
  38562. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38563. /**
  38564. * Gets the shadows Density value.
  38565. * 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.
  38566. * Values less than zero provide a filter of opposite hue.
  38567. */
  38568. get: function () {
  38569. return this._shadowsDensity;
  38570. },
  38571. /**
  38572. * Sets the shadows Density value.
  38573. * 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.
  38574. * Values less than zero provide a filter of opposite hue.
  38575. */
  38576. set: function (value) {
  38577. this._shadowsDensity = value;
  38578. this._dirty = true;
  38579. },
  38580. enumerable: true,
  38581. configurable: true
  38582. });
  38583. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38584. /**
  38585. * Gets the shadows Saturation value.
  38586. * 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.
  38587. */
  38588. get: function () {
  38589. return this._shadowsSaturation;
  38590. },
  38591. /**
  38592. * Sets the shadows Saturation value.
  38593. * 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.
  38594. */
  38595. set: function (value) {
  38596. this._shadowsSaturation = value;
  38597. this._dirty = true;
  38598. },
  38599. enumerable: true,
  38600. configurable: true
  38601. });
  38602. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38603. /**
  38604. * Gets the shadows Exposure value.
  38605. * 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.
  38606. */
  38607. get: function () {
  38608. return this._shadowsExposure;
  38609. },
  38610. /**
  38611. * Sets the shadows Exposure value.
  38612. * 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.
  38613. */
  38614. set: function (value) {
  38615. this._shadowsExposure = value;
  38616. this._dirty = true;
  38617. },
  38618. enumerable: true,
  38619. configurable: true
  38620. });
  38621. ColorCurves.prototype.getClassName = function () {
  38622. return "ColorCurves";
  38623. };
  38624. /**
  38625. * Binds the color curves to the shader.
  38626. * @param colorCurves The color curve to bind
  38627. * @param effect The effect to bind to
  38628. */
  38629. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38630. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38631. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38632. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38633. if (colorCurves._dirty) {
  38634. colorCurves._dirty = false;
  38635. // Fill in global info.
  38636. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38637. // Compute highlights info.
  38638. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38639. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38640. // Compute midtones info.
  38641. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38642. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38643. // Compute shadows info.
  38644. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38645. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38646. // Compute deltas (neutral is midtones).
  38647. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38648. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38649. }
  38650. if (effect) {
  38651. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38652. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38653. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38654. }
  38655. };
  38656. /**
  38657. * Prepare the list of uniforms associated with the ColorCurves effects.
  38658. * @param uniformsList The list of uniforms used in the effect
  38659. */
  38660. ColorCurves.PrepareUniforms = function (uniformsList) {
  38661. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38662. };
  38663. /**
  38664. * Returns color grading data based on a hue, density, saturation and exposure value.
  38665. * @param filterHue The hue of the color filter.
  38666. * @param filterDensity The density of the color filter.
  38667. * @param saturation The saturation.
  38668. * @param exposure The exposure.
  38669. * @param result The result data container.
  38670. */
  38671. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38672. if (hue == null) {
  38673. return;
  38674. }
  38675. hue = ColorCurves.clamp(hue, 0, 360);
  38676. density = ColorCurves.clamp(density, -100, 100);
  38677. saturation = ColorCurves.clamp(saturation, -100, 100);
  38678. exposure = ColorCurves.clamp(exposure, -100, 100);
  38679. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38680. // so that the maximum filter density is only 50% control. This provides fine control
  38681. // for small values and reasonable range.
  38682. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38683. density *= 0.5;
  38684. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38685. if (density < 0) {
  38686. density *= -1;
  38687. hue = (hue + 180) % 360;
  38688. }
  38689. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38690. result.scaleToRef(2, result);
  38691. result.a = 1 + 0.01 * saturation;
  38692. };
  38693. /**
  38694. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38695. * @param value The input slider value in range [-100,100].
  38696. * @returns Adjusted value.
  38697. */
  38698. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38699. value /= 100;
  38700. var x = Math.abs(value);
  38701. x = Math.pow(x, 2);
  38702. if (value < 0) {
  38703. x *= -1;
  38704. }
  38705. x *= 100;
  38706. return x;
  38707. };
  38708. /**
  38709. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38710. * @param hue The hue (H) input.
  38711. * @param saturation The saturation (S) input.
  38712. * @param brightness The brightness (B) input.
  38713. * @result An RGBA color represented as Vector4.
  38714. */
  38715. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38716. var h = ColorCurves.clamp(hue, 0, 360);
  38717. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38718. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38719. if (s === 0) {
  38720. result.r = v;
  38721. result.g = v;
  38722. result.b = v;
  38723. }
  38724. else {
  38725. // sector 0 to 5
  38726. h /= 60;
  38727. var i = Math.floor(h);
  38728. // fractional part of h
  38729. var f = h - i;
  38730. var p = v * (1 - s);
  38731. var q = v * (1 - s * f);
  38732. var t = v * (1 - s * (1 - f));
  38733. switch (i) {
  38734. case 0:
  38735. result.r = v;
  38736. result.g = t;
  38737. result.b = p;
  38738. break;
  38739. case 1:
  38740. result.r = q;
  38741. result.g = v;
  38742. result.b = p;
  38743. break;
  38744. case 2:
  38745. result.r = p;
  38746. result.g = v;
  38747. result.b = t;
  38748. break;
  38749. case 3:
  38750. result.r = p;
  38751. result.g = q;
  38752. result.b = v;
  38753. break;
  38754. case 4:
  38755. result.r = t;
  38756. result.g = p;
  38757. result.b = v;
  38758. break;
  38759. default:// case 5:
  38760. result.r = v;
  38761. result.g = p;
  38762. result.b = q;
  38763. break;
  38764. }
  38765. }
  38766. result.a = 1;
  38767. };
  38768. /**
  38769. * Returns a value clamped between min and max
  38770. * @param value The value to clamp
  38771. * @param min The minimum of value
  38772. * @param max The maximum of value
  38773. * @returns The clamped value.
  38774. */
  38775. ColorCurves.clamp = function (value, min, max) {
  38776. return Math.min(Math.max(value, min), max);
  38777. };
  38778. /**
  38779. * Clones the current color curve instance.
  38780. * @return The cloned curves
  38781. */
  38782. ColorCurves.prototype.clone = function () {
  38783. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38784. };
  38785. /**
  38786. * Serializes the current color curve instance to a json representation.
  38787. * @return a JSON representation
  38788. */
  38789. ColorCurves.prototype.serialize = function () {
  38790. return BABYLON.SerializationHelper.Serialize(this);
  38791. };
  38792. /**
  38793. * Parses the color curve from a json representation.
  38794. * @param source the JSON source to parse
  38795. * @return The parsed curves
  38796. */
  38797. ColorCurves.Parse = function (source) {
  38798. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38799. };
  38800. __decorate([
  38801. BABYLON.serialize()
  38802. ], ColorCurves.prototype, "_globalHue", void 0);
  38803. __decorate([
  38804. BABYLON.serialize()
  38805. ], ColorCurves.prototype, "_globalDensity", void 0);
  38806. __decorate([
  38807. BABYLON.serialize()
  38808. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38809. __decorate([
  38810. BABYLON.serialize()
  38811. ], ColorCurves.prototype, "_globalExposure", void 0);
  38812. __decorate([
  38813. BABYLON.serialize()
  38814. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38815. __decorate([
  38816. BABYLON.serialize()
  38817. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38818. __decorate([
  38819. BABYLON.serialize()
  38820. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38821. __decorate([
  38822. BABYLON.serialize()
  38823. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38824. __decorate([
  38825. BABYLON.serialize()
  38826. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38827. __decorate([
  38828. BABYLON.serialize()
  38829. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38830. __decorate([
  38831. BABYLON.serialize()
  38832. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38833. __decorate([
  38834. BABYLON.serialize()
  38835. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38836. return ColorCurves;
  38837. }());
  38838. BABYLON.ColorCurves = ColorCurves;
  38839. })(BABYLON || (BABYLON = {}));
  38840. //# sourceMappingURL=babylon.colorCurves.js.map
  38841. "use strict";
  38842. //# sourceMappingURL=babylon.behavior.js.map
  38843. "use strict";
  38844. var BABYLON;
  38845. (function (BABYLON) {
  38846. /**
  38847. * "Static Class" containing the most commonly used helper while dealing with material for
  38848. * rendering purpose.
  38849. *
  38850. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38851. *
  38852. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38853. */
  38854. var MaterialHelper = /** @class */ (function () {
  38855. function MaterialHelper() {
  38856. }
  38857. /**
  38858. * Bind the current view position to an effect.
  38859. * @param effect The effect to be bound
  38860. * @param scene The scene the eyes position is used from
  38861. */
  38862. MaterialHelper.BindEyePosition = function (effect, scene) {
  38863. if (scene._forcedViewPosition) {
  38864. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38865. return;
  38866. }
  38867. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38868. };
  38869. /**
  38870. * Helps preparing the defines values about the UVs in used in the effect.
  38871. * UVs are shared as much as we can accross chanels in the shaders.
  38872. * @param texture The texture we are preparing the UVs for
  38873. * @param defines The defines to update
  38874. * @param key The chanel key "diffuse", "specular"... used in the shader
  38875. */
  38876. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38877. defines._needUVs = true;
  38878. defines[key] = true;
  38879. if (texture.getTextureMatrix().isIdentity(true)) {
  38880. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38881. if (texture.coordinatesIndex === 0) {
  38882. defines["MAINUV1"] = true;
  38883. }
  38884. else {
  38885. defines["MAINUV2"] = true;
  38886. }
  38887. }
  38888. else {
  38889. defines[key + "DIRECTUV"] = 0;
  38890. }
  38891. };
  38892. /**
  38893. * Binds a texture matrix value to its corrsponding uniform
  38894. * @param texture The texture to bind the matrix for
  38895. * @param uniformBuffer The uniform buffer receivin the data
  38896. * @param key The chanel key "diffuse", "specular"... used in the shader
  38897. */
  38898. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38899. var matrix = texture.getTextureMatrix();
  38900. if (!matrix.isIdentity(true)) {
  38901. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38902. }
  38903. };
  38904. /**
  38905. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38906. * @param mesh defines the current mesh
  38907. * @param scene defines the current scene
  38908. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38909. * @param pointsCloud defines if point cloud rendering has to be turned on
  38910. * @param fogEnabled defines if fog has to be turned on
  38911. * @param alphaTest defines if alpha testing has to be turned on
  38912. * @param defines defines the current list of defines
  38913. */
  38914. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38915. if (defines._areMiscDirty) {
  38916. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38917. defines["POINTSIZE"] = pointsCloud;
  38918. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38919. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38920. defines["ALPHATEST"] = alphaTest;
  38921. }
  38922. };
  38923. /**
  38924. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38925. * @param scene defines the current scene
  38926. * @param engine defines the current engine
  38927. * @param defines specifies the list of active defines
  38928. * @param useInstances defines if instances have to be turned on
  38929. * @param useClipPlane defines if clip plane have to be turned on
  38930. */
  38931. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38932. if (useClipPlane === void 0) { useClipPlane = null; }
  38933. var changed = false;
  38934. if (useClipPlane == null) {
  38935. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38936. }
  38937. if (defines["CLIPPLANE"] !== useClipPlane) {
  38938. defines["CLIPPLANE"] = useClipPlane;
  38939. changed = true;
  38940. }
  38941. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38942. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38943. changed = true;
  38944. }
  38945. if (defines["INSTANCES"] !== useInstances) {
  38946. defines["INSTANCES"] = useInstances;
  38947. changed = true;
  38948. }
  38949. if (changed) {
  38950. defines.markAsUnprocessed();
  38951. }
  38952. };
  38953. /**
  38954. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38955. * @param mesh The mesh containing the geometry data we will draw
  38956. * @param defines The defines to update
  38957. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38958. * @param useBones Precise whether bones should be used or not (override mesh info)
  38959. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38960. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38961. * @returns false if defines are considered not dirty and have not been checked
  38962. */
  38963. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38964. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38965. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38966. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38967. return false;
  38968. }
  38969. defines._normals = defines._needNormals;
  38970. defines._uvs = defines._needUVs;
  38971. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38972. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38973. defines["TANGENT"] = true;
  38974. }
  38975. if (defines._needUVs) {
  38976. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38977. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38978. }
  38979. else {
  38980. defines["UV1"] = false;
  38981. defines["UV2"] = false;
  38982. }
  38983. if (useVertexColor) {
  38984. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38985. defines["VERTEXCOLOR"] = hasVertexColors;
  38986. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38987. }
  38988. if (useBones) {
  38989. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38990. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38991. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38992. }
  38993. else {
  38994. defines["NUM_BONE_INFLUENCERS"] = 0;
  38995. defines["BonesPerMesh"] = 0;
  38996. }
  38997. }
  38998. if (useMorphTargets) {
  38999. var manager = mesh.morphTargetManager;
  39000. if (manager) {
  39001. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  39002. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  39003. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  39004. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  39005. }
  39006. else {
  39007. defines["MORPHTARGETS_TANGENT"] = false;
  39008. defines["MORPHTARGETS_NORMAL"] = false;
  39009. defines["MORPHTARGETS"] = false;
  39010. defines["NUM_MORPH_INFLUENCERS"] = 0;
  39011. }
  39012. }
  39013. return true;
  39014. };
  39015. /**
  39016. * Prepares the defines related to the light information passed in parameter
  39017. * @param scene The scene we are intending to draw
  39018. * @param mesh The mesh the effect is compiling for
  39019. * @param defines The defines to update
  39020. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  39021. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  39022. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  39023. * @returns true if normals will be required for the rest of the effect
  39024. */
  39025. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  39026. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39027. if (disableLighting === void 0) { disableLighting = false; }
  39028. if (!defines._areLightsDirty) {
  39029. return defines._needNormals;
  39030. }
  39031. var lightIndex = 0;
  39032. var needNormals = false;
  39033. var needRebuild = false;
  39034. var lightmapMode = false;
  39035. var shadowEnabled = false;
  39036. var specularEnabled = false;
  39037. if (scene.lightsEnabled && !disableLighting) {
  39038. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  39039. var light = _a[_i];
  39040. needNormals = true;
  39041. if (defines["LIGHT" + lightIndex] === undefined) {
  39042. needRebuild = true;
  39043. }
  39044. defines["LIGHT" + lightIndex] = true;
  39045. defines["SPOTLIGHT" + lightIndex] = false;
  39046. defines["HEMILIGHT" + lightIndex] = false;
  39047. defines["POINTLIGHT" + lightIndex] = false;
  39048. defines["DIRLIGHT" + lightIndex] = false;
  39049. var type;
  39050. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  39051. type = "SPOTLIGHT" + lightIndex;
  39052. var spotLight = light;
  39053. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  39054. }
  39055. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  39056. type = "HEMILIGHT" + lightIndex;
  39057. }
  39058. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39059. type = "POINTLIGHT" + lightIndex;
  39060. }
  39061. else {
  39062. type = "DIRLIGHT" + lightIndex;
  39063. }
  39064. defines[type] = true;
  39065. // Specular
  39066. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39067. specularEnabled = true;
  39068. }
  39069. // Shadows
  39070. defines["SHADOW" + lightIndex] = false;
  39071. defines["SHADOWPCF" + lightIndex] = false;
  39072. defines["SHADOWPCSS" + lightIndex] = false;
  39073. defines["SHADOWPOISSON" + lightIndex] = false;
  39074. defines["SHADOWESM" + lightIndex] = false;
  39075. defines["SHADOWCUBE" + lightIndex] = false;
  39076. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39077. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39078. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39079. var shadowGenerator = light.getShadowGenerator();
  39080. if (shadowGenerator) {
  39081. shadowEnabled = true;
  39082. shadowGenerator.prepareDefines(defines, lightIndex);
  39083. }
  39084. }
  39085. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39086. lightmapMode = true;
  39087. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39088. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39089. }
  39090. else {
  39091. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39092. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39093. }
  39094. lightIndex++;
  39095. if (lightIndex === maxSimultaneousLights)
  39096. break;
  39097. }
  39098. }
  39099. defines["SPECULARTERM"] = specularEnabled;
  39100. defines["SHADOWS"] = shadowEnabled;
  39101. // Resetting all other lights if any
  39102. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39103. if (defines["LIGHT" + index] !== undefined) {
  39104. defines["LIGHT" + index] = false;
  39105. defines["HEMILIGHT" + lightIndex] = false;
  39106. defines["POINTLIGHT" + lightIndex] = false;
  39107. defines["DIRLIGHT" + lightIndex] = false;
  39108. defines["SPOTLIGHT" + lightIndex] = false;
  39109. defines["SHADOW" + lightIndex] = false;
  39110. }
  39111. }
  39112. var caps = scene.getEngine().getCaps();
  39113. if (defines["SHADOWFLOAT"] === undefined) {
  39114. needRebuild = true;
  39115. }
  39116. defines["SHADOWFLOAT"] = shadowEnabled &&
  39117. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39118. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39119. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39120. if (needRebuild) {
  39121. defines.rebuild();
  39122. }
  39123. return needNormals;
  39124. };
  39125. /**
  39126. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39127. * that won t be acctive due to defines being turned off.
  39128. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39129. * @param samplersList The samplers list
  39130. * @param defines The defines helping in the list generation
  39131. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39132. */
  39133. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39134. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39135. var uniformsList;
  39136. var uniformBuffersList = null;
  39137. if (uniformsListOrOptions.uniformsNames) {
  39138. var options = uniformsListOrOptions;
  39139. uniformsList = options.uniformsNames;
  39140. uniformBuffersList = options.uniformBuffersNames;
  39141. samplersList = options.samplers;
  39142. defines = options.defines;
  39143. maxSimultaneousLights = options.maxSimultaneousLights;
  39144. }
  39145. else {
  39146. uniformsList = uniformsListOrOptions;
  39147. if (!samplersList) {
  39148. samplersList = [];
  39149. }
  39150. }
  39151. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39152. if (!defines["LIGHT" + lightIndex]) {
  39153. break;
  39154. }
  39155. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39156. if (uniformBuffersList) {
  39157. uniformBuffersList.push("Light" + lightIndex);
  39158. }
  39159. samplersList.push("shadowSampler" + lightIndex);
  39160. samplersList.push("depthSampler" + lightIndex);
  39161. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39162. samplersList.push("projectionLightSampler" + lightIndex);
  39163. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39164. }
  39165. }
  39166. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39167. uniformsList.push("morphTargetInfluences");
  39168. }
  39169. };
  39170. /**
  39171. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39172. * @param defines The defines to update while falling back
  39173. * @param fallbacks The authorized effect fallbacks
  39174. * @param maxSimultaneousLights The maximum number of lights allowed
  39175. * @param rank the current rank of the Effect
  39176. * @returns The newly affected rank
  39177. */
  39178. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39179. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39180. if (rank === void 0) { rank = 0; }
  39181. var lightFallbackRank = 0;
  39182. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39183. if (!defines["LIGHT" + lightIndex]) {
  39184. break;
  39185. }
  39186. if (lightIndex > 0) {
  39187. lightFallbackRank = rank + lightIndex;
  39188. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39189. }
  39190. if (!defines["SHADOWS"]) {
  39191. if (defines["SHADOW" + lightIndex]) {
  39192. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39193. }
  39194. if (defines["SHADOWPCF" + lightIndex]) {
  39195. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39196. }
  39197. if (defines["SHADOWPCSS" + lightIndex]) {
  39198. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39199. }
  39200. if (defines["SHADOWPOISSON" + lightIndex]) {
  39201. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39202. }
  39203. if (defines["SHADOWESM" + lightIndex]) {
  39204. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39205. }
  39206. }
  39207. }
  39208. return lightFallbackRank++;
  39209. };
  39210. /**
  39211. * Prepares the list of attributes required for morph targets according to the effect defines.
  39212. * @param attribs The current list of supported attribs
  39213. * @param mesh The mesh to prepare the morph targets attributes for
  39214. * @param defines The current Defines of the effect
  39215. */
  39216. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39217. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39218. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39219. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39220. var manager = mesh.morphTargetManager;
  39221. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39222. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39223. for (var index = 0; index < influencers; index++) {
  39224. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39225. if (normal) {
  39226. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39227. }
  39228. if (tangent) {
  39229. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39230. }
  39231. if (attribs.length > maxAttributesCount) {
  39232. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39233. }
  39234. }
  39235. }
  39236. };
  39237. /**
  39238. * Prepares the list of attributes required for bones according to the effect defines.
  39239. * @param attribs The current list of supported attribs
  39240. * @param mesh The mesh to prepare the bones attributes for
  39241. * @param defines The current Defines of the effect
  39242. * @param fallbacks The current efffect fallback strategy
  39243. */
  39244. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39245. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39246. fallbacks.addCPUSkinningFallback(0, mesh);
  39247. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39248. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39249. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39250. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39251. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39252. }
  39253. }
  39254. };
  39255. /**
  39256. * Prepares the list of attributes required for instances according to the effect defines.
  39257. * @param attribs The current list of supported attribs
  39258. * @param defines The current Defines of the effect
  39259. */
  39260. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39261. if (defines["INSTANCES"]) {
  39262. attribs.push("world0");
  39263. attribs.push("world1");
  39264. attribs.push("world2");
  39265. attribs.push("world3");
  39266. }
  39267. };
  39268. /**
  39269. * Binds the light shadow information to the effect for the given mesh.
  39270. * @param light The light containing the generator
  39271. * @param scene The scene the lights belongs to
  39272. * @param mesh The mesh we are binding the information to render
  39273. * @param lightIndex The light index in the effect used to render the mesh
  39274. * @param effect The effect we are binding the data to
  39275. */
  39276. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39277. if (light.shadowEnabled && mesh.receiveShadows) {
  39278. var shadowGenerator = light.getShadowGenerator();
  39279. if (shadowGenerator) {
  39280. shadowGenerator.bindShadowLight(lightIndex, effect);
  39281. }
  39282. }
  39283. };
  39284. /**
  39285. * Binds the light information to the effect.
  39286. * @param light The light containing the generator
  39287. * @param effect The effect we are binding the data to
  39288. * @param lightIndex The light index in the effect used to render
  39289. */
  39290. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39291. light.transferToEffect(effect, lightIndex + "");
  39292. };
  39293. /**
  39294. * Binds the lights information from the scene to the effect for the given mesh.
  39295. * @param scene The scene the lights belongs to
  39296. * @param mesh The mesh we are binding the information to render
  39297. * @param effect The effect we are binding the data to
  39298. * @param defines The generated defines for the effect
  39299. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39300. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39301. */
  39302. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39303. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39304. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39305. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39306. for (var i = 0; i < len; i++) {
  39307. var light = mesh._lightSources[i];
  39308. var iAsString = i.toString();
  39309. var scaledIntensity = light.getScaledIntensity();
  39310. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39311. MaterialHelper.BindLightProperties(light, effect, i);
  39312. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39313. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39314. if (defines["SPECULARTERM"]) {
  39315. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39316. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39317. }
  39318. // Shadows
  39319. if (scene.shadowsEnabled) {
  39320. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39321. }
  39322. light._uniformBuffer.update();
  39323. }
  39324. };
  39325. /**
  39326. * Binds the fog information from the scene to the effect for the given mesh.
  39327. * @param scene The scene the lights belongs to
  39328. * @param mesh The mesh we are binding the information to render
  39329. * @param effect The effect we are binding the data to
  39330. */
  39331. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39332. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39333. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39334. effect.setColor3("vFogColor", scene.fogColor);
  39335. }
  39336. };
  39337. /**
  39338. * Binds the bones information from the mesh to the effect.
  39339. * @param mesh The mesh we are binding the information to render
  39340. * @param effect The effect we are binding the data to
  39341. */
  39342. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39343. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39344. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39345. if (matrices && effect) {
  39346. effect.setMatrices("mBones", matrices);
  39347. }
  39348. }
  39349. };
  39350. /**
  39351. * Binds the morph targets information from the mesh to the effect.
  39352. * @param abstractMesh The mesh we are binding the information to render
  39353. * @param effect The effect we are binding the data to
  39354. */
  39355. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39356. var manager = abstractMesh.morphTargetManager;
  39357. if (!abstractMesh || !manager) {
  39358. return;
  39359. }
  39360. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39361. };
  39362. /**
  39363. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39364. * @param defines The generated defines used in the effect
  39365. * @param effect The effect we are binding the data to
  39366. * @param scene The scene we are willing to render with logarithmic scale for
  39367. */
  39368. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39369. if (defines["LOGARITHMICDEPTH"]) {
  39370. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39371. }
  39372. };
  39373. /**
  39374. * Binds the clip plane information from the scene to the effect.
  39375. * @param scene The scene the clip plane information are extracted from
  39376. * @param effect The effect we are binding the data to
  39377. */
  39378. MaterialHelper.BindClipPlane = function (effect, scene) {
  39379. if (scene.clipPlane) {
  39380. var clipPlane = scene.clipPlane;
  39381. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39382. }
  39383. };
  39384. return MaterialHelper;
  39385. }());
  39386. BABYLON.MaterialHelper = MaterialHelper;
  39387. })(BABYLON || (BABYLON = {}));
  39388. //# sourceMappingURL=babylon.materialHelper.js.map
  39389. "use strict";
  39390. var BABYLON;
  39391. (function (BABYLON) {
  39392. var PushMaterial = /** @class */ (function (_super) {
  39393. __extends(PushMaterial, _super);
  39394. function PushMaterial(name, scene) {
  39395. var _this = _super.call(this, name, scene) || this;
  39396. _this._normalMatrix = new BABYLON.Matrix();
  39397. _this.storeEffectOnSubMeshes = true;
  39398. return _this;
  39399. }
  39400. PushMaterial.prototype.getEffect = function () {
  39401. return this._activeEffect;
  39402. };
  39403. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39404. if (!mesh) {
  39405. return false;
  39406. }
  39407. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39408. return true;
  39409. }
  39410. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39411. };
  39412. /**
  39413. * Binds the given world matrix to the active effect
  39414. *
  39415. * @param world the matrix to bind
  39416. */
  39417. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39418. this._activeEffect.setMatrix("world", world);
  39419. };
  39420. /**
  39421. * Binds the given normal matrix to the active effect
  39422. *
  39423. * @param normalMatrix the matrix to bind
  39424. */
  39425. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39426. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39427. };
  39428. PushMaterial.prototype.bind = function (world, mesh) {
  39429. if (!mesh) {
  39430. return;
  39431. }
  39432. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39433. };
  39434. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39435. if (effect === void 0) { effect = null; }
  39436. _super.prototype._afterBind.call(this, mesh);
  39437. this.getScene()._cachedEffect = effect;
  39438. };
  39439. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39440. if (visibility === void 0) { visibility = 1; }
  39441. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39442. };
  39443. return PushMaterial;
  39444. }(BABYLON.Material));
  39445. BABYLON.PushMaterial = PushMaterial;
  39446. })(BABYLON || (BABYLON = {}));
  39447. //# sourceMappingURL=babylon.pushMaterial.js.map
  39448. "use strict";
  39449. var BABYLON;
  39450. (function (BABYLON) {
  39451. /** @ignore */
  39452. var StandardMaterialDefines = /** @class */ (function (_super) {
  39453. __extends(StandardMaterialDefines, _super);
  39454. function StandardMaterialDefines() {
  39455. var _this = _super.call(this) || this;
  39456. _this.MAINUV1 = false;
  39457. _this.MAINUV2 = false;
  39458. _this.DIFFUSE = false;
  39459. _this.DIFFUSEDIRECTUV = 0;
  39460. _this.AMBIENT = false;
  39461. _this.AMBIENTDIRECTUV = 0;
  39462. _this.OPACITY = false;
  39463. _this.OPACITYDIRECTUV = 0;
  39464. _this.OPACITYRGB = false;
  39465. _this.REFLECTION = false;
  39466. _this.EMISSIVE = false;
  39467. _this.EMISSIVEDIRECTUV = 0;
  39468. _this.SPECULAR = false;
  39469. _this.SPECULARDIRECTUV = 0;
  39470. _this.BUMP = false;
  39471. _this.BUMPDIRECTUV = 0;
  39472. _this.PARALLAX = false;
  39473. _this.PARALLAXOCCLUSION = false;
  39474. _this.SPECULAROVERALPHA = false;
  39475. _this.CLIPPLANE = false;
  39476. _this.ALPHATEST = false;
  39477. _this.DEPTHPREPASS = false;
  39478. _this.ALPHAFROMDIFFUSE = false;
  39479. _this.POINTSIZE = false;
  39480. _this.FOG = false;
  39481. _this.SPECULARTERM = false;
  39482. _this.DIFFUSEFRESNEL = false;
  39483. _this.OPACITYFRESNEL = false;
  39484. _this.REFLECTIONFRESNEL = false;
  39485. _this.REFRACTIONFRESNEL = false;
  39486. _this.EMISSIVEFRESNEL = false;
  39487. _this.FRESNEL = false;
  39488. _this.NORMAL = false;
  39489. _this.UV1 = false;
  39490. _this.UV2 = false;
  39491. _this.VERTEXCOLOR = false;
  39492. _this.VERTEXALPHA = false;
  39493. _this.NUM_BONE_INFLUENCERS = 0;
  39494. _this.BonesPerMesh = 0;
  39495. _this.INSTANCES = false;
  39496. _this.GLOSSINESS = false;
  39497. _this.ROUGHNESS = false;
  39498. _this.EMISSIVEASILLUMINATION = false;
  39499. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39500. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39501. _this.LIGHTMAP = false;
  39502. _this.LIGHTMAPDIRECTUV = 0;
  39503. _this.OBJECTSPACE_NORMALMAP = false;
  39504. _this.USELIGHTMAPASSHADOWMAP = false;
  39505. _this.REFLECTIONMAP_3D = false;
  39506. _this.REFLECTIONMAP_SPHERICAL = false;
  39507. _this.REFLECTIONMAP_PLANAR = false;
  39508. _this.REFLECTIONMAP_CUBIC = false;
  39509. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39510. _this.REFLECTIONMAP_PROJECTION = false;
  39511. _this.REFLECTIONMAP_SKYBOX = false;
  39512. _this.REFLECTIONMAP_EXPLICIT = false;
  39513. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39514. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39515. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39516. _this.INVERTCUBICMAP = false;
  39517. _this.LOGARITHMICDEPTH = false;
  39518. _this.REFRACTION = false;
  39519. _this.REFRACTIONMAP_3D = false;
  39520. _this.REFLECTIONOVERALPHA = false;
  39521. _this.TWOSIDEDLIGHTING = false;
  39522. _this.SHADOWFLOAT = false;
  39523. _this.MORPHTARGETS = false;
  39524. _this.MORPHTARGETS_NORMAL = false;
  39525. _this.MORPHTARGETS_TANGENT = false;
  39526. _this.NUM_MORPH_INFLUENCERS = 0;
  39527. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39528. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39529. _this.IMAGEPROCESSING = false;
  39530. _this.VIGNETTE = false;
  39531. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39532. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39533. _this.TONEMAPPING = false;
  39534. _this.CONTRAST = false;
  39535. _this.COLORCURVES = false;
  39536. _this.COLORGRADING = false;
  39537. _this.COLORGRADING3D = false;
  39538. _this.SAMPLER3DGREENDEPTH = false;
  39539. _this.SAMPLER3DBGRMAP = false;
  39540. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39541. _this.EXPOSURE = false;
  39542. _this.GRAIN = false;
  39543. _this.rebuild();
  39544. return _this;
  39545. }
  39546. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39547. var modes = [
  39548. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39549. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39550. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39551. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39552. ];
  39553. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39554. var mode = modes_1[_i];
  39555. this[mode] = (mode === modeToEnable);
  39556. }
  39557. };
  39558. return StandardMaterialDefines;
  39559. }(BABYLON.MaterialDefines));
  39560. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39561. var StandardMaterial = /** @class */ (function (_super) {
  39562. __extends(StandardMaterial, _super);
  39563. function StandardMaterial(name, scene) {
  39564. var _this = _super.call(this, name, scene) || this;
  39565. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39566. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39567. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39568. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39569. _this.specularPower = 64;
  39570. _this._useAlphaFromDiffuseTexture = false;
  39571. _this._useEmissiveAsIllumination = false;
  39572. _this._linkEmissiveWithDiffuse = false;
  39573. _this._useSpecularOverAlpha = false;
  39574. _this._useReflectionOverAlpha = false;
  39575. _this._disableLighting = false;
  39576. _this._useObjectSpaceNormalMap = false;
  39577. _this._useParallax = false;
  39578. _this._useParallaxOcclusion = false;
  39579. _this.parallaxScaleBias = 0.05;
  39580. _this._roughness = 0;
  39581. _this.indexOfRefraction = 0.98;
  39582. _this.invertRefractionY = true;
  39583. _this._useLightmapAsShadowmap = false;
  39584. _this._useReflectionFresnelFromSpecular = false;
  39585. _this._useGlossinessFromSpecularMapAlpha = false;
  39586. _this._maxSimultaneousLights = 4;
  39587. /**
  39588. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39589. */
  39590. _this._invertNormalMapX = false;
  39591. /**
  39592. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39593. */
  39594. _this._invertNormalMapY = false;
  39595. /**
  39596. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39597. */
  39598. _this._twoSidedLighting = false;
  39599. _this._renderTargets = new BABYLON.SmartArray(16);
  39600. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39601. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39602. // Setup the default processing configuration to the scene.
  39603. _this._attachImageProcessingConfiguration(null);
  39604. _this.getRenderTargetTextures = function () {
  39605. _this._renderTargets.reset();
  39606. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39607. _this._renderTargets.push(_this._reflectionTexture);
  39608. }
  39609. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39610. _this._renderTargets.push(_this._refractionTexture);
  39611. }
  39612. return _this._renderTargets;
  39613. };
  39614. return _this;
  39615. }
  39616. ;
  39617. ;
  39618. ;
  39619. ;
  39620. ;
  39621. ;
  39622. ;
  39623. ;
  39624. ;
  39625. ;
  39626. ;
  39627. ;
  39628. ;
  39629. ;
  39630. ;
  39631. ;
  39632. ;
  39633. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39634. /**
  39635. * Gets the image processing configuration used either in this material.
  39636. */
  39637. get: function () {
  39638. return this._imageProcessingConfiguration;
  39639. },
  39640. /**
  39641. * Sets the Default image processing configuration used either in the this material.
  39642. *
  39643. * If sets to null, the scene one is in use.
  39644. */
  39645. set: function (value) {
  39646. this._attachImageProcessingConfiguration(value);
  39647. // Ensure the effect will be rebuilt.
  39648. this._markAllSubMeshesAsTexturesDirty();
  39649. },
  39650. enumerable: true,
  39651. configurable: true
  39652. });
  39653. /**
  39654. * Attaches a new image processing configuration to the Standard Material.
  39655. * @param configuration
  39656. */
  39657. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39658. var _this = this;
  39659. if (configuration === this._imageProcessingConfiguration) {
  39660. return;
  39661. }
  39662. // Detaches observer.
  39663. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39664. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39665. }
  39666. // Pick the scene configuration if needed.
  39667. if (!configuration) {
  39668. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39669. }
  39670. else {
  39671. this._imageProcessingConfiguration = configuration;
  39672. }
  39673. // Attaches observer.
  39674. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39675. _this._markAllSubMeshesAsImageProcessingDirty();
  39676. });
  39677. };
  39678. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39679. /**
  39680. * Gets wether the color curves effect is enabled.
  39681. */
  39682. get: function () {
  39683. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39684. },
  39685. /**
  39686. * Sets wether the color curves effect is enabled.
  39687. */
  39688. set: function (value) {
  39689. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39690. },
  39691. enumerable: true,
  39692. configurable: true
  39693. });
  39694. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39695. /**
  39696. * Gets wether the color grading effect is enabled.
  39697. */
  39698. get: function () {
  39699. return this.imageProcessingConfiguration.colorGradingEnabled;
  39700. },
  39701. /**
  39702. * Gets wether the color grading effect is enabled.
  39703. */
  39704. set: function (value) {
  39705. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39706. },
  39707. enumerable: true,
  39708. configurable: true
  39709. });
  39710. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39711. /**
  39712. * Gets wether tonemapping is enabled or not.
  39713. */
  39714. get: function () {
  39715. return this._imageProcessingConfiguration.toneMappingEnabled;
  39716. },
  39717. /**
  39718. * Sets wether tonemapping is enabled or not
  39719. */
  39720. set: function (value) {
  39721. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39722. },
  39723. enumerable: true,
  39724. configurable: true
  39725. });
  39726. ;
  39727. ;
  39728. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39729. /**
  39730. * The camera exposure used on this material.
  39731. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39732. * This corresponds to a photographic exposure.
  39733. */
  39734. get: function () {
  39735. return this._imageProcessingConfiguration.exposure;
  39736. },
  39737. /**
  39738. * The camera exposure used on this material.
  39739. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39740. * This corresponds to a photographic exposure.
  39741. */
  39742. set: function (value) {
  39743. this._imageProcessingConfiguration.exposure = value;
  39744. },
  39745. enumerable: true,
  39746. configurable: true
  39747. });
  39748. ;
  39749. ;
  39750. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39751. /**
  39752. * Gets The camera contrast used on this material.
  39753. */
  39754. get: function () {
  39755. return this._imageProcessingConfiguration.contrast;
  39756. },
  39757. /**
  39758. * Sets The camera contrast used on this material.
  39759. */
  39760. set: function (value) {
  39761. this._imageProcessingConfiguration.contrast = value;
  39762. },
  39763. enumerable: true,
  39764. configurable: true
  39765. });
  39766. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39767. /**
  39768. * Gets the Color Grading 2D Lookup Texture.
  39769. */
  39770. get: function () {
  39771. return this._imageProcessingConfiguration.colorGradingTexture;
  39772. },
  39773. /**
  39774. * Sets the Color Grading 2D Lookup Texture.
  39775. */
  39776. set: function (value) {
  39777. this._imageProcessingConfiguration.colorGradingTexture = value;
  39778. },
  39779. enumerable: true,
  39780. configurable: true
  39781. });
  39782. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39783. /**
  39784. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39785. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39786. * 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;
  39787. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39788. */
  39789. get: function () {
  39790. return this._imageProcessingConfiguration.colorCurves;
  39791. },
  39792. /**
  39793. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39794. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39795. * 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;
  39796. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39797. */
  39798. set: function (value) {
  39799. this._imageProcessingConfiguration.colorCurves = value;
  39800. },
  39801. enumerable: true,
  39802. configurable: true
  39803. });
  39804. StandardMaterial.prototype.getClassName = function () {
  39805. return "StandardMaterial";
  39806. };
  39807. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39808. get: function () {
  39809. return this._useLogarithmicDepth;
  39810. },
  39811. set: function (value) {
  39812. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39813. this._markAllSubMeshesAsMiscDirty();
  39814. },
  39815. enumerable: true,
  39816. configurable: true
  39817. });
  39818. StandardMaterial.prototype.needAlphaBlending = function () {
  39819. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39820. };
  39821. StandardMaterial.prototype.needAlphaTesting = function () {
  39822. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39823. };
  39824. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39825. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39826. };
  39827. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39828. return this._diffuseTexture;
  39829. };
  39830. /**
  39831. * Child classes can use it to update shaders
  39832. */
  39833. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39834. if (useInstances === void 0) { useInstances = false; }
  39835. if (subMesh.effect && this.isFrozen) {
  39836. if (this._wasPreviouslyReady && subMesh.effect) {
  39837. return true;
  39838. }
  39839. }
  39840. if (!subMesh._materialDefines) {
  39841. subMesh._materialDefines = new StandardMaterialDefines();
  39842. }
  39843. var scene = this.getScene();
  39844. var defines = subMesh._materialDefines;
  39845. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39846. if (defines._renderId === scene.getRenderId()) {
  39847. return true;
  39848. }
  39849. }
  39850. var engine = scene.getEngine();
  39851. // Lights
  39852. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39853. // Textures
  39854. if (defines._areTexturesDirty) {
  39855. defines._needUVs = false;
  39856. defines.MAINUV1 = false;
  39857. defines.MAINUV2 = false;
  39858. if (scene.texturesEnabled) {
  39859. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39860. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39861. return false;
  39862. }
  39863. else {
  39864. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39865. }
  39866. }
  39867. else {
  39868. defines.DIFFUSE = false;
  39869. }
  39870. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39871. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39872. return false;
  39873. }
  39874. else {
  39875. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39876. }
  39877. }
  39878. else {
  39879. defines.AMBIENT = false;
  39880. }
  39881. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39882. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39883. return false;
  39884. }
  39885. else {
  39886. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39887. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39888. }
  39889. }
  39890. else {
  39891. defines.OPACITY = false;
  39892. }
  39893. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39894. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39895. return false;
  39896. }
  39897. else {
  39898. defines._needNormals = true;
  39899. defines.REFLECTION = true;
  39900. defines.ROUGHNESS = (this._roughness > 0);
  39901. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39902. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39903. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39904. switch (this._reflectionTexture.coordinatesMode) {
  39905. case BABYLON.Texture.CUBIC_MODE:
  39906. case BABYLON.Texture.INVCUBIC_MODE:
  39907. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39908. break;
  39909. case BABYLON.Texture.EXPLICIT_MODE:
  39910. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39911. break;
  39912. case BABYLON.Texture.PLANAR_MODE:
  39913. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39914. break;
  39915. case BABYLON.Texture.PROJECTION_MODE:
  39916. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39917. break;
  39918. case BABYLON.Texture.SKYBOX_MODE:
  39919. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39920. break;
  39921. case BABYLON.Texture.SPHERICAL_MODE:
  39922. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39923. break;
  39924. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39925. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39926. break;
  39927. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39928. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39929. break;
  39930. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39931. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39932. break;
  39933. }
  39934. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39935. }
  39936. }
  39937. else {
  39938. defines.REFLECTION = false;
  39939. }
  39940. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39941. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39942. return false;
  39943. }
  39944. else {
  39945. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39946. }
  39947. }
  39948. else {
  39949. defines.EMISSIVE = false;
  39950. }
  39951. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39952. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39953. return false;
  39954. }
  39955. else {
  39956. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39957. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39958. }
  39959. }
  39960. else {
  39961. defines.LIGHTMAP = false;
  39962. }
  39963. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39964. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39965. return false;
  39966. }
  39967. else {
  39968. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39969. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39970. }
  39971. }
  39972. else {
  39973. defines.SPECULAR = false;
  39974. }
  39975. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39976. // Bump texure can not be not blocking.
  39977. if (!this._bumpTexture.isReady()) {
  39978. return false;
  39979. }
  39980. else {
  39981. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39982. defines.PARALLAX = this._useParallax;
  39983. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39984. }
  39985. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39986. }
  39987. else {
  39988. defines.BUMP = false;
  39989. }
  39990. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39991. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39992. return false;
  39993. }
  39994. else {
  39995. defines._needUVs = true;
  39996. defines.REFRACTION = true;
  39997. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39998. }
  39999. }
  40000. else {
  40001. defines.REFRACTION = false;
  40002. }
  40003. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  40004. }
  40005. else {
  40006. defines.DIFFUSE = false;
  40007. defines.AMBIENT = false;
  40008. defines.OPACITY = false;
  40009. defines.REFLECTION = false;
  40010. defines.EMISSIVE = false;
  40011. defines.LIGHTMAP = false;
  40012. defines.BUMP = false;
  40013. defines.REFRACTION = false;
  40014. }
  40015. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  40016. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  40017. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  40018. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40019. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40020. }
  40021. if (defines._areImageProcessingDirty) {
  40022. if (!this._imageProcessingConfiguration.isReady()) {
  40023. return false;
  40024. }
  40025. this._imageProcessingConfiguration.prepareDefines(defines);
  40026. }
  40027. if (defines._areFresnelDirty) {
  40028. if (StandardMaterial.FresnelEnabled) {
  40029. // Fresnel
  40030. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  40031. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  40032. this._reflectionFresnelParameters) {
  40033. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  40034. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  40035. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  40036. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  40037. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  40038. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  40039. defines._needNormals = true;
  40040. defines.FRESNEL = true;
  40041. }
  40042. }
  40043. else {
  40044. defines.FRESNEL = false;
  40045. }
  40046. }
  40047. // Misc.
  40048. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  40049. // Attribs
  40050. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40051. // Values that need to be evaluated on every frame
  40052. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40053. // Get correct effect
  40054. if (defines.isDirty) {
  40055. defines.markAsProcessed();
  40056. scene.resetCachedMaterial();
  40057. // Fallbacks
  40058. var fallbacks = new BABYLON.EffectFallbacks();
  40059. if (defines.REFLECTION) {
  40060. fallbacks.addFallback(0, "REFLECTION");
  40061. }
  40062. if (defines.SPECULAR) {
  40063. fallbacks.addFallback(0, "SPECULAR");
  40064. }
  40065. if (defines.BUMP) {
  40066. fallbacks.addFallback(0, "BUMP");
  40067. }
  40068. if (defines.PARALLAX) {
  40069. fallbacks.addFallback(1, "PARALLAX");
  40070. }
  40071. if (defines.PARALLAXOCCLUSION) {
  40072. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40073. }
  40074. if (defines.SPECULAROVERALPHA) {
  40075. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40076. }
  40077. if (defines.FOG) {
  40078. fallbacks.addFallback(1, "FOG");
  40079. }
  40080. if (defines.POINTSIZE) {
  40081. fallbacks.addFallback(0, "POINTSIZE");
  40082. }
  40083. if (defines.LOGARITHMICDEPTH) {
  40084. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40085. }
  40086. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40087. if (defines.SPECULARTERM) {
  40088. fallbacks.addFallback(0, "SPECULARTERM");
  40089. }
  40090. if (defines.DIFFUSEFRESNEL) {
  40091. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40092. }
  40093. if (defines.OPACITYFRESNEL) {
  40094. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40095. }
  40096. if (defines.REFLECTIONFRESNEL) {
  40097. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40098. }
  40099. if (defines.EMISSIVEFRESNEL) {
  40100. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40101. }
  40102. if (defines.FRESNEL) {
  40103. fallbacks.addFallback(4, "FRESNEL");
  40104. }
  40105. //Attributes
  40106. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40107. if (defines.NORMAL) {
  40108. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40109. }
  40110. if (defines.UV1) {
  40111. attribs.push(BABYLON.VertexBuffer.UVKind);
  40112. }
  40113. if (defines.UV2) {
  40114. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40115. }
  40116. if (defines.VERTEXCOLOR) {
  40117. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40118. }
  40119. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40120. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40121. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40122. var shaderName = "default";
  40123. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40124. "vFogInfos", "vFogColor", "pointSize",
  40125. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40126. "mBones",
  40127. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40128. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40129. "vReflectionPosition", "vReflectionSize",
  40130. "logarithmicDepthConstant", "vTangentSpaceParams"
  40131. ];
  40132. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40133. var uniformBuffers = ["Material", "Scene"];
  40134. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40135. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40136. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40137. uniformsNames: uniforms,
  40138. uniformBuffersNames: uniformBuffers,
  40139. samplers: samplers,
  40140. defines: defines,
  40141. maxSimultaneousLights: this._maxSimultaneousLights
  40142. });
  40143. if (this.customShaderNameResolve) {
  40144. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40145. }
  40146. var join = defines.toString();
  40147. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40148. attributes: attribs,
  40149. uniformsNames: uniforms,
  40150. uniformBuffersNames: uniformBuffers,
  40151. samplers: samplers,
  40152. defines: join,
  40153. fallbacks: fallbacks,
  40154. onCompiled: this.onCompiled,
  40155. onError: this.onError,
  40156. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40157. }, engine), defines);
  40158. this.buildUniformLayout();
  40159. }
  40160. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40161. return false;
  40162. }
  40163. defines._renderId = scene.getRenderId();
  40164. this._wasPreviouslyReady = true;
  40165. return true;
  40166. };
  40167. StandardMaterial.prototype.buildUniformLayout = function () {
  40168. // Order is important !
  40169. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40170. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40171. this._uniformBuffer.addUniform("opacityParts", 4);
  40172. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40173. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40174. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40175. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40176. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40177. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40178. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40179. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40180. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40181. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40182. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40183. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40184. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40185. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40186. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40187. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40188. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40189. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40190. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40191. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40192. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40193. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40194. this._uniformBuffer.addUniform("specularMatrix", 16);
  40195. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40196. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40197. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40198. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40199. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40200. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40201. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40202. this._uniformBuffer.addUniform("pointSize", 1);
  40203. this._uniformBuffer.create();
  40204. };
  40205. StandardMaterial.prototype.unbind = function () {
  40206. if (this._activeEffect) {
  40207. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40208. this._activeEffect.setTexture("reflection2DSampler", null);
  40209. }
  40210. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40211. this._activeEffect.setTexture("refraction2DSampler", null);
  40212. }
  40213. }
  40214. _super.prototype.unbind.call(this);
  40215. };
  40216. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40217. var scene = this.getScene();
  40218. var defines = subMesh._materialDefines;
  40219. if (!defines) {
  40220. return;
  40221. }
  40222. var effect = subMesh.effect;
  40223. if (!effect) {
  40224. return;
  40225. }
  40226. this._activeEffect = effect;
  40227. // Matrices
  40228. this.bindOnlyWorldMatrix(world);
  40229. // Normal Matrix
  40230. if (defines.OBJECTSPACE_NORMALMAP) {
  40231. world.toNormalMatrix(this._normalMatrix);
  40232. this.bindOnlyNormalMatrix(this._normalMatrix);
  40233. }
  40234. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40235. // Bones
  40236. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40237. if (mustRebind) {
  40238. this._uniformBuffer.bindToEffect(effect, "Material");
  40239. this.bindViewProjection(effect);
  40240. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40241. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40242. // Fresnel
  40243. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40244. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40245. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40246. }
  40247. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40248. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40249. }
  40250. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40251. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40252. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40253. }
  40254. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40255. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40256. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40257. }
  40258. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40259. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40260. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40261. }
  40262. }
  40263. // Textures
  40264. if (scene.texturesEnabled) {
  40265. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40266. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40267. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40268. }
  40269. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40270. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40271. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40272. }
  40273. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40274. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40275. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40276. }
  40277. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40278. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40279. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40280. if (this._reflectionTexture.boundingBoxSize) {
  40281. var cubeTexture = this._reflectionTexture;
  40282. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40283. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40284. }
  40285. }
  40286. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40287. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40288. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40289. }
  40290. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40291. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40292. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40293. }
  40294. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40295. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40296. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40297. }
  40298. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40299. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40300. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40301. if (scene._mirroredCameraPosition) {
  40302. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40303. }
  40304. else {
  40305. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40306. }
  40307. }
  40308. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40309. var depth = 1.0;
  40310. if (!this._refractionTexture.isCube) {
  40311. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40312. if (this._refractionTexture.depth) {
  40313. depth = this._refractionTexture.depth;
  40314. }
  40315. }
  40316. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40317. }
  40318. }
  40319. // Point size
  40320. if (this.pointsCloud) {
  40321. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40322. }
  40323. if (defines.SPECULARTERM) {
  40324. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40325. }
  40326. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40327. // Diffuse
  40328. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40329. }
  40330. // Textures
  40331. if (scene.texturesEnabled) {
  40332. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40333. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40334. }
  40335. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40336. effect.setTexture("ambientSampler", this._ambientTexture);
  40337. }
  40338. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40339. effect.setTexture("opacitySampler", this._opacityTexture);
  40340. }
  40341. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40342. if (this._reflectionTexture.isCube) {
  40343. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40344. }
  40345. else {
  40346. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40347. }
  40348. }
  40349. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40350. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40351. }
  40352. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40353. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40354. }
  40355. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40356. effect.setTexture("specularSampler", this._specularTexture);
  40357. }
  40358. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40359. effect.setTexture("bumpSampler", this._bumpTexture);
  40360. }
  40361. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40362. var depth = 1.0;
  40363. if (this._refractionTexture.isCube) {
  40364. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40365. }
  40366. else {
  40367. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40368. }
  40369. }
  40370. }
  40371. // Clip plane
  40372. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40373. // Colors
  40374. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40375. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40376. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40377. }
  40378. if (mustRebind || !this.isFrozen) {
  40379. // Lights
  40380. if (scene.lightsEnabled && !this._disableLighting) {
  40381. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40382. }
  40383. // View
  40384. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40385. this.bindView(effect);
  40386. }
  40387. // Fog
  40388. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40389. // Morph targets
  40390. if (defines.NUM_MORPH_INFLUENCERS) {
  40391. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40392. }
  40393. // Log. depth
  40394. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40395. // image processing
  40396. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40397. this._imageProcessingConfiguration.bind(this._activeEffect);
  40398. }
  40399. }
  40400. this._uniformBuffer.update();
  40401. this._afterBind(mesh, this._activeEffect);
  40402. };
  40403. StandardMaterial.prototype.getAnimatables = function () {
  40404. var results = [];
  40405. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40406. results.push(this._diffuseTexture);
  40407. }
  40408. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40409. results.push(this._ambientTexture);
  40410. }
  40411. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40412. results.push(this._opacityTexture);
  40413. }
  40414. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40415. results.push(this._reflectionTexture);
  40416. }
  40417. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40418. results.push(this._emissiveTexture);
  40419. }
  40420. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40421. results.push(this._specularTexture);
  40422. }
  40423. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40424. results.push(this._bumpTexture);
  40425. }
  40426. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40427. results.push(this._lightmapTexture);
  40428. }
  40429. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40430. results.push(this._refractionTexture);
  40431. }
  40432. return results;
  40433. };
  40434. StandardMaterial.prototype.getActiveTextures = function () {
  40435. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40436. if (this._diffuseTexture) {
  40437. activeTextures.push(this._diffuseTexture);
  40438. }
  40439. if (this._ambientTexture) {
  40440. activeTextures.push(this._ambientTexture);
  40441. }
  40442. if (this._opacityTexture) {
  40443. activeTextures.push(this._opacityTexture);
  40444. }
  40445. if (this._reflectionTexture) {
  40446. activeTextures.push(this._reflectionTexture);
  40447. }
  40448. if (this._emissiveTexture) {
  40449. activeTextures.push(this._emissiveTexture);
  40450. }
  40451. if (this._specularTexture) {
  40452. activeTextures.push(this._specularTexture);
  40453. }
  40454. if (this._bumpTexture) {
  40455. activeTextures.push(this._bumpTexture);
  40456. }
  40457. if (this._lightmapTexture) {
  40458. activeTextures.push(this._lightmapTexture);
  40459. }
  40460. if (this._refractionTexture) {
  40461. activeTextures.push(this._refractionTexture);
  40462. }
  40463. return activeTextures;
  40464. };
  40465. StandardMaterial.prototype.hasTexture = function (texture) {
  40466. if (_super.prototype.hasTexture.call(this, texture)) {
  40467. return true;
  40468. }
  40469. if (this._diffuseTexture === texture) {
  40470. return true;
  40471. }
  40472. if (this._ambientTexture === texture) {
  40473. return true;
  40474. }
  40475. if (this._opacityTexture === texture) {
  40476. return true;
  40477. }
  40478. if (this._reflectionTexture === texture) {
  40479. return true;
  40480. }
  40481. if (this._emissiveTexture === texture) {
  40482. return true;
  40483. }
  40484. if (this._specularTexture === texture) {
  40485. return true;
  40486. }
  40487. if (this._bumpTexture === texture) {
  40488. return true;
  40489. }
  40490. if (this._lightmapTexture === texture) {
  40491. return true;
  40492. }
  40493. if (this._refractionTexture === texture) {
  40494. return true;
  40495. }
  40496. return false;
  40497. };
  40498. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40499. if (forceDisposeTextures) {
  40500. if (this._diffuseTexture) {
  40501. this._diffuseTexture.dispose();
  40502. }
  40503. if (this._ambientTexture) {
  40504. this._ambientTexture.dispose();
  40505. }
  40506. if (this._opacityTexture) {
  40507. this._opacityTexture.dispose();
  40508. }
  40509. if (this._reflectionTexture) {
  40510. this._reflectionTexture.dispose();
  40511. }
  40512. if (this._emissiveTexture) {
  40513. this._emissiveTexture.dispose();
  40514. }
  40515. if (this._specularTexture) {
  40516. this._specularTexture.dispose();
  40517. }
  40518. if (this._bumpTexture) {
  40519. this._bumpTexture.dispose();
  40520. }
  40521. if (this._lightmapTexture) {
  40522. this._lightmapTexture.dispose();
  40523. }
  40524. if (this._refractionTexture) {
  40525. this._refractionTexture.dispose();
  40526. }
  40527. }
  40528. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40529. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40530. }
  40531. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40532. };
  40533. StandardMaterial.prototype.clone = function (name) {
  40534. var _this = this;
  40535. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40536. result.name = name;
  40537. result.id = name;
  40538. return result;
  40539. };
  40540. StandardMaterial.prototype.serialize = function () {
  40541. return BABYLON.SerializationHelper.Serialize(this);
  40542. };
  40543. // Statics
  40544. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40545. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40546. };
  40547. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40548. get: function () {
  40549. return StandardMaterial._DiffuseTextureEnabled;
  40550. },
  40551. set: function (value) {
  40552. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40553. return;
  40554. }
  40555. StandardMaterial._DiffuseTextureEnabled = value;
  40556. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40557. },
  40558. enumerable: true,
  40559. configurable: true
  40560. });
  40561. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40562. get: function () {
  40563. return StandardMaterial._AmbientTextureEnabled;
  40564. },
  40565. set: function (value) {
  40566. if (StandardMaterial._AmbientTextureEnabled === value) {
  40567. return;
  40568. }
  40569. StandardMaterial._AmbientTextureEnabled = value;
  40570. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40571. },
  40572. enumerable: true,
  40573. configurable: true
  40574. });
  40575. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40576. get: function () {
  40577. return StandardMaterial._OpacityTextureEnabled;
  40578. },
  40579. set: function (value) {
  40580. if (StandardMaterial._OpacityTextureEnabled === value) {
  40581. return;
  40582. }
  40583. StandardMaterial._OpacityTextureEnabled = value;
  40584. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40585. },
  40586. enumerable: true,
  40587. configurable: true
  40588. });
  40589. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40590. get: function () {
  40591. return StandardMaterial._ReflectionTextureEnabled;
  40592. },
  40593. set: function (value) {
  40594. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40595. return;
  40596. }
  40597. StandardMaterial._ReflectionTextureEnabled = value;
  40598. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40599. },
  40600. enumerable: true,
  40601. configurable: true
  40602. });
  40603. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40604. get: function () {
  40605. return StandardMaterial._EmissiveTextureEnabled;
  40606. },
  40607. set: function (value) {
  40608. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40609. return;
  40610. }
  40611. StandardMaterial._EmissiveTextureEnabled = value;
  40612. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40613. },
  40614. enumerable: true,
  40615. configurable: true
  40616. });
  40617. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40618. get: function () {
  40619. return StandardMaterial._SpecularTextureEnabled;
  40620. },
  40621. set: function (value) {
  40622. if (StandardMaterial._SpecularTextureEnabled === value) {
  40623. return;
  40624. }
  40625. StandardMaterial._SpecularTextureEnabled = value;
  40626. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40627. },
  40628. enumerable: true,
  40629. configurable: true
  40630. });
  40631. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40632. get: function () {
  40633. return StandardMaterial._BumpTextureEnabled;
  40634. },
  40635. set: function (value) {
  40636. if (StandardMaterial._BumpTextureEnabled === value) {
  40637. return;
  40638. }
  40639. StandardMaterial._BumpTextureEnabled = value;
  40640. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40641. },
  40642. enumerable: true,
  40643. configurable: true
  40644. });
  40645. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40646. get: function () {
  40647. return StandardMaterial._LightmapTextureEnabled;
  40648. },
  40649. set: function (value) {
  40650. if (StandardMaterial._LightmapTextureEnabled === value) {
  40651. return;
  40652. }
  40653. StandardMaterial._LightmapTextureEnabled = value;
  40654. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40655. },
  40656. enumerable: true,
  40657. configurable: true
  40658. });
  40659. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40660. get: function () {
  40661. return StandardMaterial._RefractionTextureEnabled;
  40662. },
  40663. set: function (value) {
  40664. if (StandardMaterial._RefractionTextureEnabled === value) {
  40665. return;
  40666. }
  40667. StandardMaterial._RefractionTextureEnabled = value;
  40668. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40669. },
  40670. enumerable: true,
  40671. configurable: true
  40672. });
  40673. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40674. get: function () {
  40675. return StandardMaterial._ColorGradingTextureEnabled;
  40676. },
  40677. set: function (value) {
  40678. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40679. return;
  40680. }
  40681. StandardMaterial._ColorGradingTextureEnabled = value;
  40682. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40683. },
  40684. enumerable: true,
  40685. configurable: true
  40686. });
  40687. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40688. get: function () {
  40689. return StandardMaterial._FresnelEnabled;
  40690. },
  40691. set: function (value) {
  40692. if (StandardMaterial._FresnelEnabled === value) {
  40693. return;
  40694. }
  40695. StandardMaterial._FresnelEnabled = value;
  40696. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40697. },
  40698. enumerable: true,
  40699. configurable: true
  40700. });
  40701. // Flags used to enable or disable a type of texture for all Standard Materials
  40702. StandardMaterial._DiffuseTextureEnabled = true;
  40703. StandardMaterial._AmbientTextureEnabled = true;
  40704. StandardMaterial._OpacityTextureEnabled = true;
  40705. StandardMaterial._ReflectionTextureEnabled = true;
  40706. StandardMaterial._EmissiveTextureEnabled = true;
  40707. StandardMaterial._SpecularTextureEnabled = true;
  40708. StandardMaterial._BumpTextureEnabled = true;
  40709. StandardMaterial._LightmapTextureEnabled = true;
  40710. StandardMaterial._RefractionTextureEnabled = true;
  40711. StandardMaterial._ColorGradingTextureEnabled = true;
  40712. StandardMaterial._FresnelEnabled = true;
  40713. __decorate([
  40714. BABYLON.serializeAsTexture("diffuseTexture")
  40715. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40716. __decorate([
  40717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40718. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40719. __decorate([
  40720. BABYLON.serializeAsTexture("ambientTexture")
  40721. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40722. __decorate([
  40723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40724. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40725. __decorate([
  40726. BABYLON.serializeAsTexture("opacityTexture")
  40727. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40728. __decorate([
  40729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40730. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40731. __decorate([
  40732. BABYLON.serializeAsTexture("reflectionTexture")
  40733. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40734. __decorate([
  40735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40736. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40737. __decorate([
  40738. BABYLON.serializeAsTexture("emissiveTexture")
  40739. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40740. __decorate([
  40741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40742. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40743. __decorate([
  40744. BABYLON.serializeAsTexture("specularTexture")
  40745. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40746. __decorate([
  40747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40748. ], StandardMaterial.prototype, "specularTexture", void 0);
  40749. __decorate([
  40750. BABYLON.serializeAsTexture("bumpTexture")
  40751. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40752. __decorate([
  40753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40754. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40755. __decorate([
  40756. BABYLON.serializeAsTexture("lightmapTexture")
  40757. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40758. __decorate([
  40759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40760. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40761. __decorate([
  40762. BABYLON.serializeAsTexture("refractionTexture")
  40763. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40764. __decorate([
  40765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40766. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40767. __decorate([
  40768. BABYLON.serializeAsColor3("ambient")
  40769. ], StandardMaterial.prototype, "ambientColor", void 0);
  40770. __decorate([
  40771. BABYLON.serializeAsColor3("diffuse")
  40772. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40773. __decorate([
  40774. BABYLON.serializeAsColor3("specular")
  40775. ], StandardMaterial.prototype, "specularColor", void 0);
  40776. __decorate([
  40777. BABYLON.serializeAsColor3("emissive")
  40778. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40779. __decorate([
  40780. BABYLON.serialize()
  40781. ], StandardMaterial.prototype, "specularPower", void 0);
  40782. __decorate([
  40783. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40784. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40785. __decorate([
  40786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40787. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40788. __decorate([
  40789. BABYLON.serialize("useEmissiveAsIllumination")
  40790. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40791. __decorate([
  40792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40793. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40794. __decorate([
  40795. BABYLON.serialize("linkEmissiveWithDiffuse")
  40796. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40797. __decorate([
  40798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40799. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40800. __decorate([
  40801. BABYLON.serialize("useSpecularOverAlpha")
  40802. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40803. __decorate([
  40804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40805. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40806. __decorate([
  40807. BABYLON.serialize("useReflectionOverAlpha")
  40808. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40809. __decorate([
  40810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40811. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40812. __decorate([
  40813. BABYLON.serialize("disableLighting")
  40814. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40815. __decorate([
  40816. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40817. ], StandardMaterial.prototype, "disableLighting", void 0);
  40818. __decorate([
  40819. BABYLON.serialize("useObjectSpaceNormalMap")
  40820. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40821. __decorate([
  40822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40823. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40824. __decorate([
  40825. BABYLON.serialize("useParallax")
  40826. ], StandardMaterial.prototype, "_useParallax", void 0);
  40827. __decorate([
  40828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40829. ], StandardMaterial.prototype, "useParallax", void 0);
  40830. __decorate([
  40831. BABYLON.serialize("useParallaxOcclusion")
  40832. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40833. __decorate([
  40834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40835. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40836. __decorate([
  40837. BABYLON.serialize()
  40838. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40839. __decorate([
  40840. BABYLON.serialize("roughness")
  40841. ], StandardMaterial.prototype, "_roughness", void 0);
  40842. __decorate([
  40843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40844. ], StandardMaterial.prototype, "roughness", void 0);
  40845. __decorate([
  40846. BABYLON.serialize()
  40847. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40848. __decorate([
  40849. BABYLON.serialize()
  40850. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40851. __decorate([
  40852. BABYLON.serialize("useLightmapAsShadowmap")
  40853. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40854. __decorate([
  40855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40856. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40857. __decorate([
  40858. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40859. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40860. __decorate([
  40861. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40862. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40863. __decorate([
  40864. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40865. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40866. __decorate([
  40867. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40868. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40869. __decorate([
  40870. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40871. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40872. __decorate([
  40873. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40874. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40875. __decorate([
  40876. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40877. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40878. __decorate([
  40879. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40880. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40881. __decorate([
  40882. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40883. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40884. __decorate([
  40885. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40886. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40887. __decorate([
  40888. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40889. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40890. __decorate([
  40891. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40892. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40893. __decorate([
  40894. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40895. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40896. __decorate([
  40897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40898. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40899. __decorate([
  40900. BABYLON.serialize("maxSimultaneousLights")
  40901. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40902. __decorate([
  40903. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40904. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40905. __decorate([
  40906. BABYLON.serialize("invertNormalMapX")
  40907. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40908. __decorate([
  40909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40910. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40911. __decorate([
  40912. BABYLON.serialize("invertNormalMapY")
  40913. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40914. __decorate([
  40915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40916. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40917. __decorate([
  40918. BABYLON.serialize("twoSidedLighting")
  40919. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40920. __decorate([
  40921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40922. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40923. __decorate([
  40924. BABYLON.serialize()
  40925. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40926. return StandardMaterial;
  40927. }(BABYLON.PushMaterial));
  40928. BABYLON.StandardMaterial = StandardMaterial;
  40929. })(BABYLON || (BABYLON = {}));
  40930. //# sourceMappingURL=babylon.standardMaterial.js.map
  40931. "use strict";
  40932. var BABYLON;
  40933. (function (BABYLON) {
  40934. /**
  40935. * Manages the defines for the PBR Material.
  40936. */
  40937. var PBRMaterialDefines = /** @class */ (function (_super) {
  40938. __extends(PBRMaterialDefines, _super);
  40939. /**
  40940. * Initializes the PBR Material defines.
  40941. */
  40942. function PBRMaterialDefines() {
  40943. var _this = _super.call(this) || this;
  40944. _this.PBR = true;
  40945. _this.MAINUV1 = false;
  40946. _this.MAINUV2 = false;
  40947. _this.UV1 = false;
  40948. _this.UV2 = false;
  40949. _this.ALBEDO = false;
  40950. _this.ALBEDODIRECTUV = 0;
  40951. _this.VERTEXCOLOR = false;
  40952. _this.AMBIENT = false;
  40953. _this.AMBIENTDIRECTUV = 0;
  40954. _this.AMBIENTINGRAYSCALE = false;
  40955. _this.OPACITY = false;
  40956. _this.VERTEXALPHA = false;
  40957. _this.OPACITYDIRECTUV = 0;
  40958. _this.OPACITYRGB = false;
  40959. _this.ALPHATEST = false;
  40960. _this.DEPTHPREPASS = false;
  40961. _this.ALPHABLEND = false;
  40962. _this.ALPHAFROMALBEDO = false;
  40963. _this.ALPHATESTVALUE = 0.5;
  40964. _this.SPECULAROVERALPHA = false;
  40965. _this.RADIANCEOVERALPHA = false;
  40966. _this.ALPHAFRESNEL = false;
  40967. _this.LINEARALPHAFRESNEL = false;
  40968. _this.PREMULTIPLYALPHA = false;
  40969. _this.EMISSIVE = false;
  40970. _this.EMISSIVEDIRECTUV = 0;
  40971. _this.REFLECTIVITY = false;
  40972. _this.REFLECTIVITYDIRECTUV = 0;
  40973. _this.SPECULARTERM = false;
  40974. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40975. _this.MICROSURFACEAUTOMATIC = false;
  40976. _this.LODBASEDMICROSFURACE = false;
  40977. _this.MICROSURFACEMAP = false;
  40978. _this.MICROSURFACEMAPDIRECTUV = 0;
  40979. _this.METALLICWORKFLOW = false;
  40980. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40981. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40982. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40983. _this.AOSTOREINMETALMAPRED = false;
  40984. _this.ENVIRONMENTBRDF = false;
  40985. _this.NORMAL = false;
  40986. _this.TANGENT = false;
  40987. _this.BUMP = false;
  40988. _this.BUMPDIRECTUV = 0;
  40989. _this.OBJECTSPACE_NORMALMAP = false;
  40990. _this.PARALLAX = false;
  40991. _this.PARALLAXOCCLUSION = false;
  40992. _this.NORMALXYSCALE = true;
  40993. _this.LIGHTMAP = false;
  40994. _this.LIGHTMAPDIRECTUV = 0;
  40995. _this.USELIGHTMAPASSHADOWMAP = false;
  40996. _this.GAMMALIGHTMAP = false;
  40997. _this.REFLECTION = false;
  40998. _this.REFLECTIONMAP_3D = false;
  40999. _this.REFLECTIONMAP_SPHERICAL = false;
  41000. _this.REFLECTIONMAP_PLANAR = false;
  41001. _this.REFLECTIONMAP_CUBIC = false;
  41002. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41003. _this.REFLECTIONMAP_PROJECTION = false;
  41004. _this.REFLECTIONMAP_SKYBOX = false;
  41005. _this.REFLECTIONMAP_EXPLICIT = false;
  41006. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41007. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41008. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41009. _this.INVERTCUBICMAP = false;
  41010. _this.USESPHERICALFROMREFLECTIONMAP = false;
  41011. _this.USESPHERICALINVERTEX = false;
  41012. _this.REFLECTIONMAP_OPPOSITEZ = false;
  41013. _this.LODINREFLECTIONALPHA = false;
  41014. _this.GAMMAREFLECTION = false;
  41015. _this.RADIANCEOCCLUSION = false;
  41016. _this.HORIZONOCCLUSION = false;
  41017. _this.REFRACTION = false;
  41018. _this.REFRACTIONMAP_3D = false;
  41019. _this.REFRACTIONMAP_OPPOSITEZ = false;
  41020. _this.LODINREFRACTIONALPHA = false;
  41021. _this.GAMMAREFRACTION = false;
  41022. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  41023. _this.INSTANCES = false;
  41024. _this.NUM_BONE_INFLUENCERS = 0;
  41025. _this.BonesPerMesh = 0;
  41026. _this.NONUNIFORMSCALING = false;
  41027. _this.MORPHTARGETS = false;
  41028. _this.MORPHTARGETS_NORMAL = false;
  41029. _this.MORPHTARGETS_TANGENT = false;
  41030. _this.NUM_MORPH_INFLUENCERS = 0;
  41031. _this.IMAGEPROCESSING = false;
  41032. _this.VIGNETTE = false;
  41033. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41034. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41035. _this.TONEMAPPING = false;
  41036. _this.CONTRAST = false;
  41037. _this.COLORCURVES = false;
  41038. _this.COLORGRADING = false;
  41039. _this.COLORGRADING3D = false;
  41040. _this.SAMPLER3DGREENDEPTH = false;
  41041. _this.SAMPLER3DBGRMAP = false;
  41042. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41043. _this.EXPOSURE = false;
  41044. _this.GRAIN = false;
  41045. _this.USEPHYSICALLIGHTFALLOFF = false;
  41046. _this.TWOSIDEDLIGHTING = false;
  41047. _this.SHADOWFLOAT = false;
  41048. _this.CLIPPLANE = false;
  41049. _this.POINTSIZE = false;
  41050. _this.FOG = false;
  41051. _this.LOGARITHMICDEPTH = false;
  41052. _this.FORCENORMALFORWARD = false;
  41053. _this.UNLIT = false;
  41054. _this.rebuild();
  41055. return _this;
  41056. }
  41057. /**
  41058. * Resets the PBR Material defines.
  41059. */
  41060. PBRMaterialDefines.prototype.reset = function () {
  41061. _super.prototype.reset.call(this);
  41062. this.ALPHATESTVALUE = 0.5;
  41063. this.PBR = true;
  41064. };
  41065. return PBRMaterialDefines;
  41066. }(BABYLON.MaterialDefines));
  41067. /**
  41068. * The Physically based material base class of BJS.
  41069. *
  41070. * This offers the main features of a standard PBR material.
  41071. * For more information, please refer to the documentation :
  41072. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41073. */
  41074. var PBRBaseMaterial = /** @class */ (function (_super) {
  41075. __extends(PBRBaseMaterial, _super);
  41076. /**
  41077. * Instantiates a new PBRMaterial instance.
  41078. *
  41079. * @param name The material name
  41080. * @param scene The scene the material will be use in.
  41081. */
  41082. function PBRBaseMaterial(name, scene) {
  41083. var _this = _super.call(this, name, scene) || this;
  41084. /**
  41085. * Intensity of the direct lights e.g. the four lights available in your scene.
  41086. * This impacts both the direct diffuse and specular highlights.
  41087. */
  41088. _this._directIntensity = 1.0;
  41089. /**
  41090. * Intensity of the emissive part of the material.
  41091. * This helps controlling the emissive effect without modifying the emissive color.
  41092. */
  41093. _this._emissiveIntensity = 1.0;
  41094. /**
  41095. * Intensity of the environment e.g. how much the environment will light the object
  41096. * either through harmonics for rough material or through the refelction for shiny ones.
  41097. */
  41098. _this._environmentIntensity = 1.0;
  41099. /**
  41100. * This is a special control allowing the reduction of the specular highlights coming from the
  41101. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41102. */
  41103. _this._specularIntensity = 1.0;
  41104. /**
  41105. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41106. */
  41107. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41108. /**
  41109. * Debug Control allowing disabling the bump map on this material.
  41110. */
  41111. _this._disableBumpMap = false;
  41112. /**
  41113. * AKA Occlusion Texture Intensity in other nomenclature.
  41114. */
  41115. _this._ambientTextureStrength = 1.0;
  41116. /**
  41117. * The color of a material in ambient lighting.
  41118. */
  41119. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41120. /**
  41121. * AKA Diffuse Color in other nomenclature.
  41122. */
  41123. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41124. /**
  41125. * AKA Specular Color in other nomenclature.
  41126. */
  41127. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41128. /**
  41129. * The color applied when light is reflected from a material.
  41130. */
  41131. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41132. /**
  41133. * The color applied when light is emitted from a material.
  41134. */
  41135. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41136. /**
  41137. * AKA Glossiness in other nomenclature.
  41138. */
  41139. _this._microSurface = 0.9;
  41140. /**
  41141. * source material index of refraction (IOR)' / 'destination material IOR.
  41142. */
  41143. _this._indexOfRefraction = 0.66;
  41144. /**
  41145. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41146. */
  41147. _this._invertRefractionY = false;
  41148. /**
  41149. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41150. * Materials half opaque for instance using refraction could benefit from this control.
  41151. */
  41152. _this._linkRefractionWithTransparency = false;
  41153. /**
  41154. * Specifies that the material will use the light map as a show map.
  41155. */
  41156. _this._useLightmapAsShadowmap = false;
  41157. /**
  41158. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41159. * makes the reflect vector face the model (under horizon).
  41160. */
  41161. _this._useHorizonOcclusion = true;
  41162. /**
  41163. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41164. * too much the area relying on ambient texture to define their ambient occlusion.
  41165. */
  41166. _this._useRadianceOcclusion = true;
  41167. /**
  41168. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41169. */
  41170. _this._useAlphaFromAlbedoTexture = false;
  41171. /**
  41172. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41173. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41174. */
  41175. _this._useSpecularOverAlpha = true;
  41176. /**
  41177. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41178. */
  41179. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41180. /**
  41181. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41182. */
  41183. _this._useRoughnessFromMetallicTextureAlpha = true;
  41184. /**
  41185. * Specifies if the metallic texture contains the roughness information in its green channel.
  41186. */
  41187. _this._useRoughnessFromMetallicTextureGreen = false;
  41188. /**
  41189. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41190. */
  41191. _this._useMetallnessFromMetallicTextureBlue = false;
  41192. /**
  41193. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41194. */
  41195. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41196. /**
  41197. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41198. */
  41199. _this._useAmbientInGrayScale = false;
  41200. /**
  41201. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41202. * The material will try to infer what glossiness each pixel should be.
  41203. */
  41204. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41205. /**
  41206. * BJS is using an harcoded light falloff based on a manually sets up range.
  41207. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41208. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41209. */
  41210. _this._usePhysicalLightFalloff = true;
  41211. /**
  41212. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41213. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41214. */
  41215. _this._useRadianceOverAlpha = true;
  41216. /**
  41217. * Allows using an object space normal map (instead of tangent space).
  41218. */
  41219. _this._useObjectSpaceNormalMap = false;
  41220. /**
  41221. * Allows using the bump map in parallax mode.
  41222. */
  41223. _this._useParallax = false;
  41224. /**
  41225. * Allows using the bump map in parallax occlusion mode.
  41226. */
  41227. _this._useParallaxOcclusion = false;
  41228. /**
  41229. * Controls the scale bias of the parallax mode.
  41230. */
  41231. _this._parallaxScaleBias = 0.05;
  41232. /**
  41233. * If sets to true, disables all the lights affecting the material.
  41234. */
  41235. _this._disableLighting = false;
  41236. /**
  41237. * Number of Simultaneous lights allowed on the material.
  41238. */
  41239. _this._maxSimultaneousLights = 4;
  41240. /**
  41241. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41242. */
  41243. _this._invertNormalMapX = false;
  41244. /**
  41245. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41246. */
  41247. _this._invertNormalMapY = false;
  41248. /**
  41249. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41250. */
  41251. _this._twoSidedLighting = false;
  41252. /**
  41253. * Defines the alpha limits in alpha test mode.
  41254. */
  41255. _this._alphaCutOff = 0.4;
  41256. /**
  41257. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41258. */
  41259. _this._forceAlphaTest = false;
  41260. /**
  41261. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41262. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41263. */
  41264. _this._useAlphaFresnel = false;
  41265. /**
  41266. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41267. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41268. */
  41269. _this._useLinearAlphaFresnel = false;
  41270. /**
  41271. * The transparency mode of the material.
  41272. */
  41273. _this._transparencyMode = null;
  41274. /**
  41275. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41276. * from cos thetav and roughness:
  41277. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41278. */
  41279. _this._environmentBRDFTexture = null;
  41280. /**
  41281. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41282. */
  41283. _this._forceIrradianceInFragment = false;
  41284. /**
  41285. * Force normal to face away from face.
  41286. */
  41287. _this._forceNormalForward = false;
  41288. /**
  41289. * Stores the available render targets.
  41290. */
  41291. _this._renderTargets = new BABYLON.SmartArray(16);
  41292. /**
  41293. * Sets the global ambient color for the material used in lighting calculations.
  41294. */
  41295. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41296. /**
  41297. * If set to true, no lighting calculations will be applied.
  41298. */
  41299. _this._unlit = false;
  41300. // Setup the default processing configuration to the scene.
  41301. _this._attachImageProcessingConfiguration(null);
  41302. _this.getRenderTargetTextures = function () {
  41303. _this._renderTargets.reset();
  41304. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41305. _this._renderTargets.push(_this._reflectionTexture);
  41306. }
  41307. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41308. _this._renderTargets.push(_this._refractionTexture);
  41309. }
  41310. return _this._renderTargets;
  41311. };
  41312. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41313. return _this;
  41314. }
  41315. /**
  41316. * Attaches a new image processing configuration to the PBR Material.
  41317. * @param configuration
  41318. */
  41319. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41320. var _this = this;
  41321. if (configuration === this._imageProcessingConfiguration) {
  41322. return;
  41323. }
  41324. // Detaches observer.
  41325. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41326. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41327. }
  41328. // Pick the scene configuration if needed.
  41329. if (!configuration) {
  41330. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41331. }
  41332. else {
  41333. this._imageProcessingConfiguration = configuration;
  41334. }
  41335. // Attaches observer.
  41336. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41337. _this._markAllSubMeshesAsImageProcessingDirty();
  41338. });
  41339. };
  41340. /**
  41341. * Gets the name of the material class.
  41342. */
  41343. PBRBaseMaterial.prototype.getClassName = function () {
  41344. return "PBRBaseMaterial";
  41345. };
  41346. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41347. /**
  41348. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41349. */
  41350. get: function () {
  41351. return this._useLogarithmicDepth;
  41352. },
  41353. /**
  41354. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41355. */
  41356. set: function (value) {
  41357. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41358. },
  41359. enumerable: true,
  41360. configurable: true
  41361. });
  41362. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41363. /**
  41364. * Gets the current transparency mode.
  41365. */
  41366. get: function () {
  41367. return this._transparencyMode;
  41368. },
  41369. /**
  41370. * Sets the transparency mode of the material.
  41371. */
  41372. set: function (value) {
  41373. if (this._transparencyMode === value) {
  41374. return;
  41375. }
  41376. this._transparencyMode = value;
  41377. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41378. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41379. },
  41380. enumerable: true,
  41381. configurable: true
  41382. });
  41383. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41384. /**
  41385. * Returns true if alpha blending should be disabled.
  41386. */
  41387. get: function () {
  41388. return (this._linkRefractionWithTransparency ||
  41389. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41390. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41391. },
  41392. enumerable: true,
  41393. configurable: true
  41394. });
  41395. /**
  41396. * Specifies whether or not this material should be rendered in alpha blend mode.
  41397. */
  41398. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41399. if (this._disableAlphaBlending) {
  41400. return false;
  41401. }
  41402. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41403. };
  41404. /**
  41405. * Specifies if the mesh will require alpha blending.
  41406. * @param mesh - BJS mesh.
  41407. */
  41408. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41409. if (this._disableAlphaBlending) {
  41410. return false;
  41411. }
  41412. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41413. };
  41414. /**
  41415. * Specifies whether or not this material should be rendered in alpha test mode.
  41416. */
  41417. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41418. if (this._forceAlphaTest) {
  41419. return true;
  41420. }
  41421. if (this._linkRefractionWithTransparency) {
  41422. return false;
  41423. }
  41424. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41425. };
  41426. /**
  41427. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41428. */
  41429. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41430. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41431. };
  41432. /**
  41433. * Gets the texture used for the alpha test.
  41434. */
  41435. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41436. return this._albedoTexture;
  41437. };
  41438. /**
  41439. * Specifies that the submesh is ready to be used.
  41440. * @param mesh - BJS mesh.
  41441. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41442. * @param useInstances - Specifies that instances should be used.
  41443. * @returns - boolean indicating that the submesh is ready or not.
  41444. */
  41445. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41446. if (subMesh.effect && this.isFrozen) {
  41447. if (this._wasPreviouslyReady) {
  41448. return true;
  41449. }
  41450. }
  41451. if (!subMesh._materialDefines) {
  41452. subMesh._materialDefines = new PBRMaterialDefines();
  41453. }
  41454. var defines = subMesh._materialDefines;
  41455. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41456. if (defines._renderId === this.getScene().getRenderId()) {
  41457. return true;
  41458. }
  41459. }
  41460. var scene = this.getScene();
  41461. var engine = scene.getEngine();
  41462. if (defines._areTexturesDirty) {
  41463. if (scene.texturesEnabled) {
  41464. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41465. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41466. return false;
  41467. }
  41468. }
  41469. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41470. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41471. return false;
  41472. }
  41473. }
  41474. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41475. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41476. return false;
  41477. }
  41478. }
  41479. var reflectionTexture = this._getReflectionTexture();
  41480. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41481. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41482. return false;
  41483. }
  41484. }
  41485. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41486. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41487. return false;
  41488. }
  41489. }
  41490. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41491. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41492. return false;
  41493. }
  41494. }
  41495. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41496. if (this._metallicTexture) {
  41497. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41498. return false;
  41499. }
  41500. }
  41501. else if (this._reflectivityTexture) {
  41502. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41503. return false;
  41504. }
  41505. }
  41506. if (this._microSurfaceTexture) {
  41507. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41508. return false;
  41509. }
  41510. }
  41511. }
  41512. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41513. // Bump texture cannot be not blocking.
  41514. if (!this._bumpTexture.isReady()) {
  41515. return false;
  41516. }
  41517. }
  41518. var refractionTexture = this._getRefractionTexture();
  41519. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41520. if (!refractionTexture.isReadyOrNotBlocking()) {
  41521. return false;
  41522. }
  41523. }
  41524. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41525. // This is blocking.
  41526. if (!this._environmentBRDFTexture.isReady()) {
  41527. return false;
  41528. }
  41529. }
  41530. }
  41531. }
  41532. if (defines._areImageProcessingDirty) {
  41533. if (!this._imageProcessingConfiguration.isReady()) {
  41534. return false;
  41535. }
  41536. }
  41537. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41538. mesh.createNormals(true);
  41539. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41540. }
  41541. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41542. if (effect) {
  41543. scene.resetCachedMaterial();
  41544. subMesh.setEffect(effect, defines);
  41545. this.buildUniformLayout();
  41546. }
  41547. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41548. return false;
  41549. }
  41550. defines._renderId = scene.getRenderId();
  41551. this._wasPreviouslyReady = true;
  41552. return true;
  41553. };
  41554. /**
  41555. * Specifies if the material uses metallic roughness workflow.
  41556. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41557. */
  41558. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41559. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41560. return true;
  41561. }
  41562. return false;
  41563. };
  41564. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41565. if (onCompiled === void 0) { onCompiled = null; }
  41566. if (onError === void 0) { onError = null; }
  41567. if (useInstances === void 0) { useInstances = null; }
  41568. if (useClipPlane === void 0) { useClipPlane = null; }
  41569. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41570. if (!defines.isDirty) {
  41571. return null;
  41572. }
  41573. defines.markAsProcessed();
  41574. var scene = this.getScene();
  41575. var engine = scene.getEngine();
  41576. // Fallbacks
  41577. var fallbacks = new BABYLON.EffectFallbacks();
  41578. var fallbackRank = 0;
  41579. if (defines.USESPHERICALINVERTEX) {
  41580. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41581. }
  41582. if (defines.FOG) {
  41583. fallbacks.addFallback(fallbackRank, "FOG");
  41584. }
  41585. if (defines.POINTSIZE) {
  41586. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41587. }
  41588. if (defines.LOGARITHMICDEPTH) {
  41589. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41590. }
  41591. if (defines.PARALLAX) {
  41592. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41593. }
  41594. if (defines.PARALLAXOCCLUSION) {
  41595. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41596. }
  41597. if (defines.ENVIRONMENTBRDF) {
  41598. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41599. }
  41600. if (defines.TANGENT) {
  41601. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41602. }
  41603. if (defines.BUMP) {
  41604. fallbacks.addFallback(fallbackRank++, "BUMP");
  41605. }
  41606. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41607. if (defines.SPECULARTERM) {
  41608. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41609. }
  41610. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41611. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41612. }
  41613. if (defines.LIGHTMAP) {
  41614. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41615. }
  41616. if (defines.NORMAL) {
  41617. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41618. }
  41619. if (defines.AMBIENT) {
  41620. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41621. }
  41622. if (defines.EMISSIVE) {
  41623. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41624. }
  41625. if (defines.VERTEXCOLOR) {
  41626. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41627. }
  41628. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41629. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41630. }
  41631. if (defines.MORPHTARGETS) {
  41632. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41633. }
  41634. //Attributes
  41635. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41636. if (defines.NORMAL) {
  41637. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41638. }
  41639. if (defines.TANGENT) {
  41640. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41641. }
  41642. if (defines.UV1) {
  41643. attribs.push(BABYLON.VertexBuffer.UVKind);
  41644. }
  41645. if (defines.UV2) {
  41646. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41647. }
  41648. if (defines.VERTEXCOLOR) {
  41649. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41650. }
  41651. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41652. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41653. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41654. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41655. "vFogInfos", "vFogColor", "pointSize",
  41656. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41657. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41658. "mBones",
  41659. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41660. "vLightingIntensity",
  41661. "logarithmicDepthConstant",
  41662. "vSphericalX", "vSphericalY", "vSphericalZ",
  41663. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41664. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41665. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41666. "vTangentSpaceParams"
  41667. ];
  41668. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41669. "bumpSampler", "lightmapSampler", "opacitySampler",
  41670. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41671. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41672. "microSurfaceSampler", "environmentBrdfSampler"];
  41673. var uniformBuffers = ["Material", "Scene"];
  41674. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41675. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41676. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41677. uniformsNames: uniforms,
  41678. uniformBuffersNames: uniformBuffers,
  41679. samplers: samplers,
  41680. defines: defines,
  41681. maxSimultaneousLights: this._maxSimultaneousLights
  41682. });
  41683. var join = defines.toString();
  41684. return engine.createEffect("pbr", {
  41685. attributes: attribs,
  41686. uniformsNames: uniforms,
  41687. uniformBuffersNames: uniformBuffers,
  41688. samplers: samplers,
  41689. defines: join,
  41690. fallbacks: fallbacks,
  41691. onCompiled: onCompiled,
  41692. onError: onError,
  41693. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41694. }, engine);
  41695. };
  41696. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41697. if (useInstances === void 0) { useInstances = null; }
  41698. if (useClipPlane === void 0) { useClipPlane = null; }
  41699. var scene = this.getScene();
  41700. var engine = scene.getEngine();
  41701. // Lights
  41702. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41703. defines._needNormals = true;
  41704. // Textures
  41705. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41706. if (defines._areTexturesDirty) {
  41707. defines._needUVs = false;
  41708. if (scene.texturesEnabled) {
  41709. if (scene.getEngine().getCaps().textureLOD) {
  41710. defines.LODBASEDMICROSFURACE = true;
  41711. }
  41712. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41713. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41714. }
  41715. else {
  41716. defines.ALBEDO = false;
  41717. }
  41718. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41719. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41720. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41721. }
  41722. else {
  41723. defines.AMBIENT = false;
  41724. }
  41725. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41726. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41727. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41728. }
  41729. else {
  41730. defines.OPACITY = false;
  41731. }
  41732. var reflectionTexture = this._getReflectionTexture();
  41733. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41734. defines.REFLECTION = true;
  41735. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41736. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41737. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41738. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41739. defines.INVERTCUBICMAP = true;
  41740. }
  41741. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41742. switch (reflectionTexture.coordinatesMode) {
  41743. case BABYLON.Texture.CUBIC_MODE:
  41744. case BABYLON.Texture.INVCUBIC_MODE:
  41745. defines.REFLECTIONMAP_CUBIC = true;
  41746. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41747. break;
  41748. case BABYLON.Texture.EXPLICIT_MODE:
  41749. defines.REFLECTIONMAP_EXPLICIT = true;
  41750. break;
  41751. case BABYLON.Texture.PLANAR_MODE:
  41752. defines.REFLECTIONMAP_PLANAR = true;
  41753. break;
  41754. case BABYLON.Texture.PROJECTION_MODE:
  41755. defines.REFLECTIONMAP_PROJECTION = true;
  41756. break;
  41757. case BABYLON.Texture.SKYBOX_MODE:
  41758. defines.REFLECTIONMAP_SKYBOX = true;
  41759. break;
  41760. case BABYLON.Texture.SPHERICAL_MODE:
  41761. defines.REFLECTIONMAP_SPHERICAL = true;
  41762. break;
  41763. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41764. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41765. break;
  41766. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41767. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41768. break;
  41769. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41770. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41771. break;
  41772. }
  41773. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41774. if (reflectionTexture.sphericalPolynomial) {
  41775. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41776. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41777. defines.USESPHERICALINVERTEX = false;
  41778. }
  41779. else {
  41780. defines.USESPHERICALINVERTEX = true;
  41781. }
  41782. }
  41783. }
  41784. }
  41785. else {
  41786. defines.REFLECTION = false;
  41787. defines.REFLECTIONMAP_3D = false;
  41788. defines.REFLECTIONMAP_SPHERICAL = false;
  41789. defines.REFLECTIONMAP_PLANAR = false;
  41790. defines.REFLECTIONMAP_CUBIC = false;
  41791. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41792. defines.REFLECTIONMAP_PROJECTION = false;
  41793. defines.REFLECTIONMAP_SKYBOX = false;
  41794. defines.REFLECTIONMAP_EXPLICIT = false;
  41795. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41796. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41797. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41798. defines.INVERTCUBICMAP = false;
  41799. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41800. defines.USESPHERICALINVERTEX = false;
  41801. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41802. defines.LODINREFLECTIONALPHA = false;
  41803. defines.GAMMAREFLECTION = false;
  41804. }
  41805. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41806. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41807. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41808. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41809. }
  41810. else {
  41811. defines.LIGHTMAP = false;
  41812. }
  41813. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41814. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41815. }
  41816. else {
  41817. defines.EMISSIVE = false;
  41818. }
  41819. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41820. if (this._metallicTexture) {
  41821. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41822. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41823. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41824. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41825. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41826. }
  41827. else if (this._reflectivityTexture) {
  41828. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41829. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41830. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41831. }
  41832. else {
  41833. defines.REFLECTIVITY = false;
  41834. }
  41835. if (this._microSurfaceTexture) {
  41836. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41837. }
  41838. else {
  41839. defines.MICROSURFACEMAP = false;
  41840. }
  41841. }
  41842. else {
  41843. defines.REFLECTIVITY = false;
  41844. defines.MICROSURFACEMAP = false;
  41845. }
  41846. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41847. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41848. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41849. defines.PARALLAX = true;
  41850. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41851. }
  41852. else {
  41853. defines.PARALLAX = false;
  41854. }
  41855. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41856. }
  41857. else {
  41858. defines.BUMP = false;
  41859. }
  41860. var refractionTexture = this._getRefractionTexture();
  41861. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41862. defines.REFRACTION = true;
  41863. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41864. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41865. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41866. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41867. if (this._linkRefractionWithTransparency) {
  41868. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41869. }
  41870. }
  41871. else {
  41872. defines.REFRACTION = false;
  41873. }
  41874. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41875. defines.ENVIRONMENTBRDF = true;
  41876. }
  41877. else {
  41878. defines.ENVIRONMENTBRDF = false;
  41879. }
  41880. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41881. defines.ALPHAFROMALBEDO = true;
  41882. }
  41883. else {
  41884. defines.ALPHAFROMALBEDO = false;
  41885. }
  41886. }
  41887. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41888. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41889. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41890. if (!this.backFaceCulling && this._twoSidedLighting) {
  41891. defines.TWOSIDEDLIGHTING = true;
  41892. }
  41893. else {
  41894. defines.TWOSIDEDLIGHTING = false;
  41895. }
  41896. defines.ALPHATESTVALUE = this._alphaCutOff;
  41897. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41898. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41899. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41900. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41901. }
  41902. if (defines._areImageProcessingDirty) {
  41903. this._imageProcessingConfiguration.prepareDefines(defines);
  41904. }
  41905. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41906. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41907. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41908. // Misc.
  41909. if (defines._areMiscDirty) {
  41910. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41911. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41912. }
  41913. // Values that need to be evaluated on every frame
  41914. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41915. // Attribs
  41916. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41917. };
  41918. /**
  41919. * Force shader compilation
  41920. */
  41921. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41922. var _this = this;
  41923. var localOptions = __assign({ clipPlane: false }, options);
  41924. var defines = new PBRMaterialDefines();
  41925. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41926. if (effect.isReady()) {
  41927. if (onCompiled) {
  41928. onCompiled(this);
  41929. }
  41930. }
  41931. else {
  41932. effect.onCompileObservable.add(function () {
  41933. if (onCompiled) {
  41934. onCompiled(_this);
  41935. }
  41936. });
  41937. }
  41938. };
  41939. /**
  41940. * Initializes the uniform buffer layout for the shader.
  41941. */
  41942. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41943. // Order is important !
  41944. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41945. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41946. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41947. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41948. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41949. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41950. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41951. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41952. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41953. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41954. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41955. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41956. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41957. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41958. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41959. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41960. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41961. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41962. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41963. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41964. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41965. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41966. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41967. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41968. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41969. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41970. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41971. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41972. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41973. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41974. this._uniformBuffer.addUniform("pointSize", 1);
  41975. this._uniformBuffer.create();
  41976. };
  41977. /**
  41978. * Unbinds the textures.
  41979. */
  41980. PBRBaseMaterial.prototype.unbind = function () {
  41981. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41982. this._uniformBuffer.setTexture("reflectionSampler", null);
  41983. }
  41984. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41985. this._uniformBuffer.setTexture("refractionSampler", null);
  41986. }
  41987. _super.prototype.unbind.call(this);
  41988. };
  41989. /**
  41990. * Binds the submesh data.
  41991. * @param world - The world matrix.
  41992. * @param mesh - The BJS mesh.
  41993. * @param subMesh - A submesh of the BJS mesh.
  41994. */
  41995. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41996. var scene = this.getScene();
  41997. var defines = subMesh._materialDefines;
  41998. if (!defines) {
  41999. return;
  42000. }
  42001. var effect = subMesh.effect;
  42002. if (!effect) {
  42003. return;
  42004. }
  42005. this._activeEffect = effect;
  42006. // Matrices
  42007. this.bindOnlyWorldMatrix(world);
  42008. // Normal Matrix
  42009. if (defines.OBJECTSPACE_NORMALMAP) {
  42010. world.toNormalMatrix(this._normalMatrix);
  42011. this.bindOnlyNormalMatrix(this._normalMatrix);
  42012. }
  42013. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42014. // Bones
  42015. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  42016. var reflectionTexture = null;
  42017. if (mustRebind) {
  42018. this._uniformBuffer.bindToEffect(effect, "Material");
  42019. this.bindViewProjection(effect);
  42020. reflectionTexture = this._getReflectionTexture();
  42021. var refractionTexture = this._getRefractionTexture();
  42022. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42023. // Texture uniforms
  42024. if (scene.texturesEnabled) {
  42025. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42026. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  42027. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  42028. }
  42029. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42030. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  42031. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42032. }
  42033. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42034. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42035. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42036. }
  42037. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42038. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  42039. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  42040. if (reflectionTexture.boundingBoxSize) {
  42041. var cubeTexture = reflectionTexture;
  42042. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42043. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42044. }
  42045. var polynomials = reflectionTexture.sphericalPolynomial;
  42046. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  42047. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  42048. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  42049. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  42050. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  42051. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  42052. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  42053. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  42054. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  42055. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  42056. }
  42057. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  42058. }
  42059. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42060. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42061. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42062. }
  42063. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42064. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42065. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42066. }
  42067. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42068. if (this._metallicTexture) {
  42069. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42070. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42071. }
  42072. else if (this._reflectivityTexture) {
  42073. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42074. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42075. }
  42076. if (this._microSurfaceTexture) {
  42077. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42078. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42079. }
  42080. }
  42081. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42082. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42083. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42084. if (scene._mirroredCameraPosition) {
  42085. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42086. }
  42087. else {
  42088. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42089. }
  42090. }
  42091. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42092. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42093. var depth = 1.0;
  42094. if (!refractionTexture.isCube) {
  42095. if (refractionTexture.depth) {
  42096. depth = refractionTexture.depth;
  42097. }
  42098. }
  42099. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42100. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42101. }
  42102. }
  42103. // Point size
  42104. if (this.pointsCloud) {
  42105. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42106. }
  42107. // Colors
  42108. if (defines.METALLICWORKFLOW) {
  42109. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42110. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42111. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42112. }
  42113. else {
  42114. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42115. }
  42116. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42117. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42118. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42119. // Misc
  42120. this._lightingInfos.x = this._directIntensity;
  42121. this._lightingInfos.y = this._emissiveIntensity;
  42122. this._lightingInfos.z = this._environmentIntensity;
  42123. this._lightingInfos.w = this._specularIntensity;
  42124. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42125. }
  42126. // Textures
  42127. if (scene.texturesEnabled) {
  42128. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42129. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42130. }
  42131. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42132. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42133. }
  42134. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42135. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42136. }
  42137. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42138. if (defines.LODBASEDMICROSFURACE) {
  42139. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42140. }
  42141. else {
  42142. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42143. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42144. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42145. }
  42146. }
  42147. if (defines.ENVIRONMENTBRDF) {
  42148. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42149. }
  42150. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42151. if (defines.LODBASEDMICROSFURACE) {
  42152. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42153. }
  42154. else {
  42155. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42156. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42157. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42158. }
  42159. }
  42160. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42161. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42162. }
  42163. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42164. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42165. }
  42166. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42167. if (this._metallicTexture) {
  42168. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42169. }
  42170. else if (this._reflectivityTexture) {
  42171. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42172. }
  42173. if (this._microSurfaceTexture) {
  42174. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42175. }
  42176. }
  42177. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42178. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42179. }
  42180. }
  42181. // Clip plane
  42182. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42183. // Colors
  42184. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42185. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42186. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42187. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42188. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42189. }
  42190. if (mustRebind || !this.isFrozen) {
  42191. // Lights
  42192. if (scene.lightsEnabled && !this._disableLighting) {
  42193. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42194. }
  42195. // View
  42196. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42197. this.bindView(effect);
  42198. }
  42199. // Fog
  42200. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42201. // Morph targets
  42202. if (defines.NUM_MORPH_INFLUENCERS) {
  42203. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42204. }
  42205. // image processing
  42206. this._imageProcessingConfiguration.bind(this._activeEffect);
  42207. // Log. depth
  42208. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42209. }
  42210. this._uniformBuffer.update();
  42211. this._afterBind(mesh);
  42212. };
  42213. /**
  42214. * Returns the animatable textures.
  42215. * @returns - Array of animatable textures.
  42216. */
  42217. PBRBaseMaterial.prototype.getAnimatables = function () {
  42218. var results = [];
  42219. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42220. results.push(this._albedoTexture);
  42221. }
  42222. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42223. results.push(this._ambientTexture);
  42224. }
  42225. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42226. results.push(this._opacityTexture);
  42227. }
  42228. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42229. results.push(this._reflectionTexture);
  42230. }
  42231. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42232. results.push(this._emissiveTexture);
  42233. }
  42234. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42235. results.push(this._metallicTexture);
  42236. }
  42237. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42238. results.push(this._reflectivityTexture);
  42239. }
  42240. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42241. results.push(this._bumpTexture);
  42242. }
  42243. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42244. results.push(this._lightmapTexture);
  42245. }
  42246. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42247. results.push(this._refractionTexture);
  42248. }
  42249. return results;
  42250. };
  42251. /**
  42252. * Returns the texture used for reflections.
  42253. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42254. */
  42255. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42256. if (this._reflectionTexture) {
  42257. return this._reflectionTexture;
  42258. }
  42259. return this.getScene().environmentTexture;
  42260. };
  42261. /**
  42262. * Returns the texture used for refraction or null if none is used.
  42263. * @returns - Refection texture if present. If no refraction texture and refraction
  42264. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42265. */
  42266. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42267. if (this._refractionTexture) {
  42268. return this._refractionTexture;
  42269. }
  42270. if (this._linkRefractionWithTransparency) {
  42271. return this.getScene().environmentTexture;
  42272. }
  42273. return null;
  42274. };
  42275. /**
  42276. * Disposes the resources of the material.
  42277. * @param forceDisposeEffect - Forces the disposal of effects.
  42278. * @param forceDisposeTextures - Forces the disposal of all textures.
  42279. */
  42280. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42281. if (forceDisposeTextures) {
  42282. if (this._albedoTexture) {
  42283. this._albedoTexture.dispose();
  42284. }
  42285. if (this._ambientTexture) {
  42286. this._ambientTexture.dispose();
  42287. }
  42288. if (this._opacityTexture) {
  42289. this._opacityTexture.dispose();
  42290. }
  42291. if (this._reflectionTexture) {
  42292. this._reflectionTexture.dispose();
  42293. }
  42294. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42295. this._environmentBRDFTexture.dispose();
  42296. }
  42297. if (this._emissiveTexture) {
  42298. this._emissiveTexture.dispose();
  42299. }
  42300. if (this._metallicTexture) {
  42301. this._metallicTexture.dispose();
  42302. }
  42303. if (this._reflectivityTexture) {
  42304. this._reflectivityTexture.dispose();
  42305. }
  42306. if (this._bumpTexture) {
  42307. this._bumpTexture.dispose();
  42308. }
  42309. if (this._lightmapTexture) {
  42310. this._lightmapTexture.dispose();
  42311. }
  42312. if (this._refractionTexture) {
  42313. this._refractionTexture.dispose();
  42314. }
  42315. }
  42316. this._renderTargets.dispose();
  42317. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42318. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42319. }
  42320. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42321. };
  42322. /**
  42323. * Stores the reflectivity values based on metallic roughness workflow.
  42324. */
  42325. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42326. __decorate([
  42327. BABYLON.serializeAsImageProcessingConfiguration()
  42328. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42329. __decorate([
  42330. BABYLON.serialize()
  42331. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42332. __decorate([
  42333. BABYLON.serialize()
  42334. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42335. return PBRBaseMaterial;
  42336. }(BABYLON.PushMaterial));
  42337. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42338. })(BABYLON || (BABYLON = {}));
  42339. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42340. "use strict";
  42341. var BABYLON;
  42342. (function (BABYLON) {
  42343. /**
  42344. * The Physically based simple base material of BJS.
  42345. *
  42346. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42347. * It is used as the base class for both the specGloss and metalRough conventions.
  42348. */
  42349. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42350. __extends(PBRBaseSimpleMaterial, _super);
  42351. /**
  42352. * Instantiates a new PBRMaterial instance.
  42353. *
  42354. * @param name The material name
  42355. * @param scene The scene the material will be use in.
  42356. */
  42357. function PBRBaseSimpleMaterial(name, scene) {
  42358. var _this = _super.call(this, name, scene) || this;
  42359. /**
  42360. * Number of Simultaneous lights allowed on the material.
  42361. */
  42362. _this.maxSimultaneousLights = 4;
  42363. /**
  42364. * If sets to true, disables all the lights affecting the material.
  42365. */
  42366. _this.disableLighting = false;
  42367. /**
  42368. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42369. */
  42370. _this.invertNormalMapX = false;
  42371. /**
  42372. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42373. */
  42374. _this.invertNormalMapY = false;
  42375. /**
  42376. * Emissivie color used to self-illuminate the model.
  42377. */
  42378. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42379. /**
  42380. * Occlusion Channel Strenght.
  42381. */
  42382. _this.occlusionStrength = 1.0;
  42383. _this.useLightmapAsShadowmap = false;
  42384. _this._useAlphaFromAlbedoTexture = true;
  42385. _this._useAmbientInGrayScale = true;
  42386. return _this;
  42387. }
  42388. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42389. /**
  42390. * Gets the current double sided mode.
  42391. */
  42392. get: function () {
  42393. return this._twoSidedLighting;
  42394. },
  42395. /**
  42396. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42397. */
  42398. set: function (value) {
  42399. if (this._twoSidedLighting === value) {
  42400. return;
  42401. }
  42402. this._twoSidedLighting = value;
  42403. this.backFaceCulling = !value;
  42404. this._markAllSubMeshesAsTexturesDirty();
  42405. },
  42406. enumerable: true,
  42407. configurable: true
  42408. });
  42409. /**
  42410. * Return the active textures of the material.
  42411. */
  42412. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42413. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42414. if (this.environmentTexture) {
  42415. activeTextures.push(this.environmentTexture);
  42416. }
  42417. if (this.normalTexture) {
  42418. activeTextures.push(this.normalTexture);
  42419. }
  42420. if (this.emissiveTexture) {
  42421. activeTextures.push(this.emissiveTexture);
  42422. }
  42423. if (this.occlusionTexture) {
  42424. activeTextures.push(this.occlusionTexture);
  42425. }
  42426. if (this.lightmapTexture) {
  42427. activeTextures.push(this.lightmapTexture);
  42428. }
  42429. return activeTextures;
  42430. };
  42431. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42432. if (_super.prototype.hasTexture.call(this, texture)) {
  42433. return true;
  42434. }
  42435. if (this.lightmapTexture === texture) {
  42436. return true;
  42437. }
  42438. return false;
  42439. };
  42440. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42441. return "PBRBaseSimpleMaterial";
  42442. };
  42443. __decorate([
  42444. BABYLON.serialize(),
  42445. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42446. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42447. __decorate([
  42448. BABYLON.serialize(),
  42449. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42450. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42451. __decorate([
  42452. BABYLON.serializeAsTexture(),
  42453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42454. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42455. __decorate([
  42456. BABYLON.serialize(),
  42457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42458. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42459. __decorate([
  42460. BABYLON.serialize(),
  42461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42462. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42463. __decorate([
  42464. BABYLON.serializeAsTexture(),
  42465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42466. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42467. __decorate([
  42468. BABYLON.serializeAsColor3("emissive"),
  42469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42470. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42471. __decorate([
  42472. BABYLON.serializeAsTexture(),
  42473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42474. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42475. __decorate([
  42476. BABYLON.serialize(),
  42477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42478. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42479. __decorate([
  42480. BABYLON.serializeAsTexture(),
  42481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42482. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42483. __decorate([
  42484. BABYLON.serialize(),
  42485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42486. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42487. __decorate([
  42488. BABYLON.serialize()
  42489. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42490. __decorate([
  42491. BABYLON.serializeAsTexture(),
  42492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42493. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42494. __decorate([
  42495. BABYLON.serialize(),
  42496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42497. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42498. return PBRBaseSimpleMaterial;
  42499. }(BABYLON.PBRBaseMaterial));
  42500. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42501. })(BABYLON || (BABYLON = {}));
  42502. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42503. "use strict";
  42504. var BABYLON;
  42505. (function (BABYLON) {
  42506. /**
  42507. * The Physically based material of BJS.
  42508. *
  42509. * This offers the main features of a standard PBR material.
  42510. * For more information, please refer to the documentation :
  42511. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42512. */
  42513. var PBRMaterial = /** @class */ (function (_super) {
  42514. __extends(PBRMaterial, _super);
  42515. /**
  42516. * Instantiates a new PBRMaterial instance.
  42517. *
  42518. * @param name The material name
  42519. * @param scene The scene the material will be use in.
  42520. */
  42521. function PBRMaterial(name, scene) {
  42522. var _this = _super.call(this, name, scene) || this;
  42523. /**
  42524. * Intensity of the direct lights e.g. the four lights available in your scene.
  42525. * This impacts both the direct diffuse and specular highlights.
  42526. */
  42527. _this.directIntensity = 1.0;
  42528. /**
  42529. * Intensity of the emissive part of the material.
  42530. * This helps controlling the emissive effect without modifying the emissive color.
  42531. */
  42532. _this.emissiveIntensity = 1.0;
  42533. /**
  42534. * Intensity of the environment e.g. how much the environment will light the object
  42535. * either through harmonics for rough material or through the refelction for shiny ones.
  42536. */
  42537. _this.environmentIntensity = 1.0;
  42538. /**
  42539. * This is a special control allowing the reduction of the specular highlights coming from the
  42540. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42541. */
  42542. _this.specularIntensity = 1.0;
  42543. /**
  42544. * Debug Control allowing disabling the bump map on this material.
  42545. */
  42546. _this.disableBumpMap = false;
  42547. /**
  42548. * AKA Occlusion Texture Intensity in other nomenclature.
  42549. */
  42550. _this.ambientTextureStrength = 1.0;
  42551. /**
  42552. * The color of a material in ambient lighting.
  42553. */
  42554. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42555. /**
  42556. * AKA Diffuse Color in other nomenclature.
  42557. */
  42558. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42559. /**
  42560. * AKA Specular Color in other nomenclature.
  42561. */
  42562. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42563. /**
  42564. * The color reflected from the material.
  42565. */
  42566. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42567. /**
  42568. * The color emitted from the material.
  42569. */
  42570. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42571. /**
  42572. * AKA Glossiness in other nomenclature.
  42573. */
  42574. _this.microSurface = 1.0;
  42575. /**
  42576. * source material index of refraction (IOR)' / 'destination material IOR.
  42577. */
  42578. _this.indexOfRefraction = 0.66;
  42579. /**
  42580. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42581. */
  42582. _this.invertRefractionY = false;
  42583. /**
  42584. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42585. * Materials half opaque for instance using refraction could benefit from this control.
  42586. */
  42587. _this.linkRefractionWithTransparency = false;
  42588. _this.useLightmapAsShadowmap = false;
  42589. /**
  42590. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42591. */
  42592. _this.useAlphaFromAlbedoTexture = false;
  42593. /**
  42594. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42595. */
  42596. _this.forceAlphaTest = false;
  42597. /**
  42598. * Defines the alpha limits in alpha test mode.
  42599. */
  42600. _this.alphaCutOff = 0.4;
  42601. /**
  42602. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42603. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42604. */
  42605. _this.useSpecularOverAlpha = true;
  42606. /**
  42607. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42608. */
  42609. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42610. /**
  42611. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42612. */
  42613. _this.useRoughnessFromMetallicTextureAlpha = true;
  42614. /**
  42615. * Specifies if the metallic texture contains the roughness information in its green channel.
  42616. */
  42617. _this.useRoughnessFromMetallicTextureGreen = false;
  42618. /**
  42619. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42620. */
  42621. _this.useMetallnessFromMetallicTextureBlue = false;
  42622. /**
  42623. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42624. */
  42625. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42626. /**
  42627. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42628. */
  42629. _this.useAmbientInGrayScale = false;
  42630. /**
  42631. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42632. * The material will try to infer what glossiness each pixel should be.
  42633. */
  42634. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42635. /**
  42636. * BJS is using an harcoded light falloff based on a manually sets up range.
  42637. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42638. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42639. */
  42640. _this.usePhysicalLightFalloff = true;
  42641. /**
  42642. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42643. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42644. */
  42645. _this.useRadianceOverAlpha = true;
  42646. /**
  42647. * Allows using an object space normal map (instead of tangent space).
  42648. */
  42649. _this.useObjectSpaceNormalMap = false;
  42650. /**
  42651. * Allows using the bump map in parallax mode.
  42652. */
  42653. _this.useParallax = false;
  42654. /**
  42655. * Allows using the bump map in parallax occlusion mode.
  42656. */
  42657. _this.useParallaxOcclusion = false;
  42658. /**
  42659. * Controls the scale bias of the parallax mode.
  42660. */
  42661. _this.parallaxScaleBias = 0.05;
  42662. /**
  42663. * If sets to true, disables all the lights affecting the material.
  42664. */
  42665. _this.disableLighting = false;
  42666. /**
  42667. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42668. */
  42669. _this.forceIrradianceInFragment = false;
  42670. /**
  42671. * Number of Simultaneous lights allowed on the material.
  42672. */
  42673. _this.maxSimultaneousLights = 4;
  42674. /**
  42675. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42676. */
  42677. _this.invertNormalMapX = false;
  42678. /**
  42679. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42680. */
  42681. _this.invertNormalMapY = false;
  42682. /**
  42683. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42684. */
  42685. _this.twoSidedLighting = false;
  42686. /**
  42687. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42688. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42689. */
  42690. _this.useAlphaFresnel = false;
  42691. /**
  42692. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42693. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42694. */
  42695. _this.useLinearAlphaFresnel = false;
  42696. /**
  42697. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42698. * And/Or occlude the blended part.
  42699. */
  42700. _this.environmentBRDFTexture = null;
  42701. /**
  42702. * Force normal to face away from face.
  42703. */
  42704. _this.forceNormalForward = false;
  42705. /**
  42706. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42707. * makes the reflect vector face the model (under horizon).
  42708. */
  42709. _this.useHorizonOcclusion = true;
  42710. /**
  42711. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42712. * too much the area relying on ambient texture to define their ambient occlusion.
  42713. */
  42714. _this.useRadianceOcclusion = true;
  42715. /**
  42716. * If set to true, no lighting calculations will be applied.
  42717. */
  42718. _this.unlit = false;
  42719. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42720. return _this;
  42721. }
  42722. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42723. /**
  42724. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42725. */
  42726. get: function () {
  42727. return this._PBRMATERIAL_OPAQUE;
  42728. },
  42729. enumerable: true,
  42730. configurable: true
  42731. });
  42732. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42733. /**
  42734. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42735. */
  42736. get: function () {
  42737. return this._PBRMATERIAL_ALPHATEST;
  42738. },
  42739. enumerable: true,
  42740. configurable: true
  42741. });
  42742. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42743. /**
  42744. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42745. */
  42746. get: function () {
  42747. return this._PBRMATERIAL_ALPHABLEND;
  42748. },
  42749. enumerable: true,
  42750. configurable: true
  42751. });
  42752. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42753. /**
  42754. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42755. * They are also discarded below the alpha cutoff threshold to improve performances.
  42756. */
  42757. get: function () {
  42758. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42759. },
  42760. enumerable: true,
  42761. configurable: true
  42762. });
  42763. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42764. /**
  42765. * Gets the image processing configuration used either in this material.
  42766. */
  42767. get: function () {
  42768. return this._imageProcessingConfiguration;
  42769. },
  42770. /**
  42771. * Sets the Default image processing configuration used either in the this material.
  42772. *
  42773. * If sets to null, the scene one is in use.
  42774. */
  42775. set: function (value) {
  42776. this._attachImageProcessingConfiguration(value);
  42777. // Ensure the effect will be rebuilt.
  42778. this._markAllSubMeshesAsTexturesDirty();
  42779. },
  42780. enumerable: true,
  42781. configurable: true
  42782. });
  42783. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42784. /**
  42785. * Gets wether the color curves effect is enabled.
  42786. */
  42787. get: function () {
  42788. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42789. },
  42790. /**
  42791. * Sets wether the color curves effect is enabled.
  42792. */
  42793. set: function (value) {
  42794. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42795. },
  42796. enumerable: true,
  42797. configurable: true
  42798. });
  42799. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42800. /**
  42801. * Gets wether the color grading effect is enabled.
  42802. */
  42803. get: function () {
  42804. return this.imageProcessingConfiguration.colorGradingEnabled;
  42805. },
  42806. /**
  42807. * Gets wether the color grading effect is enabled.
  42808. */
  42809. set: function (value) {
  42810. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42811. },
  42812. enumerable: true,
  42813. configurable: true
  42814. });
  42815. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42816. /**
  42817. * Gets wether tonemapping is enabled or not.
  42818. */
  42819. get: function () {
  42820. return this._imageProcessingConfiguration.toneMappingEnabled;
  42821. },
  42822. /**
  42823. * Sets wether tonemapping is enabled or not
  42824. */
  42825. set: function (value) {
  42826. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42827. },
  42828. enumerable: true,
  42829. configurable: true
  42830. });
  42831. ;
  42832. ;
  42833. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42834. /**
  42835. * The camera exposure used on this material.
  42836. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42837. * This corresponds to a photographic exposure.
  42838. */
  42839. get: function () {
  42840. return this._imageProcessingConfiguration.exposure;
  42841. },
  42842. /**
  42843. * The camera exposure used on this material.
  42844. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42845. * This corresponds to a photographic exposure.
  42846. */
  42847. set: function (value) {
  42848. this._imageProcessingConfiguration.exposure = value;
  42849. },
  42850. enumerable: true,
  42851. configurable: true
  42852. });
  42853. ;
  42854. ;
  42855. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42856. /**
  42857. * Gets The camera contrast used on this material.
  42858. */
  42859. get: function () {
  42860. return this._imageProcessingConfiguration.contrast;
  42861. },
  42862. /**
  42863. * Sets The camera contrast used on this material.
  42864. */
  42865. set: function (value) {
  42866. this._imageProcessingConfiguration.contrast = value;
  42867. },
  42868. enumerable: true,
  42869. configurable: true
  42870. });
  42871. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42872. /**
  42873. * Gets the Color Grading 2D Lookup Texture.
  42874. */
  42875. get: function () {
  42876. return this._imageProcessingConfiguration.colorGradingTexture;
  42877. },
  42878. /**
  42879. * Sets the Color Grading 2D Lookup Texture.
  42880. */
  42881. set: function (value) {
  42882. this._imageProcessingConfiguration.colorGradingTexture = value;
  42883. },
  42884. enumerable: true,
  42885. configurable: true
  42886. });
  42887. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42888. /**
  42889. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42890. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42891. * 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;
  42892. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42893. */
  42894. get: function () {
  42895. return this._imageProcessingConfiguration.colorCurves;
  42896. },
  42897. /**
  42898. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42899. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42900. * 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;
  42901. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42902. */
  42903. set: function (value) {
  42904. this._imageProcessingConfiguration.colorCurves = value;
  42905. },
  42906. enumerable: true,
  42907. configurable: true
  42908. });
  42909. /**
  42910. * Returns the name of this material class.
  42911. */
  42912. PBRMaterial.prototype.getClassName = function () {
  42913. return "PBRMaterial";
  42914. };
  42915. /**
  42916. * Returns an array of the actively used textures.
  42917. * @returns - Array of BaseTextures
  42918. */
  42919. PBRMaterial.prototype.getActiveTextures = function () {
  42920. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42921. if (this._albedoTexture) {
  42922. activeTextures.push(this._albedoTexture);
  42923. }
  42924. if (this._ambientTexture) {
  42925. activeTextures.push(this._ambientTexture);
  42926. }
  42927. if (this._opacityTexture) {
  42928. activeTextures.push(this._opacityTexture);
  42929. }
  42930. if (this._reflectionTexture) {
  42931. activeTextures.push(this._reflectionTexture);
  42932. }
  42933. if (this._emissiveTexture) {
  42934. activeTextures.push(this._emissiveTexture);
  42935. }
  42936. if (this._reflectivityTexture) {
  42937. activeTextures.push(this._reflectivityTexture);
  42938. }
  42939. if (this._metallicTexture) {
  42940. activeTextures.push(this._metallicTexture);
  42941. }
  42942. if (this._microSurfaceTexture) {
  42943. activeTextures.push(this._microSurfaceTexture);
  42944. }
  42945. if (this._bumpTexture) {
  42946. activeTextures.push(this._bumpTexture);
  42947. }
  42948. if (this._lightmapTexture) {
  42949. activeTextures.push(this._lightmapTexture);
  42950. }
  42951. if (this._refractionTexture) {
  42952. activeTextures.push(this._refractionTexture);
  42953. }
  42954. return activeTextures;
  42955. };
  42956. /**
  42957. * Checks to see if a texture is used in the material.
  42958. * @param texture - Base texture to use.
  42959. * @returns - Boolean specifying if a texture is used in the material.
  42960. */
  42961. PBRMaterial.prototype.hasTexture = function (texture) {
  42962. if (_super.prototype.hasTexture.call(this, texture)) {
  42963. return true;
  42964. }
  42965. if (this._albedoTexture === texture) {
  42966. return true;
  42967. }
  42968. if (this._ambientTexture === texture) {
  42969. return true;
  42970. }
  42971. if (this._opacityTexture === texture) {
  42972. return true;
  42973. }
  42974. if (this._reflectionTexture === texture) {
  42975. return true;
  42976. }
  42977. if (this._reflectivityTexture === texture) {
  42978. return true;
  42979. }
  42980. if (this._metallicTexture === texture) {
  42981. return true;
  42982. }
  42983. if (this._microSurfaceTexture === texture) {
  42984. return true;
  42985. }
  42986. if (this._bumpTexture === texture) {
  42987. return true;
  42988. }
  42989. if (this._lightmapTexture === texture) {
  42990. return true;
  42991. }
  42992. if (this._refractionTexture === texture) {
  42993. return true;
  42994. }
  42995. return false;
  42996. };
  42997. /**
  42998. * Makes a duplicate of the current material.
  42999. * @param name - name to use for the new material.
  43000. */
  43001. PBRMaterial.prototype.clone = function (name) {
  43002. var _this = this;
  43003. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  43004. clone.id = name;
  43005. clone.name = name;
  43006. return clone;
  43007. };
  43008. /**
  43009. * Serializes this PBR Material.
  43010. * @returns - An object with the serialized material.
  43011. */
  43012. PBRMaterial.prototype.serialize = function () {
  43013. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43014. serializationObject.customType = "BABYLON.PBRMaterial";
  43015. return serializationObject;
  43016. };
  43017. // Statics
  43018. /**
  43019. * Parses a PBR Material from a serialized object.
  43020. * @param source - Serialized object.
  43021. * @param scene - BJS scene instance.
  43022. * @param rootUrl - url for the scene object
  43023. * @returns - PBRMaterial
  43024. */
  43025. PBRMaterial.Parse = function (source, scene, rootUrl) {
  43026. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  43027. };
  43028. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  43029. /**
  43030. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  43031. */
  43032. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  43033. /**
  43034. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43035. */
  43036. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  43037. /**
  43038. * 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.
  43039. * They are also discarded below the alpha cutoff threshold to improve performances.
  43040. */
  43041. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  43042. __decorate([
  43043. BABYLON.serialize(),
  43044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43045. ], PBRMaterial.prototype, "directIntensity", void 0);
  43046. __decorate([
  43047. BABYLON.serialize(),
  43048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43049. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  43050. __decorate([
  43051. BABYLON.serialize(),
  43052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43053. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  43054. __decorate([
  43055. BABYLON.serialize(),
  43056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43057. ], PBRMaterial.prototype, "specularIntensity", void 0);
  43058. __decorate([
  43059. BABYLON.serialize(),
  43060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43061. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43062. __decorate([
  43063. BABYLON.serializeAsTexture(),
  43064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43065. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43066. __decorate([
  43067. BABYLON.serializeAsTexture(),
  43068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43069. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43070. __decorate([
  43071. BABYLON.serialize(),
  43072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43073. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43074. __decorate([
  43075. BABYLON.serializeAsTexture(),
  43076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43077. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43078. __decorate([
  43079. BABYLON.serializeAsTexture(),
  43080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43081. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43082. __decorate([
  43083. BABYLON.serializeAsTexture(),
  43084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43085. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43086. __decorate([
  43087. BABYLON.serializeAsTexture(),
  43088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43089. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43090. __decorate([
  43091. BABYLON.serializeAsTexture(),
  43092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43093. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43094. __decorate([
  43095. BABYLON.serialize(),
  43096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43097. ], PBRMaterial.prototype, "metallic", void 0);
  43098. __decorate([
  43099. BABYLON.serialize(),
  43100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43101. ], PBRMaterial.prototype, "roughness", void 0);
  43102. __decorate([
  43103. BABYLON.serializeAsTexture(),
  43104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43105. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43106. __decorate([
  43107. BABYLON.serializeAsTexture(),
  43108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43109. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43110. __decorate([
  43111. BABYLON.serializeAsTexture(),
  43112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43113. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43114. __decorate([
  43115. BABYLON.serializeAsTexture(),
  43116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43117. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43118. __decorate([
  43119. BABYLON.serializeAsColor3("ambient"),
  43120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43121. ], PBRMaterial.prototype, "ambientColor", void 0);
  43122. __decorate([
  43123. BABYLON.serializeAsColor3("albedo"),
  43124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43125. ], PBRMaterial.prototype, "albedoColor", void 0);
  43126. __decorate([
  43127. BABYLON.serializeAsColor3("reflectivity"),
  43128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43129. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43130. __decorate([
  43131. BABYLON.serializeAsColor3("reflection"),
  43132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43133. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43134. __decorate([
  43135. BABYLON.serializeAsColor3("emissive"),
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43137. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43138. __decorate([
  43139. BABYLON.serialize(),
  43140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43141. ], PBRMaterial.prototype, "microSurface", void 0);
  43142. __decorate([
  43143. BABYLON.serialize(),
  43144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43145. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43146. __decorate([
  43147. BABYLON.serialize(),
  43148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43149. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43150. __decorate([
  43151. BABYLON.serialize(),
  43152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43153. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43154. __decorate([
  43155. BABYLON.serialize(),
  43156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43157. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43158. __decorate([
  43159. BABYLON.serialize(),
  43160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43161. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43162. __decorate([
  43163. BABYLON.serialize(),
  43164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43165. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43166. __decorate([
  43167. BABYLON.serialize(),
  43168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43169. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43170. __decorate([
  43171. BABYLON.serialize(),
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43173. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43174. __decorate([
  43175. BABYLON.serialize(),
  43176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43177. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43178. __decorate([
  43179. BABYLON.serialize(),
  43180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43181. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43182. __decorate([
  43183. BABYLON.serialize(),
  43184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43185. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43186. __decorate([
  43187. BABYLON.serialize(),
  43188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43189. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43190. __decorate([
  43191. BABYLON.serialize(),
  43192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43193. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43194. __decorate([
  43195. BABYLON.serialize(),
  43196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43197. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43198. __decorate([
  43199. BABYLON.serialize(),
  43200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43201. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43202. __decorate([
  43203. BABYLON.serialize(),
  43204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43205. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43206. __decorate([
  43207. BABYLON.serialize(),
  43208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43209. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43210. __decorate([
  43211. BABYLON.serialize(),
  43212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43213. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43214. __decorate([
  43215. BABYLON.serialize(),
  43216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43217. ], PBRMaterial.prototype, "useParallax", void 0);
  43218. __decorate([
  43219. BABYLON.serialize(),
  43220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43221. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43222. __decorate([
  43223. BABYLON.serialize(),
  43224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43225. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43226. __decorate([
  43227. BABYLON.serialize(),
  43228. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43229. ], PBRMaterial.prototype, "disableLighting", void 0);
  43230. __decorate([
  43231. BABYLON.serialize(),
  43232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43233. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43234. __decorate([
  43235. BABYLON.serialize(),
  43236. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43237. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43238. __decorate([
  43239. BABYLON.serialize(),
  43240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43241. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43242. __decorate([
  43243. BABYLON.serialize(),
  43244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43245. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43246. __decorate([
  43247. BABYLON.serialize(),
  43248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43249. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43250. __decorate([
  43251. BABYLON.serialize(),
  43252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43253. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43254. __decorate([
  43255. BABYLON.serialize(),
  43256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43257. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43258. __decorate([
  43259. BABYLON.serializeAsTexture(),
  43260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43261. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43262. __decorate([
  43263. BABYLON.serialize(),
  43264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43265. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43266. __decorate([
  43267. BABYLON.serialize(),
  43268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43269. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43270. __decorate([
  43271. BABYLON.serialize(),
  43272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43273. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43274. __decorate([
  43275. BABYLON.serialize(),
  43276. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43277. ], PBRMaterial.prototype, "unlit", void 0);
  43278. return PBRMaterial;
  43279. }(BABYLON.PBRBaseMaterial));
  43280. BABYLON.PBRMaterial = PBRMaterial;
  43281. })(BABYLON || (BABYLON = {}));
  43282. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43283. "use strict";
  43284. var BABYLON;
  43285. (function (BABYLON) {
  43286. /**
  43287. * The PBR material of BJS following the metal roughness convention.
  43288. *
  43289. * This fits to the PBR convention in the GLTF definition:
  43290. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43291. */
  43292. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43293. __extends(PBRMetallicRoughnessMaterial, _super);
  43294. /**
  43295. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43296. *
  43297. * @param name The material name
  43298. * @param scene The scene the material will be use in.
  43299. */
  43300. function PBRMetallicRoughnessMaterial(name, scene) {
  43301. var _this = _super.call(this, name, scene) || this;
  43302. _this._useRoughnessFromMetallicTextureAlpha = false;
  43303. _this._useRoughnessFromMetallicTextureGreen = true;
  43304. _this._useMetallnessFromMetallicTextureBlue = true;
  43305. _this.metallic = 1.0;
  43306. _this.roughness = 1.0;
  43307. return _this;
  43308. }
  43309. /**
  43310. * Return the currrent class name of the material.
  43311. */
  43312. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43313. return "PBRMetallicRoughnessMaterial";
  43314. };
  43315. /**
  43316. * Return the active textures of the material.
  43317. */
  43318. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43319. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43320. if (this.baseTexture) {
  43321. activeTextures.push(this.baseTexture);
  43322. }
  43323. if (this.metallicRoughnessTexture) {
  43324. activeTextures.push(this.metallicRoughnessTexture);
  43325. }
  43326. return activeTextures;
  43327. };
  43328. /**
  43329. * Checks to see if a texture is used in the material.
  43330. * @param texture - Base texture to use.
  43331. * @returns - Boolean specifying if a texture is used in the material.
  43332. */
  43333. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43334. if (_super.prototype.hasTexture.call(this, texture)) {
  43335. return true;
  43336. }
  43337. if (this.baseTexture === texture) {
  43338. return true;
  43339. }
  43340. if (this.metallicRoughnessTexture === texture) {
  43341. return true;
  43342. }
  43343. return false;
  43344. };
  43345. /**
  43346. * Makes a duplicate of the current material.
  43347. * @param name - name to use for the new material.
  43348. */
  43349. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43350. var _this = this;
  43351. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43352. clone.id = name;
  43353. clone.name = name;
  43354. return clone;
  43355. };
  43356. /**
  43357. * Serialize the material to a parsable JSON object.
  43358. */
  43359. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43360. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43361. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43362. return serializationObject;
  43363. };
  43364. /**
  43365. * Parses a JSON object correponding to the serialize function.
  43366. */
  43367. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43368. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43369. };
  43370. __decorate([
  43371. BABYLON.serializeAsColor3(),
  43372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43373. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43374. __decorate([
  43375. BABYLON.serializeAsTexture(),
  43376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43377. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43378. __decorate([
  43379. BABYLON.serialize(),
  43380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43381. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43382. __decorate([
  43383. BABYLON.serialize(),
  43384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43385. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43386. __decorate([
  43387. BABYLON.serializeAsTexture(),
  43388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43389. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43390. return PBRMetallicRoughnessMaterial;
  43391. }(BABYLON.PBRBaseSimpleMaterial));
  43392. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43393. })(BABYLON || (BABYLON = {}));
  43394. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43395. "use strict";
  43396. var BABYLON;
  43397. (function (BABYLON) {
  43398. /**
  43399. * The PBR material of BJS following the specular glossiness convention.
  43400. *
  43401. * This fits to the PBR convention in the GLTF definition:
  43402. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43403. */
  43404. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43405. __extends(PBRSpecularGlossinessMaterial, _super);
  43406. /**
  43407. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43408. *
  43409. * @param name The material name
  43410. * @param scene The scene the material will be use in.
  43411. */
  43412. function PBRSpecularGlossinessMaterial(name, scene) {
  43413. var _this = _super.call(this, name, scene) || this;
  43414. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43415. return _this;
  43416. }
  43417. /**
  43418. * Return the currrent class name of the material.
  43419. */
  43420. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43421. return "PBRSpecularGlossinessMaterial";
  43422. };
  43423. /**
  43424. * Return the active textures of the material.
  43425. */
  43426. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43427. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43428. if (this.diffuseTexture) {
  43429. activeTextures.push(this.diffuseTexture);
  43430. }
  43431. if (this.specularGlossinessTexture) {
  43432. activeTextures.push(this.specularGlossinessTexture);
  43433. }
  43434. return activeTextures;
  43435. };
  43436. /**
  43437. * Checks to see if a texture is used in the material.
  43438. * @param texture - Base texture to use.
  43439. * @returns - Boolean specifying if a texture is used in the material.
  43440. */
  43441. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43442. if (_super.prototype.hasTexture.call(this, texture)) {
  43443. return true;
  43444. }
  43445. if (this.diffuseTexture === texture) {
  43446. return true;
  43447. }
  43448. if (this.specularGlossinessTexture === texture) {
  43449. return true;
  43450. }
  43451. return false;
  43452. };
  43453. /**
  43454. * Makes a duplicate of the current material.
  43455. * @param name - name to use for the new material.
  43456. */
  43457. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43458. var _this = this;
  43459. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43460. clone.id = name;
  43461. clone.name = name;
  43462. return clone;
  43463. };
  43464. /**
  43465. * Serialize the material to a parsable JSON object.
  43466. */
  43467. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43468. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43469. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43470. return serializationObject;
  43471. };
  43472. /**
  43473. * Parses a JSON object correponding to the serialize function.
  43474. */
  43475. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43476. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43477. };
  43478. __decorate([
  43479. BABYLON.serializeAsColor3("diffuse"),
  43480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43481. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43482. __decorate([
  43483. BABYLON.serializeAsTexture(),
  43484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43485. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43486. __decorate([
  43487. BABYLON.serializeAsColor3("specular"),
  43488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43489. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43490. __decorate([
  43491. BABYLON.serialize(),
  43492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43493. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43494. __decorate([
  43495. BABYLON.serializeAsTexture(),
  43496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43497. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43498. return PBRSpecularGlossinessMaterial;
  43499. }(BABYLON.PBRBaseSimpleMaterial));
  43500. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43501. })(BABYLON || (BABYLON = {}));
  43502. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43503. "use strict";
  43504. var BABYLON;
  43505. (function (BABYLON) {
  43506. BABYLON.CameraInputTypes = {};
  43507. var CameraInputsManager = /** @class */ (function () {
  43508. function CameraInputsManager(camera) {
  43509. this.attached = {};
  43510. this.camera = camera;
  43511. this.checkInputs = function () { };
  43512. }
  43513. /**
  43514. * Add an input method to a camera.
  43515. * builtin inputs example: camera.inputs.addGamepad();
  43516. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43517. * @param input camera input method
  43518. */
  43519. CameraInputsManager.prototype.add = function (input) {
  43520. var type = input.getSimpleName();
  43521. if (this.attached[type]) {
  43522. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43523. return;
  43524. }
  43525. this.attached[type] = input;
  43526. input.camera = this.camera;
  43527. //for checkInputs, we are dynamically creating a function
  43528. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43529. if (input.checkInputs) {
  43530. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43531. }
  43532. if (this.attachedElement) {
  43533. input.attachControl(this.attachedElement);
  43534. }
  43535. };
  43536. /**
  43537. * Remove a specific input method from a camera
  43538. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43539. * @param inputToRemove camera input method
  43540. */
  43541. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43542. for (var cam in this.attached) {
  43543. var input = this.attached[cam];
  43544. if (input === inputToRemove) {
  43545. input.detachControl(this.attachedElement);
  43546. input.camera = null;
  43547. delete this.attached[cam];
  43548. this.rebuildInputCheck();
  43549. }
  43550. }
  43551. };
  43552. CameraInputsManager.prototype.removeByType = function (inputType) {
  43553. for (var cam in this.attached) {
  43554. var input = this.attached[cam];
  43555. if (input.getClassName() === inputType) {
  43556. input.detachControl(this.attachedElement);
  43557. input.camera = null;
  43558. delete this.attached[cam];
  43559. this.rebuildInputCheck();
  43560. }
  43561. }
  43562. };
  43563. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43564. var current = this.checkInputs;
  43565. return function () {
  43566. current();
  43567. fn();
  43568. };
  43569. };
  43570. CameraInputsManager.prototype.attachInput = function (input) {
  43571. if (this.attachedElement) {
  43572. input.attachControl(this.attachedElement, this.noPreventDefault);
  43573. }
  43574. };
  43575. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43576. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43577. if (this.attachedElement) {
  43578. return;
  43579. }
  43580. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43581. this.attachedElement = element;
  43582. this.noPreventDefault = noPreventDefault;
  43583. for (var cam in this.attached) {
  43584. this.attached[cam].attachControl(element, noPreventDefault);
  43585. }
  43586. };
  43587. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43588. if (disconnect === void 0) { disconnect = false; }
  43589. if (this.attachedElement !== element) {
  43590. return;
  43591. }
  43592. for (var cam in this.attached) {
  43593. this.attached[cam].detachControl(element);
  43594. if (disconnect) {
  43595. this.attached[cam].camera = null;
  43596. }
  43597. }
  43598. this.attachedElement = null;
  43599. };
  43600. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43601. this.checkInputs = function () { };
  43602. for (var cam in this.attached) {
  43603. var input = this.attached[cam];
  43604. if (input.checkInputs) {
  43605. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43606. }
  43607. }
  43608. };
  43609. /**
  43610. * Remove all attached input methods from a camera
  43611. */
  43612. CameraInputsManager.prototype.clear = function () {
  43613. if (this.attachedElement) {
  43614. this.detachElement(this.attachedElement, true);
  43615. }
  43616. this.attached = {};
  43617. this.attachedElement = null;
  43618. this.checkInputs = function () { };
  43619. };
  43620. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43621. var inputs = {};
  43622. for (var cam in this.attached) {
  43623. var input = this.attached[cam];
  43624. var res = BABYLON.SerializationHelper.Serialize(input);
  43625. inputs[input.getClassName()] = res;
  43626. }
  43627. serializedCamera.inputsmgr = inputs;
  43628. };
  43629. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43630. var parsedInputs = parsedCamera.inputsmgr;
  43631. if (parsedInputs) {
  43632. this.clear();
  43633. for (var n in parsedInputs) {
  43634. var construct = BABYLON.CameraInputTypes[n];
  43635. if (construct) {
  43636. var parsedinput = parsedInputs[n];
  43637. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43638. this.add(input);
  43639. }
  43640. }
  43641. }
  43642. else {
  43643. //2016-03-08 this part is for managing backward compatibility
  43644. for (var n in this.attached) {
  43645. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43646. if (construct) {
  43647. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43648. this.remove(this.attached[n]);
  43649. this.add(input);
  43650. }
  43651. }
  43652. }
  43653. };
  43654. return CameraInputsManager;
  43655. }());
  43656. BABYLON.CameraInputsManager = CameraInputsManager;
  43657. })(BABYLON || (BABYLON = {}));
  43658. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43659. "use strict";
  43660. var BABYLON;
  43661. (function (BABYLON) {
  43662. var TargetCamera = /** @class */ (function (_super) {
  43663. __extends(TargetCamera, _super);
  43664. function TargetCamera(name, position, scene) {
  43665. var _this = _super.call(this, name, position, scene) || this;
  43666. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43667. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43668. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43669. _this.speed = 2.0;
  43670. _this.noRotationConstraint = false;
  43671. _this.lockedTarget = null;
  43672. _this._currentTarget = BABYLON.Vector3.Zero();
  43673. _this._viewMatrix = BABYLON.Matrix.Zero();
  43674. _this._camMatrix = BABYLON.Matrix.Zero();
  43675. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43676. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43677. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43678. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43679. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43680. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43681. _this._tempMatrix = BABYLON.Matrix.Zero();
  43682. return _this;
  43683. }
  43684. TargetCamera.prototype.getFrontPosition = function (distance) {
  43685. this.getWorldMatrix();
  43686. var direction = this.getTarget().subtract(this.position);
  43687. direction.normalize();
  43688. direction.scaleInPlace(distance);
  43689. return this.globalPosition.add(direction);
  43690. };
  43691. TargetCamera.prototype._getLockedTargetPosition = function () {
  43692. if (!this.lockedTarget) {
  43693. return null;
  43694. }
  43695. if (this.lockedTarget.absolutePosition) {
  43696. this.lockedTarget.computeWorldMatrix();
  43697. }
  43698. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43699. };
  43700. TargetCamera.prototype.storeState = function () {
  43701. this._storedPosition = this.position.clone();
  43702. this._storedRotation = this.rotation.clone();
  43703. if (this.rotationQuaternion) {
  43704. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43705. }
  43706. return _super.prototype.storeState.call(this);
  43707. };
  43708. /**
  43709. * Restored camera state. You must call storeState() first
  43710. */
  43711. TargetCamera.prototype._restoreStateValues = function () {
  43712. if (!_super.prototype._restoreStateValues.call(this)) {
  43713. return false;
  43714. }
  43715. this.position = this._storedPosition.clone();
  43716. this.rotation = this._storedRotation.clone();
  43717. if (this.rotationQuaternion) {
  43718. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43719. }
  43720. this.cameraDirection.copyFromFloats(0, 0, 0);
  43721. this.cameraRotation.copyFromFloats(0, 0);
  43722. return true;
  43723. };
  43724. // Cache
  43725. TargetCamera.prototype._initCache = function () {
  43726. _super.prototype._initCache.call(this);
  43727. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43728. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43729. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43730. };
  43731. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43732. if (!ignoreParentClass) {
  43733. _super.prototype._updateCache.call(this);
  43734. }
  43735. var lockedTargetPosition = this._getLockedTargetPosition();
  43736. if (!lockedTargetPosition) {
  43737. this._cache.lockedTarget = null;
  43738. }
  43739. else {
  43740. if (!this._cache.lockedTarget) {
  43741. this._cache.lockedTarget = lockedTargetPosition.clone();
  43742. }
  43743. else {
  43744. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43745. }
  43746. }
  43747. this._cache.rotation.copyFrom(this.rotation);
  43748. if (this.rotationQuaternion)
  43749. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43750. };
  43751. // Synchronized
  43752. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43753. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43754. return false;
  43755. }
  43756. var lockedTargetPosition = this._getLockedTargetPosition();
  43757. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43758. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43759. };
  43760. // Methods
  43761. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43762. var engine = this.getEngine();
  43763. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43764. };
  43765. // Target
  43766. TargetCamera.prototype.setTarget = function (target) {
  43767. this.upVector.normalize();
  43768. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43769. this._camMatrix.invert();
  43770. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43771. var vDir = target.subtract(this.position);
  43772. if (vDir.x >= 0.0) {
  43773. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43774. }
  43775. else {
  43776. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43777. }
  43778. this.rotation.z = 0;
  43779. if (isNaN(this.rotation.x)) {
  43780. this.rotation.x = 0;
  43781. }
  43782. if (isNaN(this.rotation.y)) {
  43783. this.rotation.y = 0;
  43784. }
  43785. if (isNaN(this.rotation.z)) {
  43786. this.rotation.z = 0;
  43787. }
  43788. if (this.rotationQuaternion) {
  43789. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43790. }
  43791. };
  43792. /**
  43793. * Return the current target position of the camera. This value is expressed in local space.
  43794. */
  43795. TargetCamera.prototype.getTarget = function () {
  43796. return this._currentTarget;
  43797. };
  43798. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43799. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43800. };
  43801. TargetCamera.prototype._updatePosition = function () {
  43802. if (this.parent) {
  43803. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43804. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43805. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43806. return;
  43807. }
  43808. this.position.addInPlace(this.cameraDirection);
  43809. };
  43810. TargetCamera.prototype._checkInputs = function () {
  43811. var needToMove = this._decideIfNeedsToMove();
  43812. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43813. // Move
  43814. if (needToMove) {
  43815. this._updatePosition();
  43816. }
  43817. // Rotate
  43818. if (needToRotate) {
  43819. this.rotation.x += this.cameraRotation.x;
  43820. this.rotation.y += this.cameraRotation.y;
  43821. //rotate, if quaternion is set and rotation was used
  43822. if (this.rotationQuaternion) {
  43823. var len = this.rotation.lengthSquared();
  43824. if (len) {
  43825. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43826. }
  43827. }
  43828. if (!this.noRotationConstraint) {
  43829. var limit = (Math.PI / 2) * 0.95;
  43830. if (this.rotation.x > limit)
  43831. this.rotation.x = limit;
  43832. if (this.rotation.x < -limit)
  43833. this.rotation.x = -limit;
  43834. }
  43835. }
  43836. // Inertia
  43837. if (needToMove) {
  43838. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43839. this.cameraDirection.x = 0;
  43840. }
  43841. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43842. this.cameraDirection.y = 0;
  43843. }
  43844. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43845. this.cameraDirection.z = 0;
  43846. }
  43847. this.cameraDirection.scaleInPlace(this.inertia);
  43848. }
  43849. if (needToRotate) {
  43850. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43851. this.cameraRotation.x = 0;
  43852. }
  43853. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43854. this.cameraRotation.y = 0;
  43855. }
  43856. this.cameraRotation.scaleInPlace(this.inertia);
  43857. }
  43858. _super.prototype._checkInputs.call(this);
  43859. };
  43860. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43861. if (this.rotationQuaternion) {
  43862. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43863. }
  43864. else {
  43865. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43866. }
  43867. //update the up vector!
  43868. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43869. };
  43870. TargetCamera.prototype._getViewMatrix = function () {
  43871. if (this.lockedTarget) {
  43872. this.setTarget(this._getLockedTargetPosition());
  43873. }
  43874. // Compute
  43875. this._updateCameraRotationMatrix();
  43876. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43877. // Computing target and final matrix
  43878. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43879. if (this.getScene().useRightHandedSystem) {
  43880. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43881. }
  43882. else {
  43883. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43884. }
  43885. return this._viewMatrix;
  43886. };
  43887. /**
  43888. * @override
  43889. * Override Camera.createRigCamera
  43890. */
  43891. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43892. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43893. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43894. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43895. if (!this.rotationQuaternion) {
  43896. this.rotationQuaternion = new BABYLON.Quaternion();
  43897. }
  43898. rigCamera._cameraRigParams = {};
  43899. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43900. }
  43901. return rigCamera;
  43902. }
  43903. return null;
  43904. };
  43905. /**
  43906. * @override
  43907. * Override Camera._updateRigCameras
  43908. */
  43909. TargetCamera.prototype._updateRigCameras = function () {
  43910. var camLeft = this._rigCameras[0];
  43911. var camRight = this._rigCameras[1];
  43912. switch (this.cameraRigMode) {
  43913. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43914. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43915. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43916. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43917. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43918. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43919. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43920. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43921. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43922. camLeft.setTarget(this.getTarget());
  43923. camRight.setTarget(this.getTarget());
  43924. break;
  43925. case BABYLON.Camera.RIG_MODE_VR:
  43926. if (camLeft.rotationQuaternion) {
  43927. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43928. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43929. }
  43930. else {
  43931. camLeft.rotation.copyFrom(this.rotation);
  43932. camRight.rotation.copyFrom(this.rotation);
  43933. }
  43934. camLeft.position.copyFrom(this.position);
  43935. camRight.position.copyFrom(this.position);
  43936. break;
  43937. }
  43938. _super.prototype._updateRigCameras.call(this);
  43939. };
  43940. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43941. if (!this._rigCamTransformMatrix) {
  43942. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43943. }
  43944. var target = this.getTarget();
  43945. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43946. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43947. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43948. };
  43949. TargetCamera.prototype.getClassName = function () {
  43950. return "TargetCamera";
  43951. };
  43952. __decorate([
  43953. BABYLON.serializeAsVector3()
  43954. ], TargetCamera.prototype, "rotation", void 0);
  43955. __decorate([
  43956. BABYLON.serialize()
  43957. ], TargetCamera.prototype, "speed", void 0);
  43958. __decorate([
  43959. BABYLON.serializeAsMeshReference("lockedTargetId")
  43960. ], TargetCamera.prototype, "lockedTarget", void 0);
  43961. return TargetCamera;
  43962. }(BABYLON.Camera));
  43963. BABYLON.TargetCamera = TargetCamera;
  43964. })(BABYLON || (BABYLON = {}));
  43965. //# sourceMappingURL=babylon.targetCamera.js.map
  43966. "use strict";
  43967. var BABYLON;
  43968. (function (BABYLON) {
  43969. var FreeCameraMouseInput = /** @class */ (function () {
  43970. function FreeCameraMouseInput(touchEnabled) {
  43971. if (touchEnabled === void 0) { touchEnabled = true; }
  43972. this.touchEnabled = touchEnabled;
  43973. this.buttons = [0, 1, 2];
  43974. this.angularSensibility = 2000.0;
  43975. this.previousPosition = null;
  43976. }
  43977. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43978. var _this = this;
  43979. var engine = this.camera.getEngine();
  43980. if (!this._pointerInput) {
  43981. this._pointerInput = function (p, s) {
  43982. var evt = p.event;
  43983. if (engine.isInVRExclusivePointerMode) {
  43984. return;
  43985. }
  43986. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43987. return;
  43988. }
  43989. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43990. return;
  43991. }
  43992. var srcElement = (evt.srcElement || evt.target);
  43993. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43994. try {
  43995. srcElement.setPointerCapture(evt.pointerId);
  43996. }
  43997. catch (e) {
  43998. //Nothing to do with the error. Execution will continue.
  43999. }
  44000. _this.previousPosition = {
  44001. x: evt.clientX,
  44002. y: evt.clientY
  44003. };
  44004. if (!noPreventDefault) {
  44005. evt.preventDefault();
  44006. element.focus();
  44007. }
  44008. }
  44009. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44010. try {
  44011. srcElement.releasePointerCapture(evt.pointerId);
  44012. }
  44013. catch (e) {
  44014. //Nothing to do with the error.
  44015. }
  44016. _this.previousPosition = null;
  44017. if (!noPreventDefault) {
  44018. evt.preventDefault();
  44019. }
  44020. }
  44021. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44022. if (!_this.previousPosition || engine.isPointerLock) {
  44023. return;
  44024. }
  44025. var offsetX = evt.clientX - _this.previousPosition.x;
  44026. var offsetY = evt.clientY - _this.previousPosition.y;
  44027. if (_this.camera.getScene().useRightHandedSystem) {
  44028. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44029. }
  44030. else {
  44031. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44032. }
  44033. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44034. _this.previousPosition = {
  44035. x: evt.clientX,
  44036. y: evt.clientY
  44037. };
  44038. if (!noPreventDefault) {
  44039. evt.preventDefault();
  44040. }
  44041. }
  44042. };
  44043. }
  44044. this._onMouseMove = function (evt) {
  44045. if (!engine.isPointerLock) {
  44046. return;
  44047. }
  44048. if (engine.isInVRExclusivePointerMode) {
  44049. return;
  44050. }
  44051. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44052. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44053. if (_this.camera.getScene().useRightHandedSystem) {
  44054. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44055. }
  44056. else {
  44057. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44058. }
  44059. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44060. _this.previousPosition = null;
  44061. if (!noPreventDefault) {
  44062. evt.preventDefault();
  44063. }
  44064. };
  44065. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44066. element.addEventListener("mousemove", this._onMouseMove, false);
  44067. };
  44068. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44069. if (this._observer && element) {
  44070. this.camera.getScene().onPointerObservable.remove(this._observer);
  44071. if (this._onMouseMove) {
  44072. element.removeEventListener("mousemove", this._onMouseMove);
  44073. }
  44074. this._observer = null;
  44075. this._onMouseMove = null;
  44076. this.previousPosition = null;
  44077. }
  44078. };
  44079. FreeCameraMouseInput.prototype.getClassName = function () {
  44080. return "FreeCameraMouseInput";
  44081. };
  44082. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44083. return "mouse";
  44084. };
  44085. __decorate([
  44086. BABYLON.serialize()
  44087. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44088. __decorate([
  44089. BABYLON.serialize()
  44090. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44091. return FreeCameraMouseInput;
  44092. }());
  44093. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44094. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44095. })(BABYLON || (BABYLON = {}));
  44096. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44097. "use strict";
  44098. var BABYLON;
  44099. (function (BABYLON) {
  44100. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44101. function FreeCameraKeyboardMoveInput() {
  44102. this._keys = new Array();
  44103. this.keysUp = [38];
  44104. this.keysDown = [40];
  44105. this.keysLeft = [37];
  44106. this.keysRight = [39];
  44107. }
  44108. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44109. var _this = this;
  44110. if (this._onCanvasBlurObserver) {
  44111. return;
  44112. }
  44113. this._scene = this.camera.getScene();
  44114. this._engine = this._scene.getEngine();
  44115. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44116. _this._keys = [];
  44117. });
  44118. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44119. var evt = info.event;
  44120. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44121. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44122. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44123. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44124. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44125. var index = _this._keys.indexOf(evt.keyCode);
  44126. if (index === -1) {
  44127. _this._keys.push(evt.keyCode);
  44128. }
  44129. if (!noPreventDefault) {
  44130. evt.preventDefault();
  44131. }
  44132. }
  44133. }
  44134. else {
  44135. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44136. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44137. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44138. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44139. var index = _this._keys.indexOf(evt.keyCode);
  44140. if (index >= 0) {
  44141. _this._keys.splice(index, 1);
  44142. }
  44143. if (!noPreventDefault) {
  44144. evt.preventDefault();
  44145. }
  44146. }
  44147. }
  44148. });
  44149. };
  44150. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44151. if (this._scene) {
  44152. if (this._onKeyboardObserver) {
  44153. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44154. }
  44155. if (this._onCanvasBlurObserver) {
  44156. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44157. }
  44158. this._onKeyboardObserver = null;
  44159. this._onCanvasBlurObserver = null;
  44160. }
  44161. this._keys = [];
  44162. };
  44163. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44164. if (this._onKeyboardObserver) {
  44165. var camera = this.camera;
  44166. // Keyboard
  44167. for (var index = 0; index < this._keys.length; index++) {
  44168. var keyCode = this._keys[index];
  44169. var speed = camera._computeLocalCameraSpeed();
  44170. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44171. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44172. }
  44173. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44174. camera._localDirection.copyFromFloats(0, 0, speed);
  44175. }
  44176. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44177. camera._localDirection.copyFromFloats(speed, 0, 0);
  44178. }
  44179. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44180. camera._localDirection.copyFromFloats(0, 0, -speed);
  44181. }
  44182. if (camera.getScene().useRightHandedSystem) {
  44183. camera._localDirection.z *= -1;
  44184. }
  44185. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44186. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44187. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44188. }
  44189. }
  44190. };
  44191. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44192. return "FreeCameraKeyboardMoveInput";
  44193. };
  44194. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44195. this._keys = [];
  44196. };
  44197. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44198. return "keyboard";
  44199. };
  44200. __decorate([
  44201. BABYLON.serialize()
  44202. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44203. __decorate([
  44204. BABYLON.serialize()
  44205. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44206. __decorate([
  44207. BABYLON.serialize()
  44208. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44209. __decorate([
  44210. BABYLON.serialize()
  44211. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44212. return FreeCameraKeyboardMoveInput;
  44213. }());
  44214. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44215. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44216. })(BABYLON || (BABYLON = {}));
  44217. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44218. "use strict";
  44219. var BABYLON;
  44220. (function (BABYLON) {
  44221. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44222. __extends(FreeCameraInputsManager, _super);
  44223. function FreeCameraInputsManager(camera) {
  44224. return _super.call(this, camera) || this;
  44225. }
  44226. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44227. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44228. return this;
  44229. };
  44230. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44231. if (touchEnabled === void 0) { touchEnabled = true; }
  44232. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44233. return this;
  44234. };
  44235. FreeCameraInputsManager.prototype.addGamepad = function () {
  44236. this.add(new BABYLON.FreeCameraGamepadInput());
  44237. return this;
  44238. };
  44239. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44240. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44241. return this;
  44242. };
  44243. FreeCameraInputsManager.prototype.addTouch = function () {
  44244. this.add(new BABYLON.FreeCameraTouchInput());
  44245. return this;
  44246. };
  44247. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44248. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44249. return this;
  44250. };
  44251. return FreeCameraInputsManager;
  44252. }(BABYLON.CameraInputsManager));
  44253. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44254. })(BABYLON || (BABYLON = {}));
  44255. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44256. "use strict";
  44257. var BABYLON;
  44258. (function (BABYLON) {
  44259. var FreeCamera = /** @class */ (function (_super) {
  44260. __extends(FreeCamera, _super);
  44261. function FreeCamera(name, position, scene) {
  44262. var _this = _super.call(this, name, position, scene) || this;
  44263. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44264. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44265. _this.checkCollisions = false;
  44266. _this.applyGravity = false;
  44267. _this._needMoveForGravity = false;
  44268. _this._oldPosition = BABYLON.Vector3.Zero();
  44269. _this._diffPosition = BABYLON.Vector3.Zero();
  44270. _this._newPosition = BABYLON.Vector3.Zero();
  44271. // Collisions
  44272. _this._collisionMask = -1;
  44273. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44274. if (collidedMesh === void 0) { collidedMesh = null; }
  44275. //TODO move this to the collision coordinator!
  44276. if (_this.getScene().workerCollisions)
  44277. newPosition.multiplyInPlace(_this._collider._radius);
  44278. var updatePosition = function (newPos) {
  44279. _this._newPosition.copyFrom(newPos);
  44280. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44281. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44282. _this.position.addInPlace(_this._diffPosition);
  44283. if (_this.onCollide && collidedMesh) {
  44284. _this.onCollide(collidedMesh);
  44285. }
  44286. }
  44287. };
  44288. updatePosition(newPosition);
  44289. };
  44290. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44291. _this.inputs.addKeyboard().addMouse();
  44292. return _this;
  44293. }
  44294. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44295. //-- begin properties for backward compatibility for inputs
  44296. /**
  44297. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44298. * Higher values reduce sensitivity.
  44299. */
  44300. get: function () {
  44301. var mouse = this.inputs.attached["mouse"];
  44302. if (mouse)
  44303. return mouse.angularSensibility;
  44304. return 0;
  44305. },
  44306. /**
  44307. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44308. * Higher values reduce sensitivity.
  44309. */
  44310. set: function (value) {
  44311. var mouse = this.inputs.attached["mouse"];
  44312. if (mouse)
  44313. mouse.angularSensibility = value;
  44314. },
  44315. enumerable: true,
  44316. configurable: true
  44317. });
  44318. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44319. get: function () {
  44320. var keyboard = this.inputs.attached["keyboard"];
  44321. if (keyboard)
  44322. return keyboard.keysUp;
  44323. return [];
  44324. },
  44325. set: function (value) {
  44326. var keyboard = this.inputs.attached["keyboard"];
  44327. if (keyboard)
  44328. keyboard.keysUp = value;
  44329. },
  44330. enumerable: true,
  44331. configurable: true
  44332. });
  44333. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44334. get: function () {
  44335. var keyboard = this.inputs.attached["keyboard"];
  44336. if (keyboard)
  44337. return keyboard.keysDown;
  44338. return [];
  44339. },
  44340. set: function (value) {
  44341. var keyboard = this.inputs.attached["keyboard"];
  44342. if (keyboard)
  44343. keyboard.keysDown = value;
  44344. },
  44345. enumerable: true,
  44346. configurable: true
  44347. });
  44348. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44349. get: function () {
  44350. var keyboard = this.inputs.attached["keyboard"];
  44351. if (keyboard)
  44352. return keyboard.keysLeft;
  44353. return [];
  44354. },
  44355. set: function (value) {
  44356. var keyboard = this.inputs.attached["keyboard"];
  44357. if (keyboard)
  44358. keyboard.keysLeft = value;
  44359. },
  44360. enumerable: true,
  44361. configurable: true
  44362. });
  44363. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44364. get: function () {
  44365. var keyboard = this.inputs.attached["keyboard"];
  44366. if (keyboard)
  44367. return keyboard.keysRight;
  44368. return [];
  44369. },
  44370. set: function (value) {
  44371. var keyboard = this.inputs.attached["keyboard"];
  44372. if (keyboard)
  44373. keyboard.keysRight = value;
  44374. },
  44375. enumerable: true,
  44376. configurable: true
  44377. });
  44378. // Controls
  44379. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44380. this.inputs.attachElement(element, noPreventDefault);
  44381. };
  44382. FreeCamera.prototype.detachControl = function (element) {
  44383. this.inputs.detachElement(element);
  44384. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44385. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44386. };
  44387. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44388. get: function () {
  44389. return this._collisionMask;
  44390. },
  44391. set: function (mask) {
  44392. this._collisionMask = !isNaN(mask) ? mask : -1;
  44393. },
  44394. enumerable: true,
  44395. configurable: true
  44396. });
  44397. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44398. var globalPosition;
  44399. if (this.parent) {
  44400. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44401. }
  44402. else {
  44403. globalPosition = this.position;
  44404. }
  44405. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44406. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44407. if (!this._collider) {
  44408. this._collider = new BABYLON.Collider();
  44409. }
  44410. this._collider._radius = this.ellipsoid;
  44411. this._collider.collisionMask = this._collisionMask;
  44412. //no need for clone, as long as gravity is not on.
  44413. var actualDisplacement = displacement;
  44414. //add gravity to the direction to prevent the dual-collision checking
  44415. if (this.applyGravity) {
  44416. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44417. actualDisplacement = displacement.add(this.getScene().gravity);
  44418. }
  44419. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44420. };
  44421. FreeCamera.prototype._checkInputs = function () {
  44422. if (!this._localDirection) {
  44423. this._localDirection = BABYLON.Vector3.Zero();
  44424. this._transformedDirection = BABYLON.Vector3.Zero();
  44425. }
  44426. this.inputs.checkInputs();
  44427. _super.prototype._checkInputs.call(this);
  44428. };
  44429. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44430. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44431. };
  44432. FreeCamera.prototype._updatePosition = function () {
  44433. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44434. this._collideWithWorld(this.cameraDirection);
  44435. }
  44436. else {
  44437. _super.prototype._updatePosition.call(this);
  44438. }
  44439. };
  44440. FreeCamera.prototype.dispose = function () {
  44441. this.inputs.clear();
  44442. _super.prototype.dispose.call(this);
  44443. };
  44444. FreeCamera.prototype.getClassName = function () {
  44445. return "FreeCamera";
  44446. };
  44447. __decorate([
  44448. BABYLON.serializeAsVector3()
  44449. ], FreeCamera.prototype, "ellipsoid", void 0);
  44450. __decorate([
  44451. BABYLON.serializeAsVector3()
  44452. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44453. __decorate([
  44454. BABYLON.serialize()
  44455. ], FreeCamera.prototype, "checkCollisions", void 0);
  44456. __decorate([
  44457. BABYLON.serialize()
  44458. ], FreeCamera.prototype, "applyGravity", void 0);
  44459. return FreeCamera;
  44460. }(BABYLON.TargetCamera));
  44461. BABYLON.FreeCamera = FreeCamera;
  44462. })(BABYLON || (BABYLON = {}));
  44463. //# sourceMappingURL=babylon.freeCamera.js.map
  44464. "use strict";
  44465. var BABYLON;
  44466. (function (BABYLON) {
  44467. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44468. function ArcRotateCameraKeyboardMoveInput() {
  44469. this._keys = new Array();
  44470. this.keysUp = [38];
  44471. this.keysDown = [40];
  44472. this.keysLeft = [37];
  44473. this.keysRight = [39];
  44474. this.keysReset = [220];
  44475. this.panningSensibility = 50.0;
  44476. this.zoomingSensibility = 25.0;
  44477. this.useAltToZoom = true;
  44478. }
  44479. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44480. var _this = this;
  44481. if (this._onCanvasBlurObserver) {
  44482. return;
  44483. }
  44484. this._scene = this.camera.getScene();
  44485. this._engine = this._scene.getEngine();
  44486. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44487. _this._keys = [];
  44488. });
  44489. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44490. var evt = info.event;
  44491. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44492. _this._ctrlPressed = evt.ctrlKey;
  44493. _this._altPressed = evt.altKey;
  44494. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44495. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44496. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44497. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44498. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44499. var index = _this._keys.indexOf(evt.keyCode);
  44500. if (index === -1) {
  44501. _this._keys.push(evt.keyCode);
  44502. }
  44503. if (evt.preventDefault) {
  44504. if (!noPreventDefault) {
  44505. evt.preventDefault();
  44506. }
  44507. }
  44508. }
  44509. }
  44510. else {
  44511. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44512. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44513. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44514. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44515. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44516. var index = _this._keys.indexOf(evt.keyCode);
  44517. if (index >= 0) {
  44518. _this._keys.splice(index, 1);
  44519. }
  44520. if (evt.preventDefault) {
  44521. if (!noPreventDefault) {
  44522. evt.preventDefault();
  44523. }
  44524. }
  44525. }
  44526. }
  44527. });
  44528. };
  44529. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44530. if (this._scene) {
  44531. if (this._onKeyboardObserver) {
  44532. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44533. }
  44534. if (this._onCanvasBlurObserver) {
  44535. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44536. }
  44537. this._onKeyboardObserver = null;
  44538. this._onCanvasBlurObserver = null;
  44539. }
  44540. this._keys = [];
  44541. };
  44542. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44543. if (this._onKeyboardObserver) {
  44544. var camera = this.camera;
  44545. for (var index = 0; index < this._keys.length; index++) {
  44546. var keyCode = this._keys[index];
  44547. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44548. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44549. camera.inertialPanningX -= 1 / this.panningSensibility;
  44550. }
  44551. else {
  44552. camera.inertialAlphaOffset -= 0.01;
  44553. }
  44554. }
  44555. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44556. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44557. camera.inertialPanningY += 1 / this.panningSensibility;
  44558. }
  44559. else if (this._altPressed && this.useAltToZoom) {
  44560. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44561. }
  44562. else {
  44563. camera.inertialBetaOffset -= 0.01;
  44564. }
  44565. }
  44566. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44567. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44568. camera.inertialPanningX += 1 / this.panningSensibility;
  44569. }
  44570. else {
  44571. camera.inertialAlphaOffset += 0.01;
  44572. }
  44573. }
  44574. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44575. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44576. camera.inertialPanningY -= 1 / this.panningSensibility;
  44577. }
  44578. else if (this._altPressed && this.useAltToZoom) {
  44579. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44580. }
  44581. else {
  44582. camera.inertialBetaOffset += 0.01;
  44583. }
  44584. }
  44585. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44586. camera.restoreState();
  44587. }
  44588. }
  44589. }
  44590. };
  44591. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44592. return "ArcRotateCameraKeyboardMoveInput";
  44593. };
  44594. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44595. return "keyboard";
  44596. };
  44597. __decorate([
  44598. BABYLON.serialize()
  44599. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44600. __decorate([
  44601. BABYLON.serialize()
  44602. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44603. __decorate([
  44604. BABYLON.serialize()
  44605. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44606. __decorate([
  44607. BABYLON.serialize()
  44608. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44609. __decorate([
  44610. BABYLON.serialize()
  44611. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44612. __decorate([
  44613. BABYLON.serialize()
  44614. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44615. __decorate([
  44616. BABYLON.serialize()
  44617. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44618. __decorate([
  44619. BABYLON.serialize()
  44620. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44621. return ArcRotateCameraKeyboardMoveInput;
  44622. }());
  44623. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44624. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44625. })(BABYLON || (BABYLON = {}));
  44626. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44627. "use strict";
  44628. var BABYLON;
  44629. (function (BABYLON) {
  44630. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44631. function ArcRotateCameraMouseWheelInput() {
  44632. this.wheelPrecision = 3.0;
  44633. /**
  44634. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44635. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44636. */
  44637. this.wheelDeltaPercentage = 0;
  44638. }
  44639. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44640. var _this = this;
  44641. this._wheel = function (p, s) {
  44642. //sanity check - this should be a PointerWheel event.
  44643. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44644. return;
  44645. var event = p.event;
  44646. var delta = 0;
  44647. if (event.wheelDelta) {
  44648. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44649. }
  44650. else if (event.detail) {
  44651. delta = -event.detail / _this.wheelPrecision;
  44652. }
  44653. if (delta)
  44654. _this.camera.inertialRadiusOffset += delta;
  44655. if (event.preventDefault) {
  44656. if (!noPreventDefault) {
  44657. event.preventDefault();
  44658. }
  44659. }
  44660. };
  44661. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44662. };
  44663. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44664. if (this._observer && element) {
  44665. this.camera.getScene().onPointerObservable.remove(this._observer);
  44666. this._observer = null;
  44667. this._wheel = null;
  44668. }
  44669. };
  44670. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44671. return "ArcRotateCameraMouseWheelInput";
  44672. };
  44673. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44674. return "mousewheel";
  44675. };
  44676. __decorate([
  44677. BABYLON.serialize()
  44678. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44679. __decorate([
  44680. BABYLON.serialize()
  44681. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44682. return ArcRotateCameraMouseWheelInput;
  44683. }());
  44684. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44685. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44686. })(BABYLON || (BABYLON = {}));
  44687. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44688. "use strict";
  44689. var BABYLON;
  44690. (function (BABYLON) {
  44691. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44692. function ArcRotateCameraPointersInput() {
  44693. this.buttons = [0, 1, 2];
  44694. this.angularSensibilityX = 1000.0;
  44695. this.angularSensibilityY = 1000.0;
  44696. this.pinchPrecision = 12.0;
  44697. /**
  44698. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44699. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44700. */
  44701. this.pinchDeltaPercentage = 0;
  44702. this.panningSensibility = 1000.0;
  44703. this.multiTouchPanning = true;
  44704. this.multiTouchPanAndZoom = true;
  44705. this._isPanClick = false;
  44706. this.pinchInwards = true;
  44707. }
  44708. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44709. var _this = this;
  44710. var engine = this.camera.getEngine();
  44711. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44712. var pointA = null;
  44713. var pointB = null;
  44714. var previousPinchSquaredDistance = 0;
  44715. var initialDistance = 0;
  44716. var twoFingerActivityCount = 0;
  44717. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44718. this._pointerInput = function (p, s) {
  44719. var evt = p.event;
  44720. var isTouch = p.event.pointerType === "touch";
  44721. if (engine.isInVRExclusivePointerMode) {
  44722. return;
  44723. }
  44724. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44725. return;
  44726. }
  44727. var srcElement = (evt.srcElement || evt.target);
  44728. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44729. try {
  44730. srcElement.setPointerCapture(evt.pointerId);
  44731. }
  44732. catch (e) {
  44733. //Nothing to do with the error. Execution will continue.
  44734. }
  44735. // Manage panning with pan button click
  44736. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44737. // manage pointers
  44738. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44739. if (pointA === null) {
  44740. pointA = cacheSoloPointer;
  44741. }
  44742. else if (pointB === null) {
  44743. pointB = cacheSoloPointer;
  44744. }
  44745. if (!noPreventDefault) {
  44746. evt.preventDefault();
  44747. element.focus();
  44748. }
  44749. }
  44750. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44751. _this.camera.restoreState();
  44752. }
  44753. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44754. try {
  44755. srcElement.releasePointerCapture(evt.pointerId);
  44756. }
  44757. catch (e) {
  44758. //Nothing to do with the error.
  44759. }
  44760. cacheSoloPointer = null;
  44761. previousPinchSquaredDistance = 0;
  44762. previousMultiTouchPanPosition.isPaning = false;
  44763. previousMultiTouchPanPosition.isPinching = false;
  44764. twoFingerActivityCount = 0;
  44765. initialDistance = 0;
  44766. if (!isTouch) {
  44767. pointB = null; // Mouse and pen are mono pointer
  44768. }
  44769. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44770. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44771. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44772. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44773. if (engine.badOS) {
  44774. pointA = pointB = null;
  44775. }
  44776. else {
  44777. //only remove the impacted pointer in case of multitouch allowing on most
  44778. //platforms switching from rotate to zoom and pan seamlessly.
  44779. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44780. pointA = pointB;
  44781. pointB = null;
  44782. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44783. }
  44784. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44785. pointB = null;
  44786. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44787. }
  44788. else {
  44789. pointA = pointB = null;
  44790. }
  44791. }
  44792. if (!noPreventDefault) {
  44793. evt.preventDefault();
  44794. }
  44795. }
  44796. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44797. if (!noPreventDefault) {
  44798. evt.preventDefault();
  44799. }
  44800. // One button down
  44801. if (pointA && pointB === null && cacheSoloPointer) {
  44802. if (_this.panningSensibility !== 0 &&
  44803. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44804. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44805. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44806. }
  44807. else {
  44808. var offsetX = evt.clientX - cacheSoloPointer.x;
  44809. var offsetY = evt.clientY - cacheSoloPointer.y;
  44810. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44811. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44812. }
  44813. cacheSoloPointer.x = evt.clientX;
  44814. cacheSoloPointer.y = evt.clientY;
  44815. }
  44816. else if (pointA && pointB) {
  44817. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44818. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44819. ed.x = evt.clientX;
  44820. ed.y = evt.clientY;
  44821. var direction = _this.pinchInwards ? 1 : -1;
  44822. var distX = pointA.x - pointB.x;
  44823. var distY = pointA.y - pointB.y;
  44824. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44825. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44826. if (previousPinchSquaredDistance === 0) {
  44827. initialDistance = pinchDistance;
  44828. previousPinchSquaredDistance = pinchSquaredDistance;
  44829. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44830. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44831. return;
  44832. }
  44833. if (_this.multiTouchPanAndZoom) {
  44834. if (_this.pinchDeltaPercentage) {
  44835. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44836. }
  44837. else {
  44838. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44839. (_this.pinchPrecision *
  44840. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44841. direction);
  44842. }
  44843. if (_this.panningSensibility !== 0) {
  44844. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44845. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44846. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44847. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44848. previousMultiTouchPanPosition.x = pointersCenterX;
  44849. previousMultiTouchPanPosition.y = pointersCenterY;
  44850. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44851. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44852. }
  44853. }
  44854. else {
  44855. twoFingerActivityCount++;
  44856. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44857. if (_this.pinchDeltaPercentage) {
  44858. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44859. }
  44860. else {
  44861. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44862. (_this.pinchPrecision *
  44863. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44864. direction);
  44865. }
  44866. previousMultiTouchPanPosition.isPaning = false;
  44867. previousMultiTouchPanPosition.isPinching = true;
  44868. }
  44869. else {
  44870. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44871. if (!previousMultiTouchPanPosition.isPaning) {
  44872. previousMultiTouchPanPosition.isPaning = true;
  44873. previousMultiTouchPanPosition.isPinching = false;
  44874. previousMultiTouchPanPosition.x = ed.x;
  44875. previousMultiTouchPanPosition.y = ed.y;
  44876. return;
  44877. }
  44878. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44879. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44880. }
  44881. }
  44882. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44883. previousMultiTouchPanPosition.x = ed.x;
  44884. previousMultiTouchPanPosition.y = ed.y;
  44885. }
  44886. }
  44887. previousPinchSquaredDistance = pinchSquaredDistance;
  44888. }
  44889. }
  44890. };
  44891. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44892. this._onContextMenu = function (evt) {
  44893. evt.preventDefault();
  44894. };
  44895. if (!this.camera._useCtrlForPanning) {
  44896. element.addEventListener("contextmenu", this._onContextMenu, false);
  44897. }
  44898. this._onLostFocus = function () {
  44899. //this._keys = [];
  44900. pointA = pointB = null;
  44901. previousPinchSquaredDistance = 0;
  44902. previousMultiTouchPanPosition.isPaning = false;
  44903. previousMultiTouchPanPosition.isPinching = false;
  44904. twoFingerActivityCount = 0;
  44905. cacheSoloPointer = null;
  44906. initialDistance = 0;
  44907. };
  44908. this._onMouseMove = function (evt) {
  44909. if (!engine.isPointerLock) {
  44910. return;
  44911. }
  44912. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44913. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44914. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44915. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44916. if (!noPreventDefault) {
  44917. evt.preventDefault();
  44918. }
  44919. };
  44920. this._onGestureStart = function (e) {
  44921. if (window.MSGesture === undefined) {
  44922. return;
  44923. }
  44924. if (!_this._MSGestureHandler) {
  44925. _this._MSGestureHandler = new MSGesture();
  44926. _this._MSGestureHandler.target = element;
  44927. }
  44928. _this._MSGestureHandler.addPointer(e.pointerId);
  44929. };
  44930. this._onGesture = function (e) {
  44931. _this.camera.radius *= e.scale;
  44932. if (e.preventDefault) {
  44933. if (!noPreventDefault) {
  44934. e.stopPropagation();
  44935. e.preventDefault();
  44936. }
  44937. }
  44938. };
  44939. element.addEventListener("mousemove", this._onMouseMove, false);
  44940. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44941. element.addEventListener("MSGestureChange", this._onGesture, false);
  44942. BABYLON.Tools.RegisterTopRootEvents([
  44943. { name: "blur", handler: this._onLostFocus }
  44944. ]);
  44945. };
  44946. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44947. if (this._onLostFocus) {
  44948. BABYLON.Tools.UnregisterTopRootEvents([
  44949. { name: "blur", handler: this._onLostFocus }
  44950. ]);
  44951. }
  44952. if (element && this._observer) {
  44953. this.camera.getScene().onPointerObservable.remove(this._observer);
  44954. this._observer = null;
  44955. if (this._onContextMenu) {
  44956. element.removeEventListener("contextmenu", this._onContextMenu);
  44957. }
  44958. if (this._onMouseMove) {
  44959. element.removeEventListener("mousemove", this._onMouseMove);
  44960. }
  44961. if (this._onGestureStart) {
  44962. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44963. }
  44964. if (this._onGesture) {
  44965. element.removeEventListener("MSGestureChange", this._onGesture);
  44966. }
  44967. this._isPanClick = false;
  44968. this.pinchInwards = true;
  44969. this._onMouseMove = null;
  44970. this._onGestureStart = null;
  44971. this._onGesture = null;
  44972. this._MSGestureHandler = null;
  44973. this._onLostFocus = null;
  44974. this._onContextMenu = null;
  44975. }
  44976. };
  44977. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44978. return "ArcRotateCameraPointersInput";
  44979. };
  44980. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44981. return "pointers";
  44982. };
  44983. __decorate([
  44984. BABYLON.serialize()
  44985. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44986. __decorate([
  44987. BABYLON.serialize()
  44988. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44989. __decorate([
  44990. BABYLON.serialize()
  44991. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44992. __decorate([
  44993. BABYLON.serialize()
  44994. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44995. __decorate([
  44996. BABYLON.serialize()
  44997. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44998. __decorate([
  44999. BABYLON.serialize()
  45000. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  45001. __decorate([
  45002. BABYLON.serialize()
  45003. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  45004. __decorate([
  45005. BABYLON.serialize()
  45006. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  45007. return ArcRotateCameraPointersInput;
  45008. }());
  45009. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  45010. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  45011. })(BABYLON || (BABYLON = {}));
  45012. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  45013. "use strict";
  45014. var BABYLON;
  45015. (function (BABYLON) {
  45016. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  45017. __extends(ArcRotateCameraInputsManager, _super);
  45018. function ArcRotateCameraInputsManager(camera) {
  45019. return _super.call(this, camera) || this;
  45020. }
  45021. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  45022. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  45023. return this;
  45024. };
  45025. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  45026. this.add(new BABYLON.ArcRotateCameraPointersInput());
  45027. return this;
  45028. };
  45029. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  45030. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  45031. return this;
  45032. };
  45033. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  45034. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  45035. return this;
  45036. };
  45037. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  45038. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  45039. return this;
  45040. };
  45041. return ArcRotateCameraInputsManager;
  45042. }(BABYLON.CameraInputsManager));
  45043. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  45044. })(BABYLON || (BABYLON = {}));
  45045. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  45046. "use strict";
  45047. var BABYLON;
  45048. (function (BABYLON) {
  45049. var ArcRotateCamera = /** @class */ (function (_super) {
  45050. __extends(ArcRotateCamera, _super);
  45051. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45052. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45053. _this.inertialAlphaOffset = 0;
  45054. _this.inertialBetaOffset = 0;
  45055. _this.inertialRadiusOffset = 0;
  45056. _this.lowerAlphaLimit = null;
  45057. _this.upperAlphaLimit = null;
  45058. _this.lowerBetaLimit = 0.01;
  45059. _this.upperBetaLimit = Math.PI;
  45060. _this.lowerRadiusLimit = null;
  45061. _this.upperRadiusLimit = null;
  45062. _this.inertialPanningX = 0;
  45063. _this.inertialPanningY = 0;
  45064. _this.pinchToPanMaxDistance = 20;
  45065. _this.panningDistanceLimit = null;
  45066. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45067. _this.panningInertia = 0.9;
  45068. //-- end properties for backward compatibility for inputs
  45069. _this.zoomOnFactor = 1;
  45070. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45071. _this.allowUpsideDown = true;
  45072. _this._viewMatrix = new BABYLON.Matrix();
  45073. // Panning
  45074. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45075. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45076. _this.checkCollisions = false;
  45077. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45078. _this._previousPosition = BABYLON.Vector3.Zero();
  45079. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45080. _this._newPosition = BABYLON.Vector3.Zero();
  45081. _this._computationVector = BABYLON.Vector3.Zero();
  45082. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45083. if (collidedMesh === void 0) { collidedMesh = null; }
  45084. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45085. newPosition.multiplyInPlace(_this._collider._radius);
  45086. }
  45087. if (!collidedMesh) {
  45088. _this._previousPosition.copyFrom(_this.position);
  45089. }
  45090. else {
  45091. _this.setPosition(newPosition);
  45092. if (_this.onCollide) {
  45093. _this.onCollide(collidedMesh);
  45094. }
  45095. }
  45096. // Recompute because of constraints
  45097. var cosa = Math.cos(_this.alpha);
  45098. var sina = Math.sin(_this.alpha);
  45099. var cosb = Math.cos(_this.beta);
  45100. var sinb = Math.sin(_this.beta);
  45101. if (sinb === 0) {
  45102. sinb = 0.0001;
  45103. }
  45104. var target = _this._getTargetPosition();
  45105. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45106. target.addToRef(_this._computationVector, _this._newPosition);
  45107. _this.position.copyFrom(_this._newPosition);
  45108. var up = _this.upVector;
  45109. if (_this.allowUpsideDown && _this.beta < 0) {
  45110. up = up.clone();
  45111. up = up.negate();
  45112. }
  45113. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45114. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45115. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45116. _this._collisionTriggered = false;
  45117. };
  45118. _this._target = BABYLON.Vector3.Zero();
  45119. if (target) {
  45120. _this.setTarget(target);
  45121. }
  45122. _this.alpha = alpha;
  45123. _this.beta = beta;
  45124. _this.radius = radius;
  45125. _this.getViewMatrix();
  45126. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45127. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45128. return _this;
  45129. }
  45130. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45131. get: function () {
  45132. return this._target;
  45133. },
  45134. set: function (value) {
  45135. this.setTarget(value);
  45136. },
  45137. enumerable: true,
  45138. configurable: true
  45139. });
  45140. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45141. //-- begin properties for backward compatibility for inputs
  45142. get: function () {
  45143. var pointers = this.inputs.attached["pointers"];
  45144. if (pointers)
  45145. return pointers.angularSensibilityX;
  45146. return 0;
  45147. },
  45148. set: function (value) {
  45149. var pointers = this.inputs.attached["pointers"];
  45150. if (pointers) {
  45151. pointers.angularSensibilityX = value;
  45152. }
  45153. },
  45154. enumerable: true,
  45155. configurable: true
  45156. });
  45157. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45158. get: function () {
  45159. var pointers = this.inputs.attached["pointers"];
  45160. if (pointers)
  45161. return pointers.angularSensibilityY;
  45162. return 0;
  45163. },
  45164. set: function (value) {
  45165. var pointers = this.inputs.attached["pointers"];
  45166. if (pointers) {
  45167. pointers.angularSensibilityY = value;
  45168. }
  45169. },
  45170. enumerable: true,
  45171. configurable: true
  45172. });
  45173. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45174. get: function () {
  45175. var pointers = this.inputs.attached["pointers"];
  45176. if (pointers)
  45177. return pointers.pinchPrecision;
  45178. return 0;
  45179. },
  45180. set: function (value) {
  45181. var pointers = this.inputs.attached["pointers"];
  45182. if (pointers) {
  45183. pointers.pinchPrecision = value;
  45184. }
  45185. },
  45186. enumerable: true,
  45187. configurable: true
  45188. });
  45189. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45190. get: function () {
  45191. var pointers = this.inputs.attached["pointers"];
  45192. if (pointers)
  45193. return pointers.pinchDeltaPercentage;
  45194. return 0;
  45195. },
  45196. set: function (value) {
  45197. var pointers = this.inputs.attached["pointers"];
  45198. if (pointers) {
  45199. pointers.pinchDeltaPercentage = value;
  45200. }
  45201. },
  45202. enumerable: true,
  45203. configurable: true
  45204. });
  45205. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45206. get: function () {
  45207. var pointers = this.inputs.attached["pointers"];
  45208. if (pointers)
  45209. return pointers.panningSensibility;
  45210. return 0;
  45211. },
  45212. set: function (value) {
  45213. var pointers = this.inputs.attached["pointers"];
  45214. if (pointers) {
  45215. pointers.panningSensibility = value;
  45216. }
  45217. },
  45218. enumerable: true,
  45219. configurable: true
  45220. });
  45221. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45222. get: function () {
  45223. var keyboard = this.inputs.attached["keyboard"];
  45224. if (keyboard)
  45225. return keyboard.keysUp;
  45226. return [];
  45227. },
  45228. set: function (value) {
  45229. var keyboard = this.inputs.attached["keyboard"];
  45230. if (keyboard)
  45231. keyboard.keysUp = value;
  45232. },
  45233. enumerable: true,
  45234. configurable: true
  45235. });
  45236. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45237. get: function () {
  45238. var keyboard = this.inputs.attached["keyboard"];
  45239. if (keyboard)
  45240. return keyboard.keysDown;
  45241. return [];
  45242. },
  45243. set: function (value) {
  45244. var keyboard = this.inputs.attached["keyboard"];
  45245. if (keyboard)
  45246. keyboard.keysDown = value;
  45247. },
  45248. enumerable: true,
  45249. configurable: true
  45250. });
  45251. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45252. get: function () {
  45253. var keyboard = this.inputs.attached["keyboard"];
  45254. if (keyboard)
  45255. return keyboard.keysLeft;
  45256. return [];
  45257. },
  45258. set: function (value) {
  45259. var keyboard = this.inputs.attached["keyboard"];
  45260. if (keyboard)
  45261. keyboard.keysLeft = value;
  45262. },
  45263. enumerable: true,
  45264. configurable: true
  45265. });
  45266. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45267. get: function () {
  45268. var keyboard = this.inputs.attached["keyboard"];
  45269. if (keyboard)
  45270. return keyboard.keysRight;
  45271. return [];
  45272. },
  45273. set: function (value) {
  45274. var keyboard = this.inputs.attached["keyboard"];
  45275. if (keyboard)
  45276. keyboard.keysRight = value;
  45277. },
  45278. enumerable: true,
  45279. configurable: true
  45280. });
  45281. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45282. get: function () {
  45283. var mousewheel = this.inputs.attached["mousewheel"];
  45284. if (mousewheel)
  45285. return mousewheel.wheelPrecision;
  45286. return 0;
  45287. },
  45288. set: function (value) {
  45289. var mousewheel = this.inputs.attached["mousewheel"];
  45290. if (mousewheel)
  45291. mousewheel.wheelPrecision = value;
  45292. },
  45293. enumerable: true,
  45294. configurable: true
  45295. });
  45296. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45297. get: function () {
  45298. var mousewheel = this.inputs.attached["mousewheel"];
  45299. if (mousewheel)
  45300. return mousewheel.wheelDeltaPercentage;
  45301. return 0;
  45302. },
  45303. set: function (value) {
  45304. var mousewheel = this.inputs.attached["mousewheel"];
  45305. if (mousewheel)
  45306. mousewheel.wheelDeltaPercentage = value;
  45307. },
  45308. enumerable: true,
  45309. configurable: true
  45310. });
  45311. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45312. get: function () {
  45313. return this._bouncingBehavior;
  45314. },
  45315. enumerable: true,
  45316. configurable: true
  45317. });
  45318. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45319. get: function () {
  45320. return this._bouncingBehavior != null;
  45321. },
  45322. set: function (value) {
  45323. if (value === this.useBouncingBehavior) {
  45324. return;
  45325. }
  45326. if (value) {
  45327. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45328. this.addBehavior(this._bouncingBehavior);
  45329. }
  45330. else if (this._bouncingBehavior) {
  45331. this.removeBehavior(this._bouncingBehavior);
  45332. this._bouncingBehavior = null;
  45333. }
  45334. },
  45335. enumerable: true,
  45336. configurable: true
  45337. });
  45338. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45339. get: function () {
  45340. return this._framingBehavior;
  45341. },
  45342. enumerable: true,
  45343. configurable: true
  45344. });
  45345. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45346. get: function () {
  45347. return this._framingBehavior != null;
  45348. },
  45349. set: function (value) {
  45350. if (value === this.useFramingBehavior) {
  45351. return;
  45352. }
  45353. if (value) {
  45354. this._framingBehavior = new BABYLON.FramingBehavior();
  45355. this.addBehavior(this._framingBehavior);
  45356. }
  45357. else if (this._framingBehavior) {
  45358. this.removeBehavior(this._framingBehavior);
  45359. this._framingBehavior = null;
  45360. }
  45361. },
  45362. enumerable: true,
  45363. configurable: true
  45364. });
  45365. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45366. get: function () {
  45367. return this._autoRotationBehavior;
  45368. },
  45369. enumerable: true,
  45370. configurable: true
  45371. });
  45372. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45373. get: function () {
  45374. return this._autoRotationBehavior != null;
  45375. },
  45376. set: function (value) {
  45377. if (value === this.useAutoRotationBehavior) {
  45378. return;
  45379. }
  45380. if (value) {
  45381. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45382. this.addBehavior(this._autoRotationBehavior);
  45383. }
  45384. else if (this._autoRotationBehavior) {
  45385. this.removeBehavior(this._autoRotationBehavior);
  45386. this._autoRotationBehavior = null;
  45387. }
  45388. },
  45389. enumerable: true,
  45390. configurable: true
  45391. });
  45392. // Cache
  45393. ArcRotateCamera.prototype._initCache = function () {
  45394. _super.prototype._initCache.call(this);
  45395. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45396. this._cache.alpha = undefined;
  45397. this._cache.beta = undefined;
  45398. this._cache.radius = undefined;
  45399. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45400. };
  45401. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45402. if (!ignoreParentClass) {
  45403. _super.prototype._updateCache.call(this);
  45404. }
  45405. this._cache._target.copyFrom(this._getTargetPosition());
  45406. this._cache.alpha = this.alpha;
  45407. this._cache.beta = this.beta;
  45408. this._cache.radius = this.radius;
  45409. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45410. };
  45411. ArcRotateCamera.prototype._getTargetPosition = function () {
  45412. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45413. var pos = this._targetHost.getAbsolutePosition();
  45414. if (this._targetBoundingCenter) {
  45415. pos.addToRef(this._targetBoundingCenter, this._target);
  45416. }
  45417. else {
  45418. this._target.copyFrom(pos);
  45419. }
  45420. }
  45421. var lockedTargetPosition = this._getLockedTargetPosition();
  45422. if (lockedTargetPosition) {
  45423. return lockedTargetPosition;
  45424. }
  45425. return this._target;
  45426. };
  45427. ArcRotateCamera.prototype.storeState = function () {
  45428. this._storedAlpha = this.alpha;
  45429. this._storedBeta = this.beta;
  45430. this._storedRadius = this.radius;
  45431. this._storedTarget = this._getTargetPosition().clone();
  45432. return _super.prototype.storeState.call(this);
  45433. };
  45434. /**
  45435. * Restored camera state. You must call storeState() first
  45436. */
  45437. ArcRotateCamera.prototype._restoreStateValues = function () {
  45438. if (!_super.prototype._restoreStateValues.call(this)) {
  45439. return false;
  45440. }
  45441. this.alpha = this._storedAlpha;
  45442. this.beta = this._storedBeta;
  45443. this.radius = this._storedRadius;
  45444. this.setTarget(this._storedTarget.clone());
  45445. this.inertialAlphaOffset = 0;
  45446. this.inertialBetaOffset = 0;
  45447. this.inertialRadiusOffset = 0;
  45448. this.inertialPanningX = 0;
  45449. this.inertialPanningY = 0;
  45450. return true;
  45451. };
  45452. // Synchronized
  45453. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45454. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45455. return false;
  45456. return this._cache._target.equals(this._getTargetPosition())
  45457. && this._cache.alpha === this.alpha
  45458. && this._cache.beta === this.beta
  45459. && this._cache.radius === this.radius
  45460. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45461. };
  45462. // Methods
  45463. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45464. var _this = this;
  45465. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45466. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45467. this._useCtrlForPanning = useCtrlForPanning;
  45468. this._panningMouseButton = panningMouseButton;
  45469. this.inputs.attachElement(element, noPreventDefault);
  45470. this._reset = function () {
  45471. _this.inertialAlphaOffset = 0;
  45472. _this.inertialBetaOffset = 0;
  45473. _this.inertialRadiusOffset = 0;
  45474. _this.inertialPanningX = 0;
  45475. _this.inertialPanningY = 0;
  45476. };
  45477. };
  45478. ArcRotateCamera.prototype.detachControl = function (element) {
  45479. this.inputs.detachElement(element);
  45480. if (this._reset) {
  45481. this._reset();
  45482. }
  45483. };
  45484. ArcRotateCamera.prototype._checkInputs = function () {
  45485. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45486. if (this._collisionTriggered) {
  45487. return;
  45488. }
  45489. this.inputs.checkInputs();
  45490. // Inertia
  45491. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45492. if (this.getScene().useRightHandedSystem) {
  45493. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45494. }
  45495. else {
  45496. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45497. }
  45498. this.beta += this.inertialBetaOffset;
  45499. this.radius -= this.inertialRadiusOffset;
  45500. this.inertialAlphaOffset *= this.inertia;
  45501. this.inertialBetaOffset *= this.inertia;
  45502. this.inertialRadiusOffset *= this.inertia;
  45503. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45504. this.inertialAlphaOffset = 0;
  45505. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45506. this.inertialBetaOffset = 0;
  45507. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45508. this.inertialRadiusOffset = 0;
  45509. }
  45510. // Panning inertia
  45511. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45512. if (!this._localDirection) {
  45513. this._localDirection = BABYLON.Vector3.Zero();
  45514. this._transformedDirection = BABYLON.Vector3.Zero();
  45515. }
  45516. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45517. this._localDirection.multiplyInPlace(this.panningAxis);
  45518. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45519. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45520. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45521. if (!this.panningAxis.y) {
  45522. this._transformedDirection.y = 0;
  45523. }
  45524. if (!this._targetHost) {
  45525. if (this.panningDistanceLimit) {
  45526. this._transformedDirection.addInPlace(this._target);
  45527. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45528. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45529. this._target.copyFrom(this._transformedDirection);
  45530. }
  45531. }
  45532. else {
  45533. this._target.addInPlace(this._transformedDirection);
  45534. }
  45535. }
  45536. this.inertialPanningX *= this.panningInertia;
  45537. this.inertialPanningY *= this.panningInertia;
  45538. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45539. this.inertialPanningX = 0;
  45540. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45541. this.inertialPanningY = 0;
  45542. }
  45543. // Limits
  45544. this._checkLimits();
  45545. _super.prototype._checkInputs.call(this);
  45546. };
  45547. ArcRotateCamera.prototype._checkLimits = function () {
  45548. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45549. if (this.allowUpsideDown && this.beta > Math.PI) {
  45550. this.beta = this.beta - (2 * Math.PI);
  45551. }
  45552. }
  45553. else {
  45554. if (this.beta < this.lowerBetaLimit) {
  45555. this.beta = this.lowerBetaLimit;
  45556. }
  45557. }
  45558. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45559. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45560. this.beta = this.beta + (2 * Math.PI);
  45561. }
  45562. }
  45563. else {
  45564. if (this.beta > this.upperBetaLimit) {
  45565. this.beta = this.upperBetaLimit;
  45566. }
  45567. }
  45568. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45569. this.alpha = this.lowerAlphaLimit;
  45570. }
  45571. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45572. this.alpha = this.upperAlphaLimit;
  45573. }
  45574. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45575. this.radius = this.lowerRadiusLimit;
  45576. }
  45577. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45578. this.radius = this.upperRadiusLimit;
  45579. }
  45580. };
  45581. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45582. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45583. this.radius = this._computationVector.length();
  45584. if (this.radius === 0) {
  45585. this.radius = 0.0001; // Just to avoid division by zero
  45586. }
  45587. // Alpha
  45588. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45589. if (this._computationVector.z < 0) {
  45590. this.alpha = 2 * Math.PI - this.alpha;
  45591. }
  45592. // Beta
  45593. this.beta = Math.acos(this._computationVector.y / this.radius);
  45594. this._checkLimits();
  45595. };
  45596. ArcRotateCamera.prototype.setPosition = function (position) {
  45597. if (this.position.equals(position)) {
  45598. return;
  45599. }
  45600. this.position.copyFrom(position);
  45601. this.rebuildAnglesAndRadius();
  45602. };
  45603. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45604. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45605. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45606. if (target.getBoundingInfo) {
  45607. if (toBoundingCenter) {
  45608. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45609. }
  45610. else {
  45611. this._targetBoundingCenter = null;
  45612. }
  45613. this._targetHost = target;
  45614. this._target = this._getTargetPosition();
  45615. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45616. }
  45617. else {
  45618. var newTarget = target;
  45619. var currentTarget = this._getTargetPosition();
  45620. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45621. return;
  45622. }
  45623. this._targetHost = null;
  45624. this._target = newTarget;
  45625. this._targetBoundingCenter = null;
  45626. this.onMeshTargetChangedObservable.notifyObservers(null);
  45627. }
  45628. this.rebuildAnglesAndRadius();
  45629. };
  45630. ArcRotateCamera.prototype._getViewMatrix = function () {
  45631. // Compute
  45632. var cosa = Math.cos(this.alpha);
  45633. var sina = Math.sin(this.alpha);
  45634. var cosb = Math.cos(this.beta);
  45635. var sinb = Math.sin(this.beta);
  45636. if (sinb === 0) {
  45637. sinb = 0.0001;
  45638. }
  45639. var target = this._getTargetPosition();
  45640. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45641. target.addToRef(this._computationVector, this._newPosition);
  45642. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45643. if (!this._collider) {
  45644. this._collider = new BABYLON.Collider();
  45645. }
  45646. this._collider._radius = this.collisionRadius;
  45647. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45648. this._collisionTriggered = true;
  45649. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45650. }
  45651. else {
  45652. this.position.copyFrom(this._newPosition);
  45653. var up = this.upVector;
  45654. if (this.allowUpsideDown && sinb < 0) {
  45655. up = up.clone();
  45656. up = up.negate();
  45657. }
  45658. if (this.getScene().useRightHandedSystem) {
  45659. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45660. }
  45661. else {
  45662. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45663. }
  45664. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45665. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45666. }
  45667. this._currentTarget = target;
  45668. return this._viewMatrix;
  45669. };
  45670. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45671. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45672. meshes = meshes || this.getScene().meshes;
  45673. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45674. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45675. this.radius = distance * this.zoomOnFactor;
  45676. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45677. };
  45678. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45679. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45680. var meshesOrMinMaxVector;
  45681. var distance;
  45682. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45683. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45684. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45685. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45686. }
  45687. else {
  45688. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45689. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45690. distance = minMaxVectorAndDistance.distance;
  45691. }
  45692. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45693. if (!doNotUpdateMaxZ) {
  45694. this.maxZ = distance * 2;
  45695. }
  45696. };
  45697. /**
  45698. * @override
  45699. * Override Camera.createRigCamera
  45700. */
  45701. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45702. var alphaShift = 0;
  45703. switch (this.cameraRigMode) {
  45704. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45705. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45706. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45707. case BABYLON.Camera.RIG_MODE_VR:
  45708. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45709. break;
  45710. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45711. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45712. break;
  45713. }
  45714. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45715. rigCam._cameraRigParams = {};
  45716. return rigCam;
  45717. };
  45718. /**
  45719. * @override
  45720. * Override Camera._updateRigCameras
  45721. */
  45722. ArcRotateCamera.prototype._updateRigCameras = function () {
  45723. var camLeft = this._rigCameras[0];
  45724. var camRight = this._rigCameras[1];
  45725. camLeft.beta = camRight.beta = this.beta;
  45726. camLeft.radius = camRight.radius = this.radius;
  45727. switch (this.cameraRigMode) {
  45728. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45729. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45730. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45731. case BABYLON.Camera.RIG_MODE_VR:
  45732. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45733. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45734. break;
  45735. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45736. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45737. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45738. break;
  45739. }
  45740. _super.prototype._updateRigCameras.call(this);
  45741. };
  45742. ArcRotateCamera.prototype.dispose = function () {
  45743. this.inputs.clear();
  45744. _super.prototype.dispose.call(this);
  45745. };
  45746. ArcRotateCamera.prototype.getClassName = function () {
  45747. return "ArcRotateCamera";
  45748. };
  45749. __decorate([
  45750. BABYLON.serialize()
  45751. ], ArcRotateCamera.prototype, "alpha", void 0);
  45752. __decorate([
  45753. BABYLON.serialize()
  45754. ], ArcRotateCamera.prototype, "beta", void 0);
  45755. __decorate([
  45756. BABYLON.serialize()
  45757. ], ArcRotateCamera.prototype, "radius", void 0);
  45758. __decorate([
  45759. BABYLON.serializeAsVector3("target")
  45760. ], ArcRotateCamera.prototype, "_target", void 0);
  45761. __decorate([
  45762. BABYLON.serialize()
  45763. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45764. __decorate([
  45765. BABYLON.serialize()
  45766. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45767. __decorate([
  45768. BABYLON.serialize()
  45769. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45770. __decorate([
  45771. BABYLON.serialize()
  45772. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45773. __decorate([
  45774. BABYLON.serialize()
  45775. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45776. __decorate([
  45777. BABYLON.serialize()
  45778. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45779. __decorate([
  45780. BABYLON.serialize()
  45781. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45782. __decorate([
  45783. BABYLON.serialize()
  45784. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45785. __decorate([
  45786. BABYLON.serialize()
  45787. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45788. __decorate([
  45789. BABYLON.serialize()
  45790. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45791. __decorate([
  45792. BABYLON.serialize()
  45793. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45794. __decorate([
  45795. BABYLON.serialize()
  45796. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45797. __decorate([
  45798. BABYLON.serialize()
  45799. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45800. __decorate([
  45801. BABYLON.serializeAsVector3()
  45802. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45803. __decorate([
  45804. BABYLON.serialize()
  45805. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45806. __decorate([
  45807. BABYLON.serialize()
  45808. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45809. __decorate([
  45810. BABYLON.serialize()
  45811. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45812. return ArcRotateCamera;
  45813. }(BABYLON.TargetCamera));
  45814. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45815. })(BABYLON || (BABYLON = {}));
  45816. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45817. "use strict";
  45818. var BABYLON;
  45819. (function (BABYLON) {
  45820. /**
  45821. * The HemisphericLight simulates the ambient environment light,
  45822. * so the passed direction is the light reflection direction, not the incoming direction.
  45823. */
  45824. var HemisphericLight = /** @class */ (function (_super) {
  45825. __extends(HemisphericLight, _super);
  45826. /**
  45827. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45828. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45829. * The HemisphericLight can't cast shadows.
  45830. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45831. * @param name The friendly name of the light
  45832. * @param direction The direction of the light reflection
  45833. * @param scene The scene the light belongs to
  45834. */
  45835. function HemisphericLight(name, direction, scene) {
  45836. var _this = _super.call(this, name, scene) || this;
  45837. /**
  45838. * The groundColor is the light in the opposite direction to the one specified during creation.
  45839. * 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.
  45840. */
  45841. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45842. _this.direction = direction || BABYLON.Vector3.Up();
  45843. return _this;
  45844. }
  45845. HemisphericLight.prototype._buildUniformLayout = function () {
  45846. this._uniformBuffer.addUniform("vLightData", 4);
  45847. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45848. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45849. this._uniformBuffer.addUniform("vLightGround", 3);
  45850. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45851. this._uniformBuffer.addUniform("depthValues", 2);
  45852. this._uniformBuffer.create();
  45853. };
  45854. /**
  45855. * Returns the string "HemisphericLight".
  45856. * @return The class name
  45857. */
  45858. HemisphericLight.prototype.getClassName = function () {
  45859. return "HemisphericLight";
  45860. };
  45861. /**
  45862. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45863. * Returns the updated direction.
  45864. * @param target The target the direction should point to
  45865. * @return The computed direction
  45866. */
  45867. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45868. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45869. return this.direction;
  45870. };
  45871. /**
  45872. * Returns the shadow generator associated to the light.
  45873. * @returns Always null for hemispheric lights because it does not support shadows.
  45874. */
  45875. HemisphericLight.prototype.getShadowGenerator = function () {
  45876. return null;
  45877. };
  45878. /**
  45879. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45880. * @param effect The effect to update
  45881. * @param lightIndex The index of the light in the effect to update
  45882. * @returns The hemispheric light
  45883. */
  45884. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45885. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45886. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45887. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45888. return this;
  45889. };
  45890. /**
  45891. * @ignore internal use only.
  45892. */
  45893. HemisphericLight.prototype._getWorldMatrix = function () {
  45894. if (!this._worldMatrix) {
  45895. this._worldMatrix = BABYLON.Matrix.Identity();
  45896. }
  45897. return this._worldMatrix;
  45898. };
  45899. /**
  45900. * Returns the integer 3.
  45901. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45902. */
  45903. HemisphericLight.prototype.getTypeID = function () {
  45904. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45905. };
  45906. __decorate([
  45907. BABYLON.serializeAsColor3()
  45908. ], HemisphericLight.prototype, "groundColor", void 0);
  45909. __decorate([
  45910. BABYLON.serializeAsVector3()
  45911. ], HemisphericLight.prototype, "direction", void 0);
  45912. return HemisphericLight;
  45913. }(BABYLON.Light));
  45914. BABYLON.HemisphericLight = HemisphericLight;
  45915. })(BABYLON || (BABYLON = {}));
  45916. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45917. "use strict";
  45918. var BABYLON;
  45919. (function (BABYLON) {
  45920. /**
  45921. * Base implementation of @see IShadowLight
  45922. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45923. */
  45924. var ShadowLight = /** @class */ (function (_super) {
  45925. __extends(ShadowLight, _super);
  45926. function ShadowLight() {
  45927. var _this = _super !== null && _super.apply(this, arguments) || this;
  45928. _this._needProjectionMatrixCompute = true;
  45929. return _this;
  45930. }
  45931. ShadowLight.prototype._setPosition = function (value) {
  45932. this._position = value;
  45933. };
  45934. Object.defineProperty(ShadowLight.prototype, "position", {
  45935. /**
  45936. * Sets the position the shadow will be casted from. Also use as the light position for both
  45937. * point and spot lights.
  45938. */
  45939. get: function () {
  45940. return this._position;
  45941. },
  45942. /**
  45943. * Sets the position the shadow will be casted from. Also use as the light position for both
  45944. * point and spot lights.
  45945. */
  45946. set: function (value) {
  45947. this._setPosition(value);
  45948. },
  45949. enumerable: true,
  45950. configurable: true
  45951. });
  45952. ShadowLight.prototype._setDirection = function (value) {
  45953. this._direction = value;
  45954. };
  45955. Object.defineProperty(ShadowLight.prototype, "direction", {
  45956. /**
  45957. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45958. * Also use as the light direction on spot and directional lights.
  45959. */
  45960. get: function () {
  45961. return this._direction;
  45962. },
  45963. /**
  45964. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45965. * Also use as the light direction on spot and directional lights.
  45966. */
  45967. set: function (value) {
  45968. this._setDirection(value);
  45969. },
  45970. enumerable: true,
  45971. configurable: true
  45972. });
  45973. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45974. /**
  45975. * Gets the shadow projection clipping minimum z value.
  45976. */
  45977. get: function () {
  45978. return this._shadowMinZ;
  45979. },
  45980. /**
  45981. * Sets the shadow projection clipping minimum z value.
  45982. */
  45983. set: function (value) {
  45984. this._shadowMinZ = value;
  45985. this.forceProjectionMatrixCompute();
  45986. },
  45987. enumerable: true,
  45988. configurable: true
  45989. });
  45990. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45991. /**
  45992. * Sets the shadow projection clipping maximum z value.
  45993. */
  45994. get: function () {
  45995. return this._shadowMaxZ;
  45996. },
  45997. /**
  45998. * Gets the shadow projection clipping maximum z value.
  45999. */
  46000. set: function (value) {
  46001. this._shadowMaxZ = value;
  46002. this.forceProjectionMatrixCompute();
  46003. },
  46004. enumerable: true,
  46005. configurable: true
  46006. });
  46007. /**
  46008. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  46009. * @returns true if the information has been computed, false if it does not need to (no parenting)
  46010. */
  46011. ShadowLight.prototype.computeTransformedInformation = function () {
  46012. if (this.parent && this.parent.getWorldMatrix) {
  46013. if (!this.transformedPosition) {
  46014. this.transformedPosition = BABYLON.Vector3.Zero();
  46015. }
  46016. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  46017. // In case the direction is present.
  46018. if (this.direction) {
  46019. if (!this.transformedDirection) {
  46020. this.transformedDirection = BABYLON.Vector3.Zero();
  46021. }
  46022. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  46023. }
  46024. return true;
  46025. }
  46026. return false;
  46027. };
  46028. /**
  46029. * Return the depth scale used for the shadow map.
  46030. * @returns the depth scale.
  46031. */
  46032. ShadowLight.prototype.getDepthScale = function () {
  46033. return 50.0;
  46034. };
  46035. /**
  46036. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  46037. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46038. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46039. */
  46040. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  46041. return this.transformedDirection ? this.transformedDirection : this.direction;
  46042. };
  46043. /**
  46044. * Returns the ShadowLight absolute position in the World.
  46045. * @returns the position vector in world space
  46046. */
  46047. ShadowLight.prototype.getAbsolutePosition = function () {
  46048. return this.transformedPosition ? this.transformedPosition : this.position;
  46049. };
  46050. /**
  46051. * Sets the ShadowLight direction toward the passed target.
  46052. * @param target The point tot target in local space
  46053. * @returns the updated ShadowLight direction
  46054. */
  46055. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46056. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46057. return this.direction;
  46058. };
  46059. /**
  46060. * Returns the light rotation in euler definition.
  46061. * @returns the x y z rotation in local space.
  46062. */
  46063. ShadowLight.prototype.getRotation = function () {
  46064. this.direction.normalize();
  46065. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46066. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46067. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46068. };
  46069. /**
  46070. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46071. * @returns true if a cube texture needs to be use
  46072. */
  46073. ShadowLight.prototype.needCube = function () {
  46074. return false;
  46075. };
  46076. /**
  46077. * Detects if the projection matrix requires to be recomputed this frame.
  46078. * @returns true if it requires to be recomputed otherwise, false.
  46079. */
  46080. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46081. return this._needProjectionMatrixCompute;
  46082. };
  46083. /**
  46084. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46085. */
  46086. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46087. this._needProjectionMatrixCompute = true;
  46088. };
  46089. /**
  46090. * Get the world matrix of the sahdow lights.
  46091. * @ignore Internal Use Only
  46092. */
  46093. ShadowLight.prototype._getWorldMatrix = function () {
  46094. if (!this._worldMatrix) {
  46095. this._worldMatrix = BABYLON.Matrix.Identity();
  46096. }
  46097. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46098. return this._worldMatrix;
  46099. };
  46100. /**
  46101. * Gets the minZ used for shadow according to both the scene and the light.
  46102. * @param activeCamera The camera we are returning the min for
  46103. * @returns the depth min z
  46104. */
  46105. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46106. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46107. };
  46108. /**
  46109. * Gets the maxZ used for shadow according to both the scene and the light.
  46110. * @param activeCamera The camera we are returning the max for
  46111. * @returns the depth max z
  46112. */
  46113. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46114. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46115. };
  46116. /**
  46117. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46118. * @param matrix The materix to updated with the projection information
  46119. * @param viewMatrix The transform matrix of the light
  46120. * @param renderList The list of mesh to render in the map
  46121. * @returns The current light
  46122. */
  46123. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46124. if (this.customProjectionMatrixBuilder) {
  46125. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46126. }
  46127. else {
  46128. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46129. }
  46130. return this;
  46131. };
  46132. __decorate([
  46133. BABYLON.serializeAsVector3()
  46134. ], ShadowLight.prototype, "position", null);
  46135. __decorate([
  46136. BABYLON.serializeAsVector3()
  46137. ], ShadowLight.prototype, "direction", null);
  46138. __decorate([
  46139. BABYLON.serialize()
  46140. ], ShadowLight.prototype, "shadowMinZ", null);
  46141. __decorate([
  46142. BABYLON.serialize()
  46143. ], ShadowLight.prototype, "shadowMaxZ", null);
  46144. return ShadowLight;
  46145. }(BABYLON.Light));
  46146. BABYLON.ShadowLight = ShadowLight;
  46147. })(BABYLON || (BABYLON = {}));
  46148. //# sourceMappingURL=babylon.shadowLight.js.map
  46149. "use strict";
  46150. var BABYLON;
  46151. (function (BABYLON) {
  46152. /**
  46153. * A point light is a light defined by an unique point in world space.
  46154. * The light is emitted in every direction from this point.
  46155. * A good example of a point light is a standard light bulb.
  46156. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46157. */
  46158. var PointLight = /** @class */ (function (_super) {
  46159. __extends(PointLight, _super);
  46160. /**
  46161. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46162. * A PointLight emits the light in every direction.
  46163. * It can cast shadows.
  46164. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46165. * ```javascript
  46166. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46167. * ```
  46168. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46169. * @param name The light friendly name
  46170. * @param position The position of the point light in the scene
  46171. * @param scene The scene the lights belongs to
  46172. */
  46173. function PointLight(name, position, scene) {
  46174. var _this = _super.call(this, name, scene) || this;
  46175. _this._shadowAngle = Math.PI / 2;
  46176. _this.position = position;
  46177. return _this;
  46178. }
  46179. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46180. /**
  46181. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46182. * This specifies what angle the shadow will use to be created.
  46183. *
  46184. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46185. */
  46186. get: function () {
  46187. return this._shadowAngle;
  46188. },
  46189. /**
  46190. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46191. * This specifies what angle the shadow will use to be created.
  46192. *
  46193. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46194. */
  46195. set: function (value) {
  46196. this._shadowAngle = value;
  46197. this.forceProjectionMatrixCompute();
  46198. },
  46199. enumerable: true,
  46200. configurable: true
  46201. });
  46202. Object.defineProperty(PointLight.prototype, "direction", {
  46203. /**
  46204. * Gets the direction if it has been set.
  46205. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46206. */
  46207. get: function () {
  46208. return this._direction;
  46209. },
  46210. /**
  46211. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46212. */
  46213. set: function (value) {
  46214. var previousNeedCube = this.needCube();
  46215. this._direction = value;
  46216. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46217. this._shadowGenerator.recreateShadowMap();
  46218. }
  46219. },
  46220. enumerable: true,
  46221. configurable: true
  46222. });
  46223. /**
  46224. * Returns the string "PointLight"
  46225. * @returns the class name
  46226. */
  46227. PointLight.prototype.getClassName = function () {
  46228. return "PointLight";
  46229. };
  46230. /**
  46231. * Returns the integer 0.
  46232. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46233. */
  46234. PointLight.prototype.getTypeID = function () {
  46235. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46236. };
  46237. /**
  46238. * Specifies wether or not the shadowmap should be a cube texture.
  46239. * @returns true if the shadowmap needs to be a cube texture.
  46240. */
  46241. PointLight.prototype.needCube = function () {
  46242. return !this.direction;
  46243. };
  46244. /**
  46245. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46246. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46247. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46248. */
  46249. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46250. if (this.direction) {
  46251. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46252. }
  46253. else {
  46254. switch (faceIndex) {
  46255. case 0:
  46256. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46257. case 1:
  46258. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46259. case 2:
  46260. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46261. case 3:
  46262. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46263. case 4:
  46264. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46265. case 5:
  46266. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46267. }
  46268. }
  46269. return BABYLON.Vector3.Zero();
  46270. };
  46271. /**
  46272. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46273. * - fov = PI / 2
  46274. * - aspect ratio : 1.0
  46275. * - z-near and far equal to the active camera minZ and maxZ.
  46276. * Returns the PointLight.
  46277. */
  46278. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46279. var activeCamera = this.getScene().activeCamera;
  46280. if (!activeCamera) {
  46281. return;
  46282. }
  46283. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46284. };
  46285. PointLight.prototype._buildUniformLayout = function () {
  46286. this._uniformBuffer.addUniform("vLightData", 4);
  46287. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46288. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46289. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46290. this._uniformBuffer.addUniform("depthValues", 2);
  46291. this._uniformBuffer.create();
  46292. };
  46293. /**
  46294. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46295. * @param effect The effect to update
  46296. * @param lightIndex The index of the light in the effect to update
  46297. * @returns The point light
  46298. */
  46299. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46300. if (this.computeTransformedInformation()) {
  46301. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46302. return this;
  46303. }
  46304. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46305. return this;
  46306. };
  46307. __decorate([
  46308. BABYLON.serialize()
  46309. ], PointLight.prototype, "shadowAngle", null);
  46310. return PointLight;
  46311. }(BABYLON.ShadowLight));
  46312. BABYLON.PointLight = PointLight;
  46313. })(BABYLON || (BABYLON = {}));
  46314. //# sourceMappingURL=babylon.pointLight.js.map
  46315. "use strict";
  46316. var BABYLON;
  46317. (function (BABYLON) {
  46318. /**
  46319. * A directional light is defined by a direction (what a surprise!).
  46320. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46321. * 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.
  46322. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46323. */
  46324. var DirectionalLight = /** @class */ (function (_super) {
  46325. __extends(DirectionalLight, _super);
  46326. /**
  46327. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46328. * The directional light is emitted from everywhere in the given direction.
  46329. * It can cast shawdows.
  46330. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46331. * @param name The friendly name of the light
  46332. * @param direction The direction of the light
  46333. * @param scene The scene the light belongs to
  46334. */
  46335. function DirectionalLight(name, direction, scene) {
  46336. var _this = _super.call(this, name, scene) || this;
  46337. _this._shadowFrustumSize = 0;
  46338. _this._shadowOrthoScale = 0.1;
  46339. /**
  46340. * Automatically compute the projection matrix to best fit (including all the casters)
  46341. * on each frame.
  46342. */
  46343. _this.autoUpdateExtends = true;
  46344. // Cache
  46345. _this._orthoLeft = Number.MAX_VALUE;
  46346. _this._orthoRight = Number.MIN_VALUE;
  46347. _this._orthoTop = Number.MIN_VALUE;
  46348. _this._orthoBottom = Number.MAX_VALUE;
  46349. _this.position = direction.scale(-1.0);
  46350. _this.direction = direction;
  46351. return _this;
  46352. }
  46353. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46354. /**
  46355. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46356. */
  46357. get: function () {
  46358. return this._shadowFrustumSize;
  46359. },
  46360. /**
  46361. * Specifies a fix frustum size for the shadow generation.
  46362. */
  46363. set: function (value) {
  46364. this._shadowFrustumSize = value;
  46365. this.forceProjectionMatrixCompute();
  46366. },
  46367. enumerable: true,
  46368. configurable: true
  46369. });
  46370. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46371. /**
  46372. * Gets the shadow projection scale against the optimal computed one.
  46373. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46374. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46375. */
  46376. get: function () {
  46377. return this._shadowOrthoScale;
  46378. },
  46379. /**
  46380. * Sets the shadow projection scale against the optimal computed one.
  46381. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46382. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46383. */
  46384. set: function (value) {
  46385. this._shadowOrthoScale = value;
  46386. this.forceProjectionMatrixCompute();
  46387. },
  46388. enumerable: true,
  46389. configurable: true
  46390. });
  46391. /**
  46392. * Returns the string "DirectionalLight".
  46393. * @return The class name
  46394. */
  46395. DirectionalLight.prototype.getClassName = function () {
  46396. return "DirectionalLight";
  46397. };
  46398. /**
  46399. * Returns the integer 1.
  46400. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46401. */
  46402. DirectionalLight.prototype.getTypeID = function () {
  46403. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46404. };
  46405. /**
  46406. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46407. * Returns the DirectionalLight Shadow projection matrix.
  46408. */
  46409. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46410. if (this.shadowFrustumSize > 0) {
  46411. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46412. }
  46413. else {
  46414. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46415. }
  46416. };
  46417. /**
  46418. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46419. * Returns the DirectionalLight Shadow projection matrix.
  46420. */
  46421. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46422. var activeCamera = this.getScene().activeCamera;
  46423. if (!activeCamera) {
  46424. return;
  46425. }
  46426. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46427. };
  46428. /**
  46429. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46430. * Returns the DirectionalLight Shadow projection matrix.
  46431. */
  46432. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46433. var activeCamera = this.getScene().activeCamera;
  46434. if (!activeCamera) {
  46435. return;
  46436. }
  46437. // Check extends
  46438. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46439. var tempVector3 = BABYLON.Vector3.Zero();
  46440. this._orthoLeft = Number.MAX_VALUE;
  46441. this._orthoRight = Number.MIN_VALUE;
  46442. this._orthoTop = Number.MIN_VALUE;
  46443. this._orthoBottom = Number.MAX_VALUE;
  46444. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46445. var mesh = renderList[meshIndex];
  46446. if (!mesh) {
  46447. continue;
  46448. }
  46449. var boundingInfo = mesh.getBoundingInfo();
  46450. var boundingBox = boundingInfo.boundingBox;
  46451. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46452. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46453. if (tempVector3.x < this._orthoLeft)
  46454. this._orthoLeft = tempVector3.x;
  46455. if (tempVector3.y < this._orthoBottom)
  46456. this._orthoBottom = tempVector3.y;
  46457. if (tempVector3.x > this._orthoRight)
  46458. this._orthoRight = tempVector3.x;
  46459. if (tempVector3.y > this._orthoTop)
  46460. this._orthoTop = tempVector3.y;
  46461. }
  46462. }
  46463. }
  46464. var xOffset = this._orthoRight - this._orthoLeft;
  46465. var yOffset = this._orthoTop - this._orthoBottom;
  46466. 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);
  46467. };
  46468. DirectionalLight.prototype._buildUniformLayout = function () {
  46469. this._uniformBuffer.addUniform("vLightData", 4);
  46470. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46471. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46472. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46473. this._uniformBuffer.addUniform("depthValues", 2);
  46474. this._uniformBuffer.create();
  46475. };
  46476. /**
  46477. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46478. * @param effect The effect to update
  46479. * @param lightIndex The index of the light in the effect to update
  46480. * @returns The directional light
  46481. */
  46482. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46483. if (this.computeTransformedInformation()) {
  46484. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46485. return this;
  46486. }
  46487. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46488. return this;
  46489. };
  46490. /**
  46491. * Gets the minZ used for shadow according to both the scene and the light.
  46492. *
  46493. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46494. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46495. * @param activeCamera The camera we are returning the min for
  46496. * @returns the depth min z
  46497. */
  46498. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46499. return 1;
  46500. };
  46501. /**
  46502. * Gets the maxZ used for shadow according to both the scene and the light.
  46503. *
  46504. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46505. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46506. * @param activeCamera The camera we are returning the max for
  46507. * @returns the depth max z
  46508. */
  46509. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46510. return 1;
  46511. };
  46512. __decorate([
  46513. BABYLON.serialize()
  46514. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46515. __decorate([
  46516. BABYLON.serialize()
  46517. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46518. __decorate([
  46519. BABYLON.serialize()
  46520. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46521. return DirectionalLight;
  46522. }(BABYLON.ShadowLight));
  46523. BABYLON.DirectionalLight = DirectionalLight;
  46524. })(BABYLON || (BABYLON = {}));
  46525. //# sourceMappingURL=babylon.directionalLight.js.map
  46526. "use strict";
  46527. var BABYLON;
  46528. (function (BABYLON) {
  46529. /**
  46530. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46531. * These values define a cone of light starting from the position, emitting toward the direction.
  46532. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46533. * and the exponent defines the speed of the decay of the light with distance (reach).
  46534. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46535. */
  46536. var SpotLight = /** @class */ (function (_super) {
  46537. __extends(SpotLight, _super);
  46538. /**
  46539. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46540. * It can cast shadows.
  46541. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46542. * @param name The light friendly name
  46543. * @param position The position of the spot light in the scene
  46544. * @param direction The direction of the light in the scene
  46545. * @param angle The cone angle of the light in Radians
  46546. * @param exponent The light decay speed with the distance from the emission spot
  46547. * @param scene The scene the lights belongs to
  46548. */
  46549. function SpotLight(name, position, direction, angle, exponent, scene) {
  46550. var _this = _super.call(this, name, scene) || this;
  46551. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46552. _this._projectionTextureLightNear = 1e-6;
  46553. _this._projectionTextureLightFar = 1000.0;
  46554. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46555. _this._projectionTextureViewLightDirty = true;
  46556. _this._projectionTextureProjectionLightDirty = true;
  46557. _this._projectionTextureDirty = true;
  46558. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46559. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46560. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46561. _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);
  46562. _this.position = position;
  46563. _this.direction = direction;
  46564. _this.angle = angle;
  46565. _this.exponent = exponent;
  46566. return _this;
  46567. }
  46568. Object.defineProperty(SpotLight.prototype, "angle", {
  46569. /**
  46570. * Gets the cone angle of the spot light in Radians.
  46571. */
  46572. get: function () {
  46573. return this._angle;
  46574. },
  46575. /**
  46576. * Sets the cone angle of the spot light in Radians.
  46577. */
  46578. set: function (value) {
  46579. this._angle = value;
  46580. this._projectionTextureProjectionLightDirty = true;
  46581. this.forceProjectionMatrixCompute();
  46582. },
  46583. enumerable: true,
  46584. configurable: true
  46585. });
  46586. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46587. /**
  46588. * Allows scaling the angle of the light for shadow generation only.
  46589. */
  46590. get: function () {
  46591. return this._shadowAngleScale;
  46592. },
  46593. /**
  46594. * Allows scaling the angle of the light for shadow generation only.
  46595. */
  46596. set: function (value) {
  46597. this._shadowAngleScale = value;
  46598. this.forceProjectionMatrixCompute();
  46599. },
  46600. enumerable: true,
  46601. configurable: true
  46602. });
  46603. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46604. /**
  46605. * Allows reading the projecton texture
  46606. */
  46607. get: function () {
  46608. return this._projectionTextureMatrix;
  46609. },
  46610. enumerable: true,
  46611. configurable: true
  46612. });
  46613. ;
  46614. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46615. /**
  46616. * Gets the near clip of the Spotlight for texture projection.
  46617. */
  46618. get: function () {
  46619. return this._projectionTextureLightNear;
  46620. },
  46621. /**
  46622. * Sets the near clip of the Spotlight for texture projection.
  46623. */
  46624. set: function (value) {
  46625. this._projectionTextureLightNear = value;
  46626. this._projectionTextureProjectionLightDirty = true;
  46627. },
  46628. enumerable: true,
  46629. configurable: true
  46630. });
  46631. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46632. /**
  46633. * Gets the far clip of the Spotlight for texture projection.
  46634. */
  46635. get: function () {
  46636. return this._projectionTextureLightFar;
  46637. },
  46638. /**
  46639. * Sets the far clip of the Spotlight for texture projection.
  46640. */
  46641. set: function (value) {
  46642. this._projectionTextureLightFar = value;
  46643. this._projectionTextureProjectionLightDirty = true;
  46644. },
  46645. enumerable: true,
  46646. configurable: true
  46647. });
  46648. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46649. /**
  46650. * Gets the Up vector of the Spotlight for texture projection.
  46651. */
  46652. get: function () {
  46653. return this._projectionTextureUpDirection;
  46654. },
  46655. /**
  46656. * Sets the Up vector of the Spotlight for texture projection.
  46657. */
  46658. set: function (value) {
  46659. this._projectionTextureUpDirection = value;
  46660. this._projectionTextureProjectionLightDirty = true;
  46661. },
  46662. enumerable: true,
  46663. configurable: true
  46664. });
  46665. ;
  46666. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46667. /**
  46668. * Gets the projection texture of the light.
  46669. */
  46670. get: function () {
  46671. return this._projectionTexture;
  46672. },
  46673. /**
  46674. * Sets the projection texture of the light.
  46675. */
  46676. set: function (value) {
  46677. this._projectionTexture = value;
  46678. this._projectionTextureDirty = true;
  46679. },
  46680. enumerable: true,
  46681. configurable: true
  46682. });
  46683. /**
  46684. * Returns the string "SpotLight".
  46685. * @returns the class name
  46686. */
  46687. SpotLight.prototype.getClassName = function () {
  46688. return "SpotLight";
  46689. };
  46690. /**
  46691. * Returns the integer 2.
  46692. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46693. */
  46694. SpotLight.prototype.getTypeID = function () {
  46695. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46696. };
  46697. /**
  46698. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46699. */
  46700. SpotLight.prototype._setDirection = function (value) {
  46701. _super.prototype._setDirection.call(this, value);
  46702. this._projectionTextureViewLightDirty = true;
  46703. };
  46704. /**
  46705. * Overrides the position setter to recompute the projection texture view light Matrix.
  46706. */
  46707. SpotLight.prototype._setPosition = function (value) {
  46708. _super.prototype._setPosition.call(this, value);
  46709. this._projectionTextureViewLightDirty = true;
  46710. };
  46711. /**
  46712. * 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.
  46713. * Returns the SpotLight.
  46714. */
  46715. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46716. var activeCamera = this.getScene().activeCamera;
  46717. if (!activeCamera) {
  46718. return;
  46719. }
  46720. this._shadowAngleScale = this._shadowAngleScale || 1;
  46721. var angle = this._shadowAngleScale * this._angle;
  46722. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46723. };
  46724. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46725. this._projectionTextureViewLightDirty = false;
  46726. this._projectionTextureDirty = true;
  46727. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46728. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46729. };
  46730. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46731. this._projectionTextureProjectionLightDirty = false;
  46732. this._projectionTextureDirty = true;
  46733. var light_far = this.projectionTextureLightFar;
  46734. var light_near = this.projectionTextureLightNear;
  46735. var P = light_far / (light_far - light_near);
  46736. var Q = -P * light_near;
  46737. var S = 1.0 / Math.tan(this._angle / 2.0);
  46738. var A = 1.0;
  46739. 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);
  46740. };
  46741. /**
  46742. * Main function for light texture projection matrix computing.
  46743. */
  46744. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46745. this._projectionTextureDirty = false;
  46746. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46747. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46748. };
  46749. SpotLight.prototype._buildUniformLayout = function () {
  46750. this._uniformBuffer.addUniform("vLightData", 4);
  46751. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46752. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46753. this._uniformBuffer.addUniform("vLightDirection", 3);
  46754. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46755. this._uniformBuffer.addUniform("depthValues", 2);
  46756. this._uniformBuffer.create();
  46757. };
  46758. /**
  46759. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46760. * @param effect The effect to update
  46761. * @param lightIndex The index of the light in the effect to update
  46762. * @returns The spot light
  46763. */
  46764. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46765. var normalizeDirection;
  46766. if (this.computeTransformedInformation()) {
  46767. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46768. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46769. }
  46770. else {
  46771. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46772. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46773. }
  46774. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46775. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46776. if (this._projectionTextureViewLightDirty) {
  46777. this._computeProjectionTextureViewLightMatrix();
  46778. }
  46779. if (this._projectionTextureProjectionLightDirty) {
  46780. this._computeProjectionTextureProjectionLightMatrix();
  46781. }
  46782. if (this._projectionTextureDirty) {
  46783. this._computeProjectionTextureMatrix();
  46784. }
  46785. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46786. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46787. }
  46788. return this;
  46789. };
  46790. /**
  46791. * Disposes the light and the associated resources.
  46792. */
  46793. SpotLight.prototype.dispose = function () {
  46794. _super.prototype.dispose.call(this);
  46795. if (this._projectionTexture) {
  46796. this._projectionTexture.dispose();
  46797. }
  46798. };
  46799. __decorate([
  46800. BABYLON.serialize()
  46801. ], SpotLight.prototype, "angle", null);
  46802. __decorate([
  46803. BABYLON.serialize()
  46804. ], SpotLight.prototype, "shadowAngleScale", null);
  46805. __decorate([
  46806. BABYLON.serialize()
  46807. ], SpotLight.prototype, "exponent", void 0);
  46808. __decorate([
  46809. BABYLON.serialize()
  46810. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46811. __decorate([
  46812. BABYLON.serialize()
  46813. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46814. __decorate([
  46815. BABYLON.serialize()
  46816. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46817. __decorate([
  46818. BABYLON.serializeAsTexture("projectedLightTexture")
  46819. ], SpotLight.prototype, "_projectionTexture", void 0);
  46820. return SpotLight;
  46821. }(BABYLON.ShadowLight));
  46822. BABYLON.SpotLight = SpotLight;
  46823. })(BABYLON || (BABYLON = {}));
  46824. //# sourceMappingURL=babylon.spotLight.js.map
  46825. "use strict";
  46826. var BABYLON;
  46827. (function (BABYLON) {
  46828. /**
  46829. * Class used to override all child animations of a given target
  46830. */
  46831. var AnimationPropertiesOverride = /** @class */ (function () {
  46832. function AnimationPropertiesOverride() {
  46833. /**
  46834. * Gets or sets a value indicating if animation blending must be used
  46835. */
  46836. this.enableBlending = false;
  46837. /**
  46838. * Gets or sets the blending speed to use when enableBlending is true
  46839. */
  46840. this.blendingSpeed = 0.01;
  46841. /**
  46842. * Gets or sets the default loop mode to use
  46843. */
  46844. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46845. }
  46846. return AnimationPropertiesOverride;
  46847. }());
  46848. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46849. })(BABYLON || (BABYLON = {}));
  46850. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46851. "use strict";
  46852. var BABYLON;
  46853. (function (BABYLON) {
  46854. var AnimationRange = /** @class */ (function () {
  46855. function AnimationRange(name, from, to) {
  46856. this.name = name;
  46857. this.from = from;
  46858. this.to = to;
  46859. }
  46860. AnimationRange.prototype.clone = function () {
  46861. return new AnimationRange(this.name, this.from, this.to);
  46862. };
  46863. return AnimationRange;
  46864. }());
  46865. BABYLON.AnimationRange = AnimationRange;
  46866. /**
  46867. * Composed of a frame, and an action function
  46868. */
  46869. var AnimationEvent = /** @class */ (function () {
  46870. function AnimationEvent(frame, action, onlyOnce) {
  46871. this.frame = frame;
  46872. this.action = action;
  46873. this.onlyOnce = onlyOnce;
  46874. this.isDone = false;
  46875. }
  46876. return AnimationEvent;
  46877. }());
  46878. BABYLON.AnimationEvent = AnimationEvent;
  46879. var PathCursor = /** @class */ (function () {
  46880. function PathCursor(path) {
  46881. this.path = path;
  46882. this._onchange = new Array();
  46883. this.value = 0;
  46884. this.animations = new Array();
  46885. }
  46886. PathCursor.prototype.getPoint = function () {
  46887. var point = this.path.getPointAtLengthPosition(this.value);
  46888. return new BABYLON.Vector3(point.x, 0, point.y);
  46889. };
  46890. PathCursor.prototype.moveAhead = function (step) {
  46891. if (step === void 0) { step = 0.002; }
  46892. this.move(step);
  46893. return this;
  46894. };
  46895. PathCursor.prototype.moveBack = function (step) {
  46896. if (step === void 0) { step = 0.002; }
  46897. this.move(-step);
  46898. return this;
  46899. };
  46900. PathCursor.prototype.move = function (step) {
  46901. if (Math.abs(step) > 1) {
  46902. throw "step size should be less than 1.";
  46903. }
  46904. this.value += step;
  46905. this.ensureLimits();
  46906. this.raiseOnChange();
  46907. return this;
  46908. };
  46909. PathCursor.prototype.ensureLimits = function () {
  46910. while (this.value > 1) {
  46911. this.value -= 1;
  46912. }
  46913. while (this.value < 0) {
  46914. this.value += 1;
  46915. }
  46916. return this;
  46917. };
  46918. // used by animation engine
  46919. PathCursor.prototype.raiseOnChange = function () {
  46920. var _this = this;
  46921. this._onchange.forEach(function (f) { return f(_this); });
  46922. return this;
  46923. };
  46924. PathCursor.prototype.onchange = function (f) {
  46925. this._onchange.push(f);
  46926. return this;
  46927. };
  46928. return PathCursor;
  46929. }());
  46930. BABYLON.PathCursor = PathCursor;
  46931. var AnimationKeyInterpolation;
  46932. (function (AnimationKeyInterpolation) {
  46933. /**
  46934. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46935. */
  46936. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46937. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46938. var Animation = /** @class */ (function () {
  46939. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46940. this.name = name;
  46941. this.targetProperty = targetProperty;
  46942. this.framePerSecond = framePerSecond;
  46943. this.dataType = dataType;
  46944. this.loopMode = loopMode;
  46945. this.enableBlending = enableBlending;
  46946. this._runtimeAnimations = new Array();
  46947. // The set of event that will be linked to this animation
  46948. this._events = new Array();
  46949. this.blendingSpeed = 0.01;
  46950. this._ranges = {};
  46951. this.targetPropertyPath = targetProperty.split(".");
  46952. this.dataType = dataType;
  46953. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46954. }
  46955. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46956. var dataType = undefined;
  46957. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46958. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46959. }
  46960. else if (from instanceof BABYLON.Quaternion) {
  46961. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46962. }
  46963. else if (from instanceof BABYLON.Vector3) {
  46964. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46965. }
  46966. else if (from instanceof BABYLON.Vector2) {
  46967. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46968. }
  46969. else if (from instanceof BABYLON.Color3) {
  46970. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46971. }
  46972. else if (from instanceof BABYLON.Size) {
  46973. dataType = Animation.ANIMATIONTYPE_SIZE;
  46974. }
  46975. if (dataType == undefined) {
  46976. return null;
  46977. }
  46978. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46979. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46980. animation.setKeys(keys);
  46981. if (easingFunction !== undefined) {
  46982. animation.setEasingFunction(easingFunction);
  46983. }
  46984. return animation;
  46985. };
  46986. /**
  46987. * Sets up an animation.
  46988. * @param property the property to animate
  46989. * @param animationType the animation type to apply
  46990. * @param easingFunction the easing function used in the animation
  46991. * @returns The created animation
  46992. */
  46993. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46994. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46995. animation.setEasingFunction(easingFunction);
  46996. return animation;
  46997. };
  46998. /**
  46999. * Create and start an animation on a node
  47000. * @param {string} name defines the name of the global animation that will be run on all nodes
  47001. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47002. * @param {string} targetProperty defines property to animate
  47003. * @param {number} framePerSecond defines the number of frame per second yo use
  47004. * @param {number} totalFrame defines the number of frames in total
  47005. * @param {any} from defines the initial value
  47006. * @param {any} to defines the final value
  47007. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47008. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47009. * @param onAnimationEnd defines the callback to call when animation end
  47010. * @returns the animatable created for this animation
  47011. */
  47012. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47013. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47014. if (!animation) {
  47015. return null;
  47016. }
  47017. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47018. };
  47019. /**
  47020. * Create and start an animation on a node and its descendants
  47021. * @param {string} name defines the name of the global animation that will be run on all nodes
  47022. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47023. * @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.
  47024. * @param {string} targetProperty defines property to animate
  47025. * @param {number} framePerSecond defines the number of frame per second yo use
  47026. * @param {number} totalFrame defines the number of frames in total
  47027. * @param {any} from defines the initial value
  47028. * @param {any} to defines the final value
  47029. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47030. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47031. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  47032. * @returns the list of animatables created for all nodes
  47033. * @example https://www.babylonjs-playground.com/#MH0VLI
  47034. */
  47035. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47036. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47037. if (!animation) {
  47038. return null;
  47039. }
  47040. var scene = node.getScene();
  47041. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47042. };
  47043. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47044. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47045. if (!animation) {
  47046. return null;
  47047. }
  47048. node.animations.push(animation);
  47049. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47050. };
  47051. /**
  47052. * Transition property of the Camera to the target Value.
  47053. * @param property The property to transition
  47054. * @param targetValue The target Value of the property
  47055. * @param host The object where the property to animate belongs
  47056. * @param scene Scene used to run the animation
  47057. * @param frameRate Framerate (in frame/s) to use
  47058. * @param transition The transition type we want to use
  47059. * @param duration The duration of the animation, in milliseconds
  47060. * @param onAnimationEnd Call back trigger at the end of the animation.
  47061. */
  47062. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47063. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47064. if (duration <= 0) {
  47065. host[property] = targetValue;
  47066. if (onAnimationEnd) {
  47067. onAnimationEnd();
  47068. }
  47069. return null;
  47070. }
  47071. var endFrame = frameRate * (duration / 1000);
  47072. transition.setKeys([{
  47073. frame: 0,
  47074. value: host[property].clone ? host[property].clone() : host[property]
  47075. },
  47076. {
  47077. frame: endFrame,
  47078. value: targetValue
  47079. }]);
  47080. if (!host.animations) {
  47081. host.animations = [];
  47082. }
  47083. host.animations.push(transition);
  47084. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47085. animation.onAnimationEnd = onAnimationEnd;
  47086. return animation;
  47087. };
  47088. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47089. /**
  47090. * Return the array of runtime animations currently using this animation
  47091. */
  47092. get: function () {
  47093. return this._runtimeAnimations;
  47094. },
  47095. enumerable: true,
  47096. configurable: true
  47097. });
  47098. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47099. get: function () {
  47100. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47101. var runtimeAnimation = _a[_i];
  47102. if (!runtimeAnimation.isStopped) {
  47103. return true;
  47104. }
  47105. }
  47106. return false;
  47107. },
  47108. enumerable: true,
  47109. configurable: true
  47110. });
  47111. // Methods
  47112. /**
  47113. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47114. */
  47115. Animation.prototype.toString = function (fullDetails) {
  47116. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47117. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47118. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47119. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47120. if (fullDetails) {
  47121. ret += ", Ranges: {";
  47122. var first = true;
  47123. for (var name in this._ranges) {
  47124. if (first) {
  47125. ret += ", ";
  47126. first = false;
  47127. }
  47128. ret += name;
  47129. }
  47130. ret += "}";
  47131. }
  47132. return ret;
  47133. };
  47134. /**
  47135. * Add an event to this animation.
  47136. */
  47137. Animation.prototype.addEvent = function (event) {
  47138. this._events.push(event);
  47139. };
  47140. /**
  47141. * Remove all events found at the given frame
  47142. * @param frame
  47143. */
  47144. Animation.prototype.removeEvents = function (frame) {
  47145. for (var index = 0; index < this._events.length; index++) {
  47146. if (this._events[index].frame === frame) {
  47147. this._events.splice(index, 1);
  47148. index--;
  47149. }
  47150. }
  47151. };
  47152. Animation.prototype.getEvents = function () {
  47153. return this._events;
  47154. };
  47155. Animation.prototype.createRange = function (name, from, to) {
  47156. // check name not already in use; could happen for bones after serialized
  47157. if (!this._ranges[name]) {
  47158. this._ranges[name] = new AnimationRange(name, from, to);
  47159. }
  47160. };
  47161. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47162. if (deleteFrames === void 0) { deleteFrames = true; }
  47163. var range = this._ranges[name];
  47164. if (!range) {
  47165. return;
  47166. }
  47167. if (deleteFrames) {
  47168. var from = range.from;
  47169. var to = range.to;
  47170. // this loop MUST go high to low for multiple splices to work
  47171. for (var key = this._keys.length - 1; key >= 0; key--) {
  47172. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47173. this._keys.splice(key, 1);
  47174. }
  47175. }
  47176. }
  47177. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47178. };
  47179. Animation.prototype.getRange = function (name) {
  47180. return this._ranges[name];
  47181. };
  47182. Animation.prototype.getKeys = function () {
  47183. return this._keys;
  47184. };
  47185. Animation.prototype.getHighestFrame = function () {
  47186. var ret = 0;
  47187. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47188. if (ret < this._keys[key].frame) {
  47189. ret = this._keys[key].frame;
  47190. }
  47191. }
  47192. return ret;
  47193. };
  47194. Animation.prototype.getEasingFunction = function () {
  47195. return this._easingFunction;
  47196. };
  47197. Animation.prototype.setEasingFunction = function (easingFunction) {
  47198. this._easingFunction = easingFunction;
  47199. };
  47200. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47201. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47202. };
  47203. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47204. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47205. };
  47206. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47207. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47208. };
  47209. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47210. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47211. };
  47212. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47213. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47214. };
  47215. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47216. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47217. };
  47218. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47219. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47220. };
  47221. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47222. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47223. };
  47224. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47225. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47226. };
  47227. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47228. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47229. };
  47230. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47231. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47232. };
  47233. Animation.prototype.clone = function () {
  47234. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47235. clone.enableBlending = this.enableBlending;
  47236. clone.blendingSpeed = this.blendingSpeed;
  47237. if (this._keys) {
  47238. clone.setKeys(this._keys);
  47239. }
  47240. if (this._ranges) {
  47241. clone._ranges = {};
  47242. for (var name in this._ranges) {
  47243. var range = this._ranges[name];
  47244. if (!range) {
  47245. continue;
  47246. }
  47247. clone._ranges[name] = range.clone();
  47248. }
  47249. }
  47250. return clone;
  47251. };
  47252. Animation.prototype.setKeys = function (values) {
  47253. this._keys = values.slice(0);
  47254. };
  47255. Animation.prototype.serialize = function () {
  47256. var serializationObject = {};
  47257. serializationObject.name = this.name;
  47258. serializationObject.property = this.targetProperty;
  47259. serializationObject.framePerSecond = this.framePerSecond;
  47260. serializationObject.dataType = this.dataType;
  47261. serializationObject.loopBehavior = this.loopMode;
  47262. serializationObject.enableBlending = this.enableBlending;
  47263. serializationObject.blendingSpeed = this.blendingSpeed;
  47264. var dataType = this.dataType;
  47265. serializationObject.keys = [];
  47266. var keys = this.getKeys();
  47267. for (var index = 0; index < keys.length; index++) {
  47268. var animationKey = keys[index];
  47269. var key = {};
  47270. key.frame = animationKey.frame;
  47271. switch (dataType) {
  47272. case Animation.ANIMATIONTYPE_FLOAT:
  47273. key.values = [animationKey.value];
  47274. break;
  47275. case Animation.ANIMATIONTYPE_QUATERNION:
  47276. case Animation.ANIMATIONTYPE_MATRIX:
  47277. case Animation.ANIMATIONTYPE_VECTOR3:
  47278. case Animation.ANIMATIONTYPE_COLOR3:
  47279. key.values = animationKey.value.asArray();
  47280. break;
  47281. }
  47282. serializationObject.keys.push(key);
  47283. }
  47284. serializationObject.ranges = [];
  47285. for (var name in this._ranges) {
  47286. var source = this._ranges[name];
  47287. if (!source) {
  47288. continue;
  47289. }
  47290. var range = {};
  47291. range.name = name;
  47292. range.from = source.from;
  47293. range.to = source.to;
  47294. serializationObject.ranges.push(range);
  47295. }
  47296. return serializationObject;
  47297. };
  47298. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47299. get: function () {
  47300. return Animation._ANIMATIONTYPE_FLOAT;
  47301. },
  47302. enumerable: true,
  47303. configurable: true
  47304. });
  47305. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47306. get: function () {
  47307. return Animation._ANIMATIONTYPE_VECTOR3;
  47308. },
  47309. enumerable: true,
  47310. configurable: true
  47311. });
  47312. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47313. get: function () {
  47314. return Animation._ANIMATIONTYPE_VECTOR2;
  47315. },
  47316. enumerable: true,
  47317. configurable: true
  47318. });
  47319. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47320. get: function () {
  47321. return Animation._ANIMATIONTYPE_SIZE;
  47322. },
  47323. enumerable: true,
  47324. configurable: true
  47325. });
  47326. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47327. get: function () {
  47328. return Animation._ANIMATIONTYPE_QUATERNION;
  47329. },
  47330. enumerable: true,
  47331. configurable: true
  47332. });
  47333. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47334. get: function () {
  47335. return Animation._ANIMATIONTYPE_MATRIX;
  47336. },
  47337. enumerable: true,
  47338. configurable: true
  47339. });
  47340. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47341. get: function () {
  47342. return Animation._ANIMATIONTYPE_COLOR3;
  47343. },
  47344. enumerable: true,
  47345. configurable: true
  47346. });
  47347. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47348. get: function () {
  47349. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47350. },
  47351. enumerable: true,
  47352. configurable: true
  47353. });
  47354. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47355. get: function () {
  47356. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47357. },
  47358. enumerable: true,
  47359. configurable: true
  47360. });
  47361. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47362. get: function () {
  47363. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47364. },
  47365. enumerable: true,
  47366. configurable: true
  47367. });
  47368. Animation.Parse = function (parsedAnimation) {
  47369. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47370. var dataType = parsedAnimation.dataType;
  47371. var keys = [];
  47372. var data;
  47373. var index;
  47374. if (parsedAnimation.enableBlending) {
  47375. animation.enableBlending = parsedAnimation.enableBlending;
  47376. }
  47377. if (parsedAnimation.blendingSpeed) {
  47378. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47379. }
  47380. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47381. var key = parsedAnimation.keys[index];
  47382. var inTangent;
  47383. var outTangent;
  47384. switch (dataType) {
  47385. case Animation.ANIMATIONTYPE_FLOAT:
  47386. data = key.values[0];
  47387. if (key.values.length >= 1) {
  47388. inTangent = key.values[1];
  47389. }
  47390. if (key.values.length >= 2) {
  47391. outTangent = key.values[2];
  47392. }
  47393. break;
  47394. case Animation.ANIMATIONTYPE_QUATERNION:
  47395. data = BABYLON.Quaternion.FromArray(key.values);
  47396. if (key.values.length >= 8) {
  47397. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47398. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47399. inTangent = _inTangent;
  47400. }
  47401. }
  47402. if (key.values.length >= 12) {
  47403. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47404. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47405. outTangent = _outTangent;
  47406. }
  47407. }
  47408. break;
  47409. case Animation.ANIMATIONTYPE_MATRIX:
  47410. data = BABYLON.Matrix.FromArray(key.values);
  47411. break;
  47412. case Animation.ANIMATIONTYPE_COLOR3:
  47413. data = BABYLON.Color3.FromArray(key.values);
  47414. break;
  47415. case Animation.ANIMATIONTYPE_VECTOR3:
  47416. default:
  47417. data = BABYLON.Vector3.FromArray(key.values);
  47418. break;
  47419. }
  47420. var keyData = {};
  47421. keyData.frame = key.frame;
  47422. keyData.value = data;
  47423. if (inTangent != undefined) {
  47424. keyData.inTangent = inTangent;
  47425. }
  47426. if (outTangent != undefined) {
  47427. keyData.outTangent = outTangent;
  47428. }
  47429. keys.push(keyData);
  47430. }
  47431. animation.setKeys(keys);
  47432. if (parsedAnimation.ranges) {
  47433. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47434. data = parsedAnimation.ranges[index];
  47435. animation.createRange(data.name, data.from, data.to);
  47436. }
  47437. }
  47438. return animation;
  47439. };
  47440. Animation.AppendSerializedAnimations = function (source, destination) {
  47441. if (source.animations) {
  47442. destination.animations = [];
  47443. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47444. var animation = source.animations[animationIndex];
  47445. destination.animations.push(animation.serialize());
  47446. }
  47447. }
  47448. };
  47449. Animation.AllowMatricesInterpolation = false;
  47450. // Statics
  47451. Animation._ANIMATIONTYPE_FLOAT = 0;
  47452. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47453. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47454. Animation._ANIMATIONTYPE_MATRIX = 3;
  47455. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47456. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47457. Animation._ANIMATIONTYPE_SIZE = 6;
  47458. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47459. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47460. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47461. return Animation;
  47462. }());
  47463. BABYLON.Animation = Animation;
  47464. })(BABYLON || (BABYLON = {}));
  47465. //# sourceMappingURL=babylon.animation.js.map
  47466. "use strict";
  47467. var BABYLON;
  47468. (function (BABYLON) {
  47469. /**
  47470. * This class defines the direct association between an animation and a target
  47471. */
  47472. var TargetedAnimation = /** @class */ (function () {
  47473. function TargetedAnimation() {
  47474. }
  47475. return TargetedAnimation;
  47476. }());
  47477. BABYLON.TargetedAnimation = TargetedAnimation;
  47478. /**
  47479. * Use this class to create coordinated animations on multiple targets
  47480. */
  47481. var AnimationGroup = /** @class */ (function () {
  47482. function AnimationGroup(name, scene) {
  47483. if (scene === void 0) { scene = null; }
  47484. this.name = name;
  47485. this._targetedAnimations = new Array();
  47486. this._animatables = new Array();
  47487. this._from = Number.MAX_VALUE;
  47488. this._to = -Number.MAX_VALUE;
  47489. this._speedRatio = 1;
  47490. this.onAnimationEndObservable = new BABYLON.Observable();
  47491. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47492. this._scene.animationGroups.push(this);
  47493. }
  47494. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47495. /**
  47496. * Define if the animations are started
  47497. */
  47498. get: function () {
  47499. return this._isStarted;
  47500. },
  47501. enumerable: true,
  47502. configurable: true
  47503. });
  47504. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47505. /**
  47506. * Gets or sets the speed ratio to use for all animations
  47507. */
  47508. get: function () {
  47509. return this._speedRatio;
  47510. },
  47511. /**
  47512. * Gets or sets the speed ratio to use for all animations
  47513. */
  47514. set: function (value) {
  47515. if (this._speedRatio === value) {
  47516. return;
  47517. }
  47518. this._speedRatio = value;
  47519. for (var index = 0; index < this._animatables.length; index++) {
  47520. var animatable = this._animatables[index];
  47521. animatable.speedRatio = this._speedRatio;
  47522. }
  47523. },
  47524. enumerable: true,
  47525. configurable: true
  47526. });
  47527. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47528. /**
  47529. * Gets the targeted animations for this animation group
  47530. */
  47531. get: function () {
  47532. return this._targetedAnimations;
  47533. },
  47534. enumerable: true,
  47535. configurable: true
  47536. });
  47537. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47538. /**
  47539. * returning the list of animatables controlled by this animation group.
  47540. */
  47541. get: function () {
  47542. return this._animatables;
  47543. },
  47544. enumerable: true,
  47545. configurable: true
  47546. });
  47547. /**
  47548. * Add an animation (with its target) in the group
  47549. * @param animation defines the animation we want to add
  47550. * @param target defines the target of the animation
  47551. * @returns the {BABYLON.TargetedAnimation} object
  47552. */
  47553. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47554. var targetedAnimation = {
  47555. animation: animation,
  47556. target: target
  47557. };
  47558. var keys = animation.getKeys();
  47559. if (this._from > keys[0].frame) {
  47560. this._from = keys[0].frame;
  47561. }
  47562. if (this._to < keys[keys.length - 1].frame) {
  47563. this._to = keys[keys.length - 1].frame;
  47564. }
  47565. this._targetedAnimations.push(targetedAnimation);
  47566. return targetedAnimation;
  47567. };
  47568. /**
  47569. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47570. * It can add constant keys at begin or end
  47571. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47572. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47573. */
  47574. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47575. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47576. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47577. beginFrame = Math.max(beginFrame, this._from);
  47578. endFrame = Math.min(endFrame, this._to);
  47579. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47580. var targetedAnimation = this._targetedAnimations[index];
  47581. var keys = targetedAnimation.animation.getKeys();
  47582. var startKey = keys[0];
  47583. var endKey = keys[keys.length - 1];
  47584. if (startKey.frame > beginFrame) {
  47585. var newKey = {
  47586. frame: beginFrame,
  47587. value: startKey.value,
  47588. inTangent: startKey.inTangent,
  47589. outTangent: startKey.outTangent,
  47590. interpolation: startKey.interpolation
  47591. };
  47592. keys.splice(0, 0, newKey);
  47593. }
  47594. if (endKey.frame < endFrame) {
  47595. var newKey = {
  47596. frame: endFrame,
  47597. value: endKey.value,
  47598. inTangent: endKey.outTangent,
  47599. outTangent: endKey.outTangent,
  47600. interpolation: endKey.interpolation
  47601. };
  47602. keys.push(newKey);
  47603. }
  47604. }
  47605. return this;
  47606. };
  47607. /**
  47608. * Start all animations on given targets
  47609. * @param loop defines if animations must loop
  47610. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47611. */
  47612. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47613. var _this = this;
  47614. if (loop === void 0) { loop = false; }
  47615. if (speedRatio === void 0) { speedRatio = 1; }
  47616. if (this._isStarted || this._targetedAnimations.length === 0) {
  47617. return this;
  47618. }
  47619. var _loop_1 = function () {
  47620. var targetedAnimation = this_1._targetedAnimations[index];
  47621. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47622. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47623. }));
  47624. };
  47625. var this_1 = this;
  47626. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47627. _loop_1();
  47628. }
  47629. this._speedRatio = speedRatio;
  47630. this._isStarted = true;
  47631. return this;
  47632. };
  47633. /**
  47634. * Pause all animations
  47635. */
  47636. AnimationGroup.prototype.pause = function () {
  47637. if (!this._isStarted) {
  47638. return this;
  47639. }
  47640. for (var index = 0; index < this._animatables.length; index++) {
  47641. var animatable = this._animatables[index];
  47642. animatable.pause();
  47643. }
  47644. return this;
  47645. };
  47646. /**
  47647. * Play all animations to initial state
  47648. * This function will start() the animations if they were not started or will restart() them if they were paused
  47649. * @param loop defines if animations must loop
  47650. */
  47651. AnimationGroup.prototype.play = function (loop) {
  47652. if (this.isStarted) {
  47653. if (loop !== undefined) {
  47654. for (var index = 0; index < this._animatables.length; index++) {
  47655. var animatable = this._animatables[index];
  47656. animatable.loopAnimation = loop;
  47657. }
  47658. }
  47659. this.restart();
  47660. }
  47661. else {
  47662. this.start(loop, this._speedRatio);
  47663. }
  47664. return this;
  47665. };
  47666. /**
  47667. * Reset all animations to initial state
  47668. */
  47669. AnimationGroup.prototype.reset = function () {
  47670. if (!this._isStarted) {
  47671. return this;
  47672. }
  47673. for (var index = 0; index < this._animatables.length; index++) {
  47674. var animatable = this._animatables[index];
  47675. animatable.reset();
  47676. }
  47677. return this;
  47678. };
  47679. /**
  47680. * Restart animations from key 0
  47681. */
  47682. AnimationGroup.prototype.restart = function () {
  47683. if (!this._isStarted) {
  47684. return this;
  47685. }
  47686. for (var index = 0; index < this._animatables.length; index++) {
  47687. var animatable = this._animatables[index];
  47688. animatable.restart();
  47689. }
  47690. return this;
  47691. };
  47692. /**
  47693. * Stop all animations
  47694. */
  47695. AnimationGroup.prototype.stop = function () {
  47696. if (!this._isStarted) {
  47697. return this;
  47698. }
  47699. for (var index = 0; index < this._animatables.length; index++) {
  47700. var animatable = this._animatables[index];
  47701. animatable.stop();
  47702. }
  47703. this._isStarted = false;
  47704. return this;
  47705. };
  47706. /**
  47707. * Goes to a specific frame in this animation group
  47708. *
  47709. * @param frame the frame number to go to
  47710. * @return the animationGroup
  47711. */
  47712. AnimationGroup.prototype.goToFrame = function (frame) {
  47713. if (!this._isStarted) {
  47714. return this;
  47715. }
  47716. for (var index = 0; index < this._animatables.length; index++) {
  47717. var animatable = this._animatables[index];
  47718. animatable.goToFrame(frame);
  47719. }
  47720. return this;
  47721. };
  47722. /**
  47723. * Dispose all associated resources
  47724. */
  47725. AnimationGroup.prototype.dispose = function () {
  47726. this._targetedAnimations = [];
  47727. this._animatables = [];
  47728. var index = this._scene.animationGroups.indexOf(this);
  47729. if (index > -1) {
  47730. this._scene.animationGroups.splice(index, 1);
  47731. }
  47732. };
  47733. return AnimationGroup;
  47734. }());
  47735. BABYLON.AnimationGroup = AnimationGroup;
  47736. })(BABYLON || (BABYLON = {}));
  47737. //# sourceMappingURL=babylon.animationGroup.js.map
  47738. "use strict";
  47739. var BABYLON;
  47740. (function (BABYLON) {
  47741. var RuntimeAnimation = /** @class */ (function () {
  47742. /**
  47743. * Create a new RuntimeAnimation object
  47744. * @param target defines the target of the animation
  47745. * @param animation defines the source {BABYLON.Animation} object
  47746. * @param scene defines the hosting scene
  47747. */
  47748. function RuntimeAnimation(target, animation, scene) {
  47749. this._offsetsCache = {};
  47750. this._highLimitsCache = {};
  47751. this._stopped = false;
  47752. this._blendingFactor = 0;
  47753. this._weight = 1.0;
  47754. this._ratioOffset = 0;
  47755. this._animation = animation;
  47756. this._target = target;
  47757. this._scene = scene;
  47758. animation._runtimeAnimations.push(this);
  47759. }
  47760. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47761. /**
  47762. * Gets the weight of the runtime animation
  47763. */
  47764. get: function () {
  47765. return this._weight;
  47766. },
  47767. enumerable: true,
  47768. configurable: true
  47769. });
  47770. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47771. /**
  47772. * Gets the original value of the runtime animation
  47773. */
  47774. get: function () {
  47775. return this._originalValue;
  47776. },
  47777. enumerable: true,
  47778. configurable: true
  47779. });
  47780. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47781. /**
  47782. * Gets the current value of the runtime animation
  47783. */
  47784. get: function () {
  47785. return this._currentValue;
  47786. },
  47787. enumerable: true,
  47788. configurable: true
  47789. });
  47790. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47791. /**
  47792. * Gets the path where to store the animated value in the target
  47793. */
  47794. get: function () {
  47795. return this._targetPath;
  47796. },
  47797. enumerable: true,
  47798. configurable: true
  47799. });
  47800. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47801. /**
  47802. * Gets the actual target of the runtime animation
  47803. */
  47804. get: function () {
  47805. return this._activeTarget;
  47806. },
  47807. enumerable: true,
  47808. configurable: true
  47809. });
  47810. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47811. get: function () {
  47812. return this._animation;
  47813. },
  47814. enumerable: true,
  47815. configurable: true
  47816. });
  47817. RuntimeAnimation.prototype.reset = function () {
  47818. this._offsetsCache = {};
  47819. this._highLimitsCache = {};
  47820. this.currentFrame = 0;
  47821. this._blendingFactor = 0;
  47822. this._originalValue = null;
  47823. };
  47824. RuntimeAnimation.prototype.isStopped = function () {
  47825. return this._stopped;
  47826. };
  47827. RuntimeAnimation.prototype.dispose = function () {
  47828. var index = this._animation.runtimeAnimations.indexOf(this);
  47829. if (index > -1) {
  47830. this._animation.runtimeAnimations.splice(index, 1);
  47831. }
  47832. };
  47833. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47834. if (typeof value === "function") {
  47835. return value();
  47836. }
  47837. return value;
  47838. };
  47839. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47840. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47841. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47842. }
  47843. this.currentFrame = currentFrame;
  47844. var keys = this._animation.getKeys();
  47845. // Try to get a hash to find the right key
  47846. 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));
  47847. if (keys[startKeyIndex].frame >= currentFrame) {
  47848. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47849. startKeyIndex--;
  47850. }
  47851. }
  47852. for (var key = startKeyIndex; key < keys.length; key++) {
  47853. var endKey = keys[key + 1];
  47854. if (endKey.frame >= currentFrame) {
  47855. var startKey = keys[key];
  47856. var startValue = this._getKeyValue(startKey.value);
  47857. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47858. return startValue;
  47859. }
  47860. var endValue = this._getKeyValue(endKey.value);
  47861. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47862. var frameDelta = endKey.frame - startKey.frame;
  47863. // gradient : percent of currentFrame between the frame inf and the frame sup
  47864. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47865. // check for easingFunction and correction of gradient
  47866. var easingFunction = this._animation.getEasingFunction();
  47867. if (easingFunction != null) {
  47868. gradient = easingFunction.ease(gradient);
  47869. }
  47870. switch (this._animation.dataType) {
  47871. // Float
  47872. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47873. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47874. switch (loopMode) {
  47875. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47876. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47877. return floatValue;
  47878. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47879. return offsetValue * repeatCount + floatValue;
  47880. }
  47881. break;
  47882. // Quaternion
  47883. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47884. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47885. switch (loopMode) {
  47886. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47887. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47888. return quatValue;
  47889. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47890. return quatValue.add(offsetValue.scale(repeatCount));
  47891. }
  47892. return quatValue;
  47893. // Vector3
  47894. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47895. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47896. switch (loopMode) {
  47897. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47898. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47899. return vec3Value;
  47900. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47901. return vec3Value.add(offsetValue.scale(repeatCount));
  47902. }
  47903. // Vector2
  47904. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47905. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47906. switch (loopMode) {
  47907. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47908. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47909. return vec2Value;
  47910. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47911. return vec2Value.add(offsetValue.scale(repeatCount));
  47912. }
  47913. // Size
  47914. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47915. switch (loopMode) {
  47916. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47917. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47918. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47919. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47920. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47921. }
  47922. // Color3
  47923. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47924. switch (loopMode) {
  47925. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47926. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47927. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47928. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47929. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47930. }
  47931. // Matrix
  47932. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47933. switch (loopMode) {
  47934. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47935. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47936. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47937. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47938. }
  47939. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47940. return startValue;
  47941. }
  47942. default:
  47943. break;
  47944. }
  47945. break;
  47946. }
  47947. }
  47948. return this._getKeyValue(keys[keys.length - 1].value);
  47949. };
  47950. /**
  47951. * Affect the interpolated value to the target
  47952. * @param currentValue defines the value computed by the animation
  47953. * @param weight defines the weight to apply to this value
  47954. */
  47955. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47956. if (weight === void 0) { weight = 1.0; }
  47957. // Set value
  47958. var path;
  47959. var destination;
  47960. var targetPropertyPath = this._animation.targetPropertyPath;
  47961. if (targetPropertyPath.length > 1) {
  47962. var property = this._target[targetPropertyPath[0]];
  47963. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47964. property = property[targetPropertyPath[index]];
  47965. }
  47966. path = [targetPropertyPath.length - 1];
  47967. destination = property;
  47968. }
  47969. else {
  47970. path = targetPropertyPath[0];
  47971. destination = this._target;
  47972. }
  47973. this._targetPath = path;
  47974. this._activeTarget = destination;
  47975. this._weight = weight;
  47976. // Blending
  47977. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47978. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47979. if (enableBlending && this._blendingFactor <= 1.0 || weight !== -1.0) {
  47980. if (!this._originalValue) {
  47981. var originalValue = void 0;
  47982. if (destination.getRestPose) {
  47983. originalValue = destination.getRestPose();
  47984. }
  47985. else {
  47986. originalValue = destination[path];
  47987. }
  47988. if (originalValue.clone) {
  47989. this._originalValue = originalValue.clone();
  47990. }
  47991. else {
  47992. this._originalValue = originalValue;
  47993. }
  47994. }
  47995. }
  47996. if (enableBlending && this._blendingFactor <= 1.0) {
  47997. if (this._originalValue.prototype) {
  47998. if (this._originalValue.prototype.Lerp) {
  47999. this._currentValue = this._originalValue.construtor.prototype.Lerp(currentValue, this._originalValue, this._blendingFactor);
  48000. }
  48001. else {
  48002. this._currentValue = currentValue;
  48003. }
  48004. }
  48005. else if (this._originalValue.m) {
  48006. this._currentValue = BABYLON.Matrix.Lerp(this._originalValue, currentValue, this._blendingFactor);
  48007. }
  48008. else {
  48009. this._currentValue = this._originalValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  48010. }
  48011. this._blendingFactor += blendingSpeed;
  48012. destination[path] = this._currentValue;
  48013. }
  48014. else {
  48015. this._currentValue = currentValue;
  48016. if (weight !== -1.0) {
  48017. this._scene._registerTargetForLateAnimationBinding(this);
  48018. }
  48019. else {
  48020. destination[path] = this._currentValue;
  48021. }
  48022. }
  48023. if (this._target.markAsDirty) {
  48024. this._target.markAsDirty(this._animation.targetProperty);
  48025. }
  48026. };
  48027. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  48028. if (this._target && this._target.animationPropertiesOverride) {
  48029. return this._target.animationPropertiesOverride.loopMode;
  48030. }
  48031. return this._animation.loopMode;
  48032. };
  48033. /**
  48034. * Move the current animation to a given frame
  48035. * @param frame defines the frame to move to
  48036. */
  48037. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48038. var keys = this._animation.getKeys();
  48039. if (frame < keys[0].frame) {
  48040. frame = keys[0].frame;
  48041. }
  48042. else if (frame > keys[keys.length - 1].frame) {
  48043. frame = keys[keys.length - 1].frame;
  48044. }
  48045. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  48046. this.setValue(currentValue, -1);
  48047. };
  48048. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  48049. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  48050. this._ratioOffset = this._previousRatio - newRatio;
  48051. };
  48052. /**
  48053. * Execute the current animation
  48054. * @param delay defines the delay to add to the current frame
  48055. * @param from defines the lower bound of the animation range
  48056. * @param to defines the upper bound of the animation range
  48057. * @param loop defines if the current animation must loop
  48058. * @param speedRatio defines the current speed ratio
  48059. * @param weight defines the weight of the animation (default is -1 so no weight)
  48060. * @returns a boolean indicating if the animation has ended
  48061. */
  48062. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48063. if (weight === void 0) { weight = -1.0; }
  48064. var targetPropertyPath = this._animation.targetPropertyPath;
  48065. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48066. this._stopped = true;
  48067. return false;
  48068. }
  48069. var returnValue = true;
  48070. var keys = this._animation.getKeys();
  48071. // Adding a start key at frame 0 if missing
  48072. if (keys[0].frame !== 0) {
  48073. var newKey = { frame: 0, value: keys[0].value };
  48074. keys.splice(0, 0, newKey);
  48075. }
  48076. // Check limits
  48077. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48078. from = keys[0].frame;
  48079. }
  48080. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48081. to = keys[keys.length - 1].frame;
  48082. }
  48083. //to and from cannot be the same key
  48084. if (from === to) {
  48085. if (from > keys[0].frame) {
  48086. from--;
  48087. }
  48088. else if (to < keys[keys.length - 1].frame) {
  48089. to++;
  48090. }
  48091. }
  48092. // Compute ratio
  48093. var range = to - from;
  48094. var offsetValue;
  48095. // ratio represents the frame delta between from and to
  48096. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48097. var highLimitValue = 0;
  48098. this._previousDelay = delay;
  48099. this._previousRatio = ratio;
  48100. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48101. returnValue = false;
  48102. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48103. }
  48104. else {
  48105. // Get max value if required
  48106. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48107. var keyOffset = to.toString() + from.toString();
  48108. if (!this._offsetsCache[keyOffset]) {
  48109. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48110. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48111. switch (this._animation.dataType) {
  48112. // Float
  48113. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48114. this._offsetsCache[keyOffset] = toValue - fromValue;
  48115. break;
  48116. // Quaternion
  48117. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48118. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48119. break;
  48120. // Vector3
  48121. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48122. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48123. // Vector2
  48124. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48125. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48126. // Size
  48127. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48128. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48129. // Color3
  48130. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48131. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48132. default:
  48133. break;
  48134. }
  48135. this._highLimitsCache[keyOffset] = toValue;
  48136. }
  48137. highLimitValue = this._highLimitsCache[keyOffset];
  48138. offsetValue = this._offsetsCache[keyOffset];
  48139. }
  48140. }
  48141. if (offsetValue === undefined) {
  48142. switch (this._animation.dataType) {
  48143. // Float
  48144. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48145. offsetValue = 0;
  48146. break;
  48147. // Quaternion
  48148. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48149. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48150. break;
  48151. // Vector3
  48152. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48153. offsetValue = BABYLON.Vector3.Zero();
  48154. break;
  48155. // Vector2
  48156. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48157. offsetValue = BABYLON.Vector2.Zero();
  48158. break;
  48159. // Size
  48160. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48161. offsetValue = BABYLON.Size.Zero();
  48162. break;
  48163. // Color3
  48164. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48165. offsetValue = BABYLON.Color3.Black();
  48166. }
  48167. }
  48168. // Compute value
  48169. var repeatCount = (ratio / range) >> 0;
  48170. var currentFrame = returnValue ? from + ratio % range : to;
  48171. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48172. // Set value
  48173. this.setValue(currentValue, weight);
  48174. // Check events
  48175. var events = this._animation.getEvents();
  48176. for (var index = 0; index < events.length; index++) {
  48177. // Make sure current frame has passed event frame and that event frame is within the current range
  48178. // Also, handle both forward and reverse animations
  48179. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48180. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48181. var event = events[index];
  48182. if (!event.isDone) {
  48183. // If event should be done only once, remove it.
  48184. if (event.onlyOnce) {
  48185. events.splice(index, 1);
  48186. index--;
  48187. }
  48188. event.isDone = true;
  48189. event.action();
  48190. } // Don't do anything if the event has already be done.
  48191. }
  48192. else if (events[index].isDone && !events[index].onlyOnce) {
  48193. // reset event, the animation is looping
  48194. events[index].isDone = false;
  48195. }
  48196. }
  48197. if (!returnValue) {
  48198. this._stopped = true;
  48199. }
  48200. return returnValue;
  48201. };
  48202. return RuntimeAnimation;
  48203. }());
  48204. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48205. })(BABYLON || (BABYLON = {}));
  48206. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48207. "use strict";
  48208. var BABYLON;
  48209. (function (BABYLON) {
  48210. var Animatable = /** @class */ (function () {
  48211. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48212. if (fromFrame === void 0) { fromFrame = 0; }
  48213. if (toFrame === void 0) { toFrame = 100; }
  48214. if (loopAnimation === void 0) { loopAnimation = false; }
  48215. if (speedRatio === void 0) { speedRatio = 1.0; }
  48216. this.target = target;
  48217. this.fromFrame = fromFrame;
  48218. this.toFrame = toFrame;
  48219. this.loopAnimation = loopAnimation;
  48220. this.onAnimationEnd = onAnimationEnd;
  48221. this._localDelayOffset = null;
  48222. this._pausedDelay = null;
  48223. this._runtimeAnimations = new Array();
  48224. this._paused = false;
  48225. this._speedRatio = 1;
  48226. this._weight = -1.0;
  48227. this.animationStarted = false;
  48228. if (animations) {
  48229. this.appendAnimations(target, animations);
  48230. }
  48231. this._speedRatio = speedRatio;
  48232. this._scene = scene;
  48233. scene._activeAnimatables.push(this);
  48234. }
  48235. Object.defineProperty(Animatable.prototype, "weight", {
  48236. /**
  48237. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48238. */
  48239. get: function () {
  48240. return this._weight;
  48241. },
  48242. set: function (value) {
  48243. if (value === -1) {
  48244. this._weight = -1;
  48245. return;
  48246. }
  48247. // Else weight must be in [0, 1] range
  48248. this._weight = Math.min(Math.max(value, 0), 1.0);
  48249. },
  48250. enumerable: true,
  48251. configurable: true
  48252. });
  48253. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48254. /**
  48255. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48256. */
  48257. get: function () {
  48258. return this._speedRatio;
  48259. },
  48260. set: function (value) {
  48261. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48262. var animation = this._runtimeAnimations[index];
  48263. animation._prepareForSpeedRatioChange(value);
  48264. }
  48265. this._speedRatio = value;
  48266. },
  48267. enumerable: true,
  48268. configurable: true
  48269. });
  48270. // Methods
  48271. Animatable.prototype.getAnimations = function () {
  48272. return this._runtimeAnimations;
  48273. };
  48274. Animatable.prototype.appendAnimations = function (target, animations) {
  48275. for (var index = 0; index < animations.length; index++) {
  48276. var animation = animations[index];
  48277. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene));
  48278. }
  48279. };
  48280. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48281. var runtimeAnimations = this._runtimeAnimations;
  48282. for (var index = 0; index < runtimeAnimations.length; index++) {
  48283. if (runtimeAnimations[index].animation.targetProperty === property) {
  48284. return runtimeAnimations[index].animation;
  48285. }
  48286. }
  48287. return null;
  48288. };
  48289. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48290. var runtimeAnimations = this._runtimeAnimations;
  48291. for (var index = 0; index < runtimeAnimations.length; index++) {
  48292. if (runtimeAnimations[index].animation.targetProperty === property) {
  48293. return runtimeAnimations[index];
  48294. }
  48295. }
  48296. return null;
  48297. };
  48298. Animatable.prototype.reset = function () {
  48299. var runtimeAnimations = this._runtimeAnimations;
  48300. for (var index = 0; index < runtimeAnimations.length; index++) {
  48301. runtimeAnimations[index].reset();
  48302. }
  48303. // Reset to original value
  48304. for (index = 0; index < runtimeAnimations.length; index++) {
  48305. var animation = runtimeAnimations[index];
  48306. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48307. }
  48308. this._localDelayOffset = null;
  48309. this._pausedDelay = null;
  48310. };
  48311. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48312. var runtimeAnimations = this._runtimeAnimations;
  48313. for (var index = 0; index < runtimeAnimations.length; index++) {
  48314. runtimeAnimations[index].animation.enableBlending = true;
  48315. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48316. }
  48317. };
  48318. Animatable.prototype.disableBlending = function () {
  48319. var runtimeAnimations = this._runtimeAnimations;
  48320. for (var index = 0; index < runtimeAnimations.length; index++) {
  48321. runtimeAnimations[index].animation.enableBlending = false;
  48322. }
  48323. };
  48324. Animatable.prototype.goToFrame = function (frame) {
  48325. var runtimeAnimations = this._runtimeAnimations;
  48326. if (runtimeAnimations[0]) {
  48327. var fps = runtimeAnimations[0].animation.framePerSecond;
  48328. var currentFrame = runtimeAnimations[0].currentFrame;
  48329. var adjustTime = frame - currentFrame;
  48330. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48331. if (this._localDelayOffset === null) {
  48332. this._localDelayOffset = 0;
  48333. }
  48334. this._localDelayOffset -= delay;
  48335. }
  48336. for (var index = 0; index < runtimeAnimations.length; index++) {
  48337. runtimeAnimations[index].goToFrame(frame);
  48338. }
  48339. };
  48340. Animatable.prototype.pause = function () {
  48341. if (this._paused) {
  48342. return;
  48343. }
  48344. this._paused = true;
  48345. };
  48346. Animatable.prototype.restart = function () {
  48347. this._paused = false;
  48348. };
  48349. Animatable.prototype.stop = function (animationName) {
  48350. if (animationName) {
  48351. var idx = this._scene._activeAnimatables.indexOf(this);
  48352. if (idx > -1) {
  48353. var runtimeAnimations = this._runtimeAnimations;
  48354. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48355. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48356. continue;
  48357. }
  48358. runtimeAnimations[index].dispose();
  48359. runtimeAnimations.splice(index, 1);
  48360. }
  48361. if (runtimeAnimations.length == 0) {
  48362. this._scene._activeAnimatables.splice(idx, 1);
  48363. if (this.onAnimationEnd) {
  48364. this.onAnimationEnd();
  48365. }
  48366. }
  48367. }
  48368. }
  48369. else {
  48370. var index = this._scene._activeAnimatables.indexOf(this);
  48371. if (index > -1) {
  48372. this._scene._activeAnimatables.splice(index, 1);
  48373. var runtimeAnimations = this._runtimeAnimations;
  48374. for (var index = 0; index < runtimeAnimations.length; index++) {
  48375. runtimeAnimations[index].dispose();
  48376. }
  48377. if (this.onAnimationEnd) {
  48378. this.onAnimationEnd();
  48379. }
  48380. }
  48381. }
  48382. };
  48383. Animatable.prototype._animate = function (delay) {
  48384. if (this._paused) {
  48385. this.animationStarted = false;
  48386. if (this._pausedDelay === null) {
  48387. this._pausedDelay = delay;
  48388. }
  48389. return true;
  48390. }
  48391. if (this._localDelayOffset === null) {
  48392. this._localDelayOffset = delay;
  48393. this._pausedDelay = null;
  48394. }
  48395. else if (this._pausedDelay !== null) {
  48396. this._localDelayOffset += delay - this._pausedDelay;
  48397. this._pausedDelay = null;
  48398. }
  48399. // Animating
  48400. var running = false;
  48401. var runtimeAnimations = this._runtimeAnimations;
  48402. var index;
  48403. for (index = 0; index < runtimeAnimations.length; index++) {
  48404. var animation = runtimeAnimations[index];
  48405. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48406. running = running || isRunning;
  48407. }
  48408. this.animationStarted = running;
  48409. if (!running) {
  48410. // Remove from active animatables
  48411. index = this._scene._activeAnimatables.indexOf(this);
  48412. this._scene._activeAnimatables.splice(index, 1);
  48413. // Dispose all runtime animations
  48414. for (index = 0; index < runtimeAnimations.length; index++) {
  48415. runtimeAnimations[index].dispose();
  48416. }
  48417. }
  48418. if (!running && this.onAnimationEnd) {
  48419. this.onAnimationEnd();
  48420. this.onAnimationEnd = null;
  48421. }
  48422. return running;
  48423. };
  48424. return Animatable;
  48425. }());
  48426. BABYLON.Animatable = Animatable;
  48427. })(BABYLON || (BABYLON = {}));
  48428. //# sourceMappingURL=babylon.animatable.js.map
  48429. "use strict";
  48430. var BABYLON;
  48431. (function (BABYLON) {
  48432. var EasingFunction = /** @class */ (function () {
  48433. function EasingFunction() {
  48434. // Properties
  48435. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48436. }
  48437. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48438. get: function () {
  48439. return EasingFunction._EASINGMODE_EASEIN;
  48440. },
  48441. enumerable: true,
  48442. configurable: true
  48443. });
  48444. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48445. get: function () {
  48446. return EasingFunction._EASINGMODE_EASEOUT;
  48447. },
  48448. enumerable: true,
  48449. configurable: true
  48450. });
  48451. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48452. get: function () {
  48453. return EasingFunction._EASINGMODE_EASEINOUT;
  48454. },
  48455. enumerable: true,
  48456. configurable: true
  48457. });
  48458. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48459. var n = Math.min(Math.max(easingMode, 0), 2);
  48460. this._easingMode = n;
  48461. };
  48462. EasingFunction.prototype.getEasingMode = function () {
  48463. return this._easingMode;
  48464. };
  48465. EasingFunction.prototype.easeInCore = function (gradient) {
  48466. throw new Error('You must implement this method');
  48467. };
  48468. EasingFunction.prototype.ease = function (gradient) {
  48469. switch (this._easingMode) {
  48470. case EasingFunction.EASINGMODE_EASEIN:
  48471. return this.easeInCore(gradient);
  48472. case EasingFunction.EASINGMODE_EASEOUT:
  48473. return (1 - this.easeInCore(1 - gradient));
  48474. }
  48475. if (gradient >= 0.5) {
  48476. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48477. }
  48478. return (this.easeInCore(gradient * 2) * 0.5);
  48479. };
  48480. //Statics
  48481. EasingFunction._EASINGMODE_EASEIN = 0;
  48482. EasingFunction._EASINGMODE_EASEOUT = 1;
  48483. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48484. return EasingFunction;
  48485. }());
  48486. BABYLON.EasingFunction = EasingFunction;
  48487. var CircleEase = /** @class */ (function (_super) {
  48488. __extends(CircleEase, _super);
  48489. function CircleEase() {
  48490. return _super !== null && _super.apply(this, arguments) || this;
  48491. }
  48492. CircleEase.prototype.easeInCore = function (gradient) {
  48493. gradient = Math.max(0, Math.min(1, gradient));
  48494. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48495. };
  48496. return CircleEase;
  48497. }(EasingFunction));
  48498. BABYLON.CircleEase = CircleEase;
  48499. var BackEase = /** @class */ (function (_super) {
  48500. __extends(BackEase, _super);
  48501. function BackEase(amplitude) {
  48502. if (amplitude === void 0) { amplitude = 1; }
  48503. var _this = _super.call(this) || this;
  48504. _this.amplitude = amplitude;
  48505. return _this;
  48506. }
  48507. BackEase.prototype.easeInCore = function (gradient) {
  48508. var num = Math.max(0, this.amplitude);
  48509. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48510. };
  48511. return BackEase;
  48512. }(EasingFunction));
  48513. BABYLON.BackEase = BackEase;
  48514. var BounceEase = /** @class */ (function (_super) {
  48515. __extends(BounceEase, _super);
  48516. function BounceEase(bounces, bounciness) {
  48517. if (bounces === void 0) { bounces = 3; }
  48518. if (bounciness === void 0) { bounciness = 2; }
  48519. var _this = _super.call(this) || this;
  48520. _this.bounces = bounces;
  48521. _this.bounciness = bounciness;
  48522. return _this;
  48523. }
  48524. BounceEase.prototype.easeInCore = function (gradient) {
  48525. var y = Math.max(0.0, this.bounces);
  48526. var bounciness = this.bounciness;
  48527. if (bounciness <= 1.0) {
  48528. bounciness = 1.001;
  48529. }
  48530. var num9 = Math.pow(bounciness, y);
  48531. var num5 = 1.0 - bounciness;
  48532. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48533. var num15 = gradient * num4;
  48534. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48535. var num3 = Math.floor(num65);
  48536. var num13 = num3 + 1.0;
  48537. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48538. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48539. var num7 = (num8 + num12) * 0.5;
  48540. var num6 = gradient - num7;
  48541. var num2 = num7 - num8;
  48542. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48543. };
  48544. return BounceEase;
  48545. }(EasingFunction));
  48546. BABYLON.BounceEase = BounceEase;
  48547. var CubicEase = /** @class */ (function (_super) {
  48548. __extends(CubicEase, _super);
  48549. function CubicEase() {
  48550. return _super !== null && _super.apply(this, arguments) || this;
  48551. }
  48552. CubicEase.prototype.easeInCore = function (gradient) {
  48553. return (gradient * gradient * gradient);
  48554. };
  48555. return CubicEase;
  48556. }(EasingFunction));
  48557. BABYLON.CubicEase = CubicEase;
  48558. var ElasticEase = /** @class */ (function (_super) {
  48559. __extends(ElasticEase, _super);
  48560. function ElasticEase(oscillations, springiness) {
  48561. if (oscillations === void 0) { oscillations = 3; }
  48562. if (springiness === void 0) { springiness = 3; }
  48563. var _this = _super.call(this) || this;
  48564. _this.oscillations = oscillations;
  48565. _this.springiness = springiness;
  48566. return _this;
  48567. }
  48568. ElasticEase.prototype.easeInCore = function (gradient) {
  48569. var num2;
  48570. var num3 = Math.max(0.0, this.oscillations);
  48571. var num = Math.max(0.0, this.springiness);
  48572. if (num == 0) {
  48573. num2 = gradient;
  48574. }
  48575. else {
  48576. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48577. }
  48578. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48579. };
  48580. return ElasticEase;
  48581. }(EasingFunction));
  48582. BABYLON.ElasticEase = ElasticEase;
  48583. var ExponentialEase = /** @class */ (function (_super) {
  48584. __extends(ExponentialEase, _super);
  48585. function ExponentialEase(exponent) {
  48586. if (exponent === void 0) { exponent = 2; }
  48587. var _this = _super.call(this) || this;
  48588. _this.exponent = exponent;
  48589. return _this;
  48590. }
  48591. ExponentialEase.prototype.easeInCore = function (gradient) {
  48592. if (this.exponent <= 0) {
  48593. return gradient;
  48594. }
  48595. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48596. };
  48597. return ExponentialEase;
  48598. }(EasingFunction));
  48599. BABYLON.ExponentialEase = ExponentialEase;
  48600. var PowerEase = /** @class */ (function (_super) {
  48601. __extends(PowerEase, _super);
  48602. function PowerEase(power) {
  48603. if (power === void 0) { power = 2; }
  48604. var _this = _super.call(this) || this;
  48605. _this.power = power;
  48606. return _this;
  48607. }
  48608. PowerEase.prototype.easeInCore = function (gradient) {
  48609. var y = Math.max(0.0, this.power);
  48610. return Math.pow(gradient, y);
  48611. };
  48612. return PowerEase;
  48613. }(EasingFunction));
  48614. BABYLON.PowerEase = PowerEase;
  48615. var QuadraticEase = /** @class */ (function (_super) {
  48616. __extends(QuadraticEase, _super);
  48617. function QuadraticEase() {
  48618. return _super !== null && _super.apply(this, arguments) || this;
  48619. }
  48620. QuadraticEase.prototype.easeInCore = function (gradient) {
  48621. return (gradient * gradient);
  48622. };
  48623. return QuadraticEase;
  48624. }(EasingFunction));
  48625. BABYLON.QuadraticEase = QuadraticEase;
  48626. var QuarticEase = /** @class */ (function (_super) {
  48627. __extends(QuarticEase, _super);
  48628. function QuarticEase() {
  48629. return _super !== null && _super.apply(this, arguments) || this;
  48630. }
  48631. QuarticEase.prototype.easeInCore = function (gradient) {
  48632. return (gradient * gradient * gradient * gradient);
  48633. };
  48634. return QuarticEase;
  48635. }(EasingFunction));
  48636. BABYLON.QuarticEase = QuarticEase;
  48637. var QuinticEase = /** @class */ (function (_super) {
  48638. __extends(QuinticEase, _super);
  48639. function QuinticEase() {
  48640. return _super !== null && _super.apply(this, arguments) || this;
  48641. }
  48642. QuinticEase.prototype.easeInCore = function (gradient) {
  48643. return (gradient * gradient * gradient * gradient * gradient);
  48644. };
  48645. return QuinticEase;
  48646. }(EasingFunction));
  48647. BABYLON.QuinticEase = QuinticEase;
  48648. var SineEase = /** @class */ (function (_super) {
  48649. __extends(SineEase, _super);
  48650. function SineEase() {
  48651. return _super !== null && _super.apply(this, arguments) || this;
  48652. }
  48653. SineEase.prototype.easeInCore = function (gradient) {
  48654. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48655. };
  48656. return SineEase;
  48657. }(EasingFunction));
  48658. BABYLON.SineEase = SineEase;
  48659. var BezierCurveEase = /** @class */ (function (_super) {
  48660. __extends(BezierCurveEase, _super);
  48661. function BezierCurveEase(x1, y1, x2, y2) {
  48662. if (x1 === void 0) { x1 = 0; }
  48663. if (y1 === void 0) { y1 = 0; }
  48664. if (x2 === void 0) { x2 = 1; }
  48665. if (y2 === void 0) { y2 = 1; }
  48666. var _this = _super.call(this) || this;
  48667. _this.x1 = x1;
  48668. _this.y1 = y1;
  48669. _this.x2 = x2;
  48670. _this.y2 = y2;
  48671. return _this;
  48672. }
  48673. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48674. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48675. };
  48676. return BezierCurveEase;
  48677. }(EasingFunction));
  48678. BABYLON.BezierCurveEase = BezierCurveEase;
  48679. })(BABYLON || (BABYLON = {}));
  48680. //# sourceMappingURL=babylon.easing.js.map
  48681. "use strict";
  48682. var BABYLON;
  48683. (function (BABYLON) {
  48684. var Condition = /** @class */ (function () {
  48685. function Condition(actionManager) {
  48686. this._actionManager = actionManager;
  48687. }
  48688. Condition.prototype.isValid = function () {
  48689. return true;
  48690. };
  48691. Condition.prototype._getProperty = function (propertyPath) {
  48692. return this._actionManager._getProperty(propertyPath);
  48693. };
  48694. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48695. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48696. };
  48697. Condition.prototype.serialize = function () {
  48698. };
  48699. Condition.prototype._serialize = function (serializedCondition) {
  48700. return {
  48701. type: 2,
  48702. children: [],
  48703. name: serializedCondition.name,
  48704. properties: serializedCondition.properties
  48705. };
  48706. };
  48707. return Condition;
  48708. }());
  48709. BABYLON.Condition = Condition;
  48710. var ValueCondition = /** @class */ (function (_super) {
  48711. __extends(ValueCondition, _super);
  48712. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48713. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48714. var _this = _super.call(this, actionManager) || this;
  48715. _this.propertyPath = propertyPath;
  48716. _this.value = value;
  48717. _this.operator = operator;
  48718. _this._target = target;
  48719. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48720. _this._property = _this._getProperty(_this.propertyPath);
  48721. return _this;
  48722. }
  48723. Object.defineProperty(ValueCondition, "IsEqual", {
  48724. get: function () {
  48725. return ValueCondition._IsEqual;
  48726. },
  48727. enumerable: true,
  48728. configurable: true
  48729. });
  48730. Object.defineProperty(ValueCondition, "IsDifferent", {
  48731. get: function () {
  48732. return ValueCondition._IsDifferent;
  48733. },
  48734. enumerable: true,
  48735. configurable: true
  48736. });
  48737. Object.defineProperty(ValueCondition, "IsGreater", {
  48738. get: function () {
  48739. return ValueCondition._IsGreater;
  48740. },
  48741. enumerable: true,
  48742. configurable: true
  48743. });
  48744. Object.defineProperty(ValueCondition, "IsLesser", {
  48745. get: function () {
  48746. return ValueCondition._IsLesser;
  48747. },
  48748. enumerable: true,
  48749. configurable: true
  48750. });
  48751. // Methods
  48752. ValueCondition.prototype.isValid = function () {
  48753. switch (this.operator) {
  48754. case ValueCondition.IsGreater:
  48755. return this._effectiveTarget[this._property] > this.value;
  48756. case ValueCondition.IsLesser:
  48757. return this._effectiveTarget[this._property] < this.value;
  48758. case ValueCondition.IsEqual:
  48759. case ValueCondition.IsDifferent:
  48760. var check;
  48761. if (this.value.equals) {
  48762. check = this.value.equals(this._effectiveTarget[this._property]);
  48763. }
  48764. else {
  48765. check = this.value === this._effectiveTarget[this._property];
  48766. }
  48767. return this.operator === ValueCondition.IsEqual ? check : !check;
  48768. }
  48769. return false;
  48770. };
  48771. ValueCondition.prototype.serialize = function () {
  48772. return this._serialize({
  48773. name: "ValueCondition",
  48774. properties: [
  48775. BABYLON.Action._GetTargetProperty(this._target),
  48776. { name: "propertyPath", value: this.propertyPath },
  48777. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48778. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48779. ]
  48780. });
  48781. };
  48782. ValueCondition.GetOperatorName = function (operator) {
  48783. switch (operator) {
  48784. case ValueCondition._IsEqual: return "IsEqual";
  48785. case ValueCondition._IsDifferent: return "IsDifferent";
  48786. case ValueCondition._IsGreater: return "IsGreater";
  48787. case ValueCondition._IsLesser: return "IsLesser";
  48788. default: return "";
  48789. }
  48790. };
  48791. // Statics
  48792. ValueCondition._IsEqual = 0;
  48793. ValueCondition._IsDifferent = 1;
  48794. ValueCondition._IsGreater = 2;
  48795. ValueCondition._IsLesser = 3;
  48796. return ValueCondition;
  48797. }(Condition));
  48798. BABYLON.ValueCondition = ValueCondition;
  48799. var PredicateCondition = /** @class */ (function (_super) {
  48800. __extends(PredicateCondition, _super);
  48801. function PredicateCondition(actionManager, predicate) {
  48802. var _this = _super.call(this, actionManager) || this;
  48803. _this.predicate = predicate;
  48804. return _this;
  48805. }
  48806. PredicateCondition.prototype.isValid = function () {
  48807. return this.predicate();
  48808. };
  48809. return PredicateCondition;
  48810. }(Condition));
  48811. BABYLON.PredicateCondition = PredicateCondition;
  48812. var StateCondition = /** @class */ (function (_super) {
  48813. __extends(StateCondition, _super);
  48814. function StateCondition(actionManager, target, value) {
  48815. var _this = _super.call(this, actionManager) || this;
  48816. _this.value = value;
  48817. _this._target = target;
  48818. return _this;
  48819. }
  48820. // Methods
  48821. StateCondition.prototype.isValid = function () {
  48822. return this._target.state === this.value;
  48823. };
  48824. StateCondition.prototype.serialize = function () {
  48825. return this._serialize({
  48826. name: "StateCondition",
  48827. properties: [
  48828. BABYLON.Action._GetTargetProperty(this._target),
  48829. { name: "value", value: this.value }
  48830. ]
  48831. });
  48832. };
  48833. return StateCondition;
  48834. }(Condition));
  48835. BABYLON.StateCondition = StateCondition;
  48836. })(BABYLON || (BABYLON = {}));
  48837. //# sourceMappingURL=babylon.condition.js.map
  48838. "use strict";
  48839. var BABYLON;
  48840. (function (BABYLON) {
  48841. var Action = /** @class */ (function () {
  48842. function Action(triggerOptions, condition) {
  48843. this.triggerOptions = triggerOptions;
  48844. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48845. if (triggerOptions.parameter) {
  48846. this.trigger = triggerOptions.trigger;
  48847. this._triggerParameter = triggerOptions.parameter;
  48848. }
  48849. else {
  48850. this.trigger = triggerOptions;
  48851. }
  48852. this._nextActiveAction = this;
  48853. this._condition = condition;
  48854. }
  48855. // Methods
  48856. Action.prototype._prepare = function () {
  48857. };
  48858. Action.prototype.getTriggerParameter = function () {
  48859. return this._triggerParameter;
  48860. };
  48861. Action.prototype._executeCurrent = function (evt) {
  48862. if (this._nextActiveAction._condition) {
  48863. var condition = this._nextActiveAction._condition;
  48864. var currentRenderId = this._actionManager.getScene().getRenderId();
  48865. // We cache the current evaluation for the current frame
  48866. if (condition._evaluationId === currentRenderId) {
  48867. if (!condition._currentResult) {
  48868. return;
  48869. }
  48870. }
  48871. else {
  48872. condition._evaluationId = currentRenderId;
  48873. if (!condition.isValid()) {
  48874. condition._currentResult = false;
  48875. return;
  48876. }
  48877. condition._currentResult = true;
  48878. }
  48879. }
  48880. this.onBeforeExecuteObservable.notifyObservers(this);
  48881. this._nextActiveAction.execute(evt);
  48882. this.skipToNextActiveAction();
  48883. };
  48884. Action.prototype.execute = function (evt) {
  48885. };
  48886. Action.prototype.skipToNextActiveAction = function () {
  48887. if (this._nextActiveAction._child) {
  48888. if (!this._nextActiveAction._child._actionManager) {
  48889. this._nextActiveAction._child._actionManager = this._actionManager;
  48890. }
  48891. this._nextActiveAction = this._nextActiveAction._child;
  48892. }
  48893. else {
  48894. this._nextActiveAction = this;
  48895. }
  48896. };
  48897. Action.prototype.then = function (action) {
  48898. this._child = action;
  48899. action._actionManager = this._actionManager;
  48900. action._prepare();
  48901. return action;
  48902. };
  48903. Action.prototype._getProperty = function (propertyPath) {
  48904. return this._actionManager._getProperty(propertyPath);
  48905. };
  48906. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48907. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48908. };
  48909. Action.prototype.serialize = function (parent) {
  48910. };
  48911. // Called by BABYLON.Action objects in serialize(...). Internal use
  48912. Action.prototype._serialize = function (serializedAction, parent) {
  48913. var serializationObject = {
  48914. type: 1,
  48915. children: [],
  48916. name: serializedAction.name,
  48917. properties: serializedAction.properties || []
  48918. };
  48919. // Serialize child
  48920. if (this._child) {
  48921. this._child.serialize(serializationObject);
  48922. }
  48923. // Check if "this" has a condition
  48924. if (this._condition) {
  48925. var serializedCondition = this._condition.serialize();
  48926. serializedCondition.children.push(serializationObject);
  48927. if (parent) {
  48928. parent.children.push(serializedCondition);
  48929. }
  48930. return serializedCondition;
  48931. }
  48932. if (parent) {
  48933. parent.children.push(serializationObject);
  48934. }
  48935. return serializationObject;
  48936. };
  48937. Action._SerializeValueAsString = function (value) {
  48938. if (typeof value === "number") {
  48939. return value.toString();
  48940. }
  48941. if (typeof value === "boolean") {
  48942. return value ? "true" : "false";
  48943. }
  48944. if (value instanceof BABYLON.Vector2) {
  48945. return value.x + ", " + value.y;
  48946. }
  48947. if (value instanceof BABYLON.Vector3) {
  48948. return value.x + ", " + value.y + ", " + value.z;
  48949. }
  48950. if (value instanceof BABYLON.Color3) {
  48951. return value.r + ", " + value.g + ", " + value.b;
  48952. }
  48953. if (value instanceof BABYLON.Color4) {
  48954. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48955. }
  48956. return value; // string
  48957. };
  48958. Action._GetTargetProperty = function (target) {
  48959. return {
  48960. name: "target",
  48961. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48962. : target instanceof BABYLON.Light ? "LightProperties"
  48963. : target instanceof BABYLON.Camera ? "CameraProperties"
  48964. : "SceneProperties",
  48965. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48966. };
  48967. };
  48968. return Action;
  48969. }());
  48970. BABYLON.Action = Action;
  48971. })(BABYLON || (BABYLON = {}));
  48972. //# sourceMappingURL=babylon.action.js.map
  48973. "use strict";
  48974. var BABYLON;
  48975. (function (BABYLON) {
  48976. /**
  48977. * ActionEvent is the event beint sent when an action is triggered.
  48978. */
  48979. var ActionEvent = /** @class */ (function () {
  48980. /**
  48981. * @param source The mesh or sprite that triggered the action.
  48982. * @param pointerX The X mouse cursor position at the time of the event
  48983. * @param pointerY The Y mouse cursor position at the time of the event
  48984. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48985. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48986. */
  48987. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48988. this.source = source;
  48989. this.pointerX = pointerX;
  48990. this.pointerY = pointerY;
  48991. this.meshUnderPointer = meshUnderPointer;
  48992. this.sourceEvent = sourceEvent;
  48993. this.additionalData = additionalData;
  48994. }
  48995. /**
  48996. * Helper function to auto-create an ActionEvent from a source mesh.
  48997. * @param source The source mesh that triggered the event
  48998. * @param evt {Event} The original (browser) event
  48999. */
  49000. ActionEvent.CreateNew = function (source, evt, additionalData) {
  49001. var scene = source.getScene();
  49002. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49003. };
  49004. /**
  49005. * Helper function to auto-create an ActionEvent from a source mesh.
  49006. * @param source The source sprite that triggered the event
  49007. * @param scene Scene associated with the sprite
  49008. * @param evt {Event} The original (browser) event
  49009. */
  49010. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49011. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49012. };
  49013. /**
  49014. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49015. * @param scene the scene where the event occurred
  49016. * @param evt {Event} The original (browser) event
  49017. */
  49018. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49019. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49020. };
  49021. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49022. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49023. };
  49024. return ActionEvent;
  49025. }());
  49026. BABYLON.ActionEvent = ActionEvent;
  49027. /**
  49028. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49029. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49030. */
  49031. var ActionManager = /** @class */ (function () {
  49032. function ActionManager(scene) {
  49033. // Members
  49034. this.actions = new Array();
  49035. this.hoverCursor = '';
  49036. this._scene = scene;
  49037. scene._actionManagers.push(this);
  49038. }
  49039. Object.defineProperty(ActionManager, "NothingTrigger", {
  49040. get: function () {
  49041. return ActionManager._NothingTrigger;
  49042. },
  49043. enumerable: true,
  49044. configurable: true
  49045. });
  49046. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49047. get: function () {
  49048. return ActionManager._OnPickTrigger;
  49049. },
  49050. enumerable: true,
  49051. configurable: true
  49052. });
  49053. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49054. get: function () {
  49055. return ActionManager._OnLeftPickTrigger;
  49056. },
  49057. enumerable: true,
  49058. configurable: true
  49059. });
  49060. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49061. get: function () {
  49062. return ActionManager._OnRightPickTrigger;
  49063. },
  49064. enumerable: true,
  49065. configurable: true
  49066. });
  49067. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49068. get: function () {
  49069. return ActionManager._OnCenterPickTrigger;
  49070. },
  49071. enumerable: true,
  49072. configurable: true
  49073. });
  49074. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49075. get: function () {
  49076. return ActionManager._OnPickDownTrigger;
  49077. },
  49078. enumerable: true,
  49079. configurable: true
  49080. });
  49081. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49082. get: function () {
  49083. return ActionManager._OnDoublePickTrigger;
  49084. },
  49085. enumerable: true,
  49086. configurable: true
  49087. });
  49088. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49089. get: function () {
  49090. return ActionManager._OnPickUpTrigger;
  49091. },
  49092. enumerable: true,
  49093. configurable: true
  49094. });
  49095. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49096. /// This trigger will only be raised if you also declared a OnPickDown
  49097. get: function () {
  49098. return ActionManager._OnPickOutTrigger;
  49099. },
  49100. enumerable: true,
  49101. configurable: true
  49102. });
  49103. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49104. get: function () {
  49105. return ActionManager._OnLongPressTrigger;
  49106. },
  49107. enumerable: true,
  49108. configurable: true
  49109. });
  49110. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49111. get: function () {
  49112. return ActionManager._OnPointerOverTrigger;
  49113. },
  49114. enumerable: true,
  49115. configurable: true
  49116. });
  49117. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49118. get: function () {
  49119. return ActionManager._OnPointerOutTrigger;
  49120. },
  49121. enumerable: true,
  49122. configurable: true
  49123. });
  49124. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49125. get: function () {
  49126. return ActionManager._OnEveryFrameTrigger;
  49127. },
  49128. enumerable: true,
  49129. configurable: true
  49130. });
  49131. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49132. get: function () {
  49133. return ActionManager._OnIntersectionEnterTrigger;
  49134. },
  49135. enumerable: true,
  49136. configurable: true
  49137. });
  49138. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49139. get: function () {
  49140. return ActionManager._OnIntersectionExitTrigger;
  49141. },
  49142. enumerable: true,
  49143. configurable: true
  49144. });
  49145. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49146. get: function () {
  49147. return ActionManager._OnKeyDownTrigger;
  49148. },
  49149. enumerable: true,
  49150. configurable: true
  49151. });
  49152. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49153. get: function () {
  49154. return ActionManager._OnKeyUpTrigger;
  49155. },
  49156. enumerable: true,
  49157. configurable: true
  49158. });
  49159. // Methods
  49160. ActionManager.prototype.dispose = function () {
  49161. var index = this._scene._actionManagers.indexOf(this);
  49162. for (var i = 0; i < this.actions.length; i++) {
  49163. var action = this.actions[i];
  49164. ActionManager.Triggers[action.trigger]--;
  49165. if (ActionManager.Triggers[action.trigger] === 0) {
  49166. delete ActionManager.Triggers[action.trigger];
  49167. }
  49168. }
  49169. if (index > -1) {
  49170. this._scene._actionManagers.splice(index, 1);
  49171. }
  49172. };
  49173. ActionManager.prototype.getScene = function () {
  49174. return this._scene;
  49175. };
  49176. /**
  49177. * Does this action manager handles actions of any of the given triggers
  49178. * @param {number[]} triggers - the triggers to be tested
  49179. * @return {boolean} whether one (or more) of the triggers is handeled
  49180. */
  49181. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49182. for (var index = 0; index < this.actions.length; index++) {
  49183. var action = this.actions[index];
  49184. if (triggers.indexOf(action.trigger) > -1) {
  49185. return true;
  49186. }
  49187. }
  49188. return false;
  49189. };
  49190. /**
  49191. * Does this action manager handles actions of a given trigger
  49192. * @param {number} trigger - the trigger to be tested
  49193. * @return {boolean} whether the trigger is handeled
  49194. */
  49195. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49196. for (var index = 0; index < this.actions.length; index++) {
  49197. var action = this.actions[index];
  49198. if (action.trigger === trigger) {
  49199. return true;
  49200. }
  49201. }
  49202. return false;
  49203. };
  49204. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49205. /**
  49206. * Does this action manager has pointer triggers
  49207. * @return {boolean} whether or not it has pointer triggers
  49208. */
  49209. get: function () {
  49210. for (var index = 0; index < this.actions.length; index++) {
  49211. var action = this.actions[index];
  49212. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49213. return true;
  49214. }
  49215. }
  49216. return false;
  49217. },
  49218. enumerable: true,
  49219. configurable: true
  49220. });
  49221. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49222. /**
  49223. * Does this action manager has pick triggers
  49224. * @return {boolean} whether or not it has pick triggers
  49225. */
  49226. get: function () {
  49227. for (var index = 0; index < this.actions.length; index++) {
  49228. var action = this.actions[index];
  49229. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49230. return true;
  49231. }
  49232. }
  49233. return false;
  49234. },
  49235. enumerable: true,
  49236. configurable: true
  49237. });
  49238. Object.defineProperty(ActionManager, "HasTriggers", {
  49239. /**
  49240. * Does exist one action manager with at least one trigger
  49241. * @return {boolean} whether or not it exists one action manager with one trigger
  49242. **/
  49243. get: function () {
  49244. for (var t in ActionManager.Triggers) {
  49245. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49246. return true;
  49247. }
  49248. }
  49249. return false;
  49250. },
  49251. enumerable: true,
  49252. configurable: true
  49253. });
  49254. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49255. /**
  49256. * Does exist one action manager with at least one pick trigger
  49257. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49258. **/
  49259. get: function () {
  49260. for (var t in ActionManager.Triggers) {
  49261. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49262. var t_int = parseInt(t);
  49263. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49264. return true;
  49265. }
  49266. }
  49267. }
  49268. return false;
  49269. },
  49270. enumerable: true,
  49271. configurable: true
  49272. });
  49273. /**
  49274. * Does exist one action manager that handles actions of a given trigger
  49275. * @param {number} trigger - the trigger to be tested
  49276. * @return {boolean} whether the trigger is handeled by at least one action manager
  49277. **/
  49278. ActionManager.HasSpecificTrigger = function (trigger) {
  49279. for (var t in ActionManager.Triggers) {
  49280. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49281. var t_int = parseInt(t);
  49282. if (t_int === trigger) {
  49283. return true;
  49284. }
  49285. }
  49286. }
  49287. return false;
  49288. };
  49289. /**
  49290. * Registers an action to this action manager
  49291. * @param {BABYLON.Action} action - the action to be registered
  49292. * @return {BABYLON.Action} the action amended (prepared) after registration
  49293. */
  49294. ActionManager.prototype.registerAction = function (action) {
  49295. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49296. if (this.getScene().actionManager !== this) {
  49297. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49298. return null;
  49299. }
  49300. }
  49301. this.actions.push(action);
  49302. if (ActionManager.Triggers[action.trigger]) {
  49303. ActionManager.Triggers[action.trigger]++;
  49304. }
  49305. else {
  49306. ActionManager.Triggers[action.trigger] = 1;
  49307. }
  49308. action._actionManager = this;
  49309. action._prepare();
  49310. return action;
  49311. };
  49312. /**
  49313. * Unregisters an action to this action manager
  49314. * @param action The action to be unregistered
  49315. * @return whether the action has been unregistered
  49316. */
  49317. ActionManager.prototype.unregisterAction = function (action) {
  49318. var index = this.actions.indexOf(action);
  49319. if (index !== -1) {
  49320. this.actions.splice(index, 1);
  49321. ActionManager.Triggers[action.trigger] -= 1;
  49322. if (ActionManager.Triggers[action.trigger] === 0) {
  49323. delete ActionManager.Triggers[action.trigger];
  49324. }
  49325. delete action._actionManager;
  49326. return true;
  49327. }
  49328. return false;
  49329. };
  49330. /**
  49331. * Process a specific trigger
  49332. * @param {number} trigger - the trigger to process
  49333. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49334. */
  49335. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49336. for (var index = 0; index < this.actions.length; index++) {
  49337. var action = this.actions[index];
  49338. if (action.trigger === trigger) {
  49339. if (evt) {
  49340. if (trigger === ActionManager.OnKeyUpTrigger
  49341. || trigger === ActionManager.OnKeyDownTrigger) {
  49342. var parameter = action.getTriggerParameter();
  49343. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49344. if (!parameter.toLowerCase) {
  49345. continue;
  49346. }
  49347. var lowerCase = parameter.toLowerCase();
  49348. if (lowerCase !== evt.sourceEvent.key) {
  49349. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49350. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49351. if (actualkey !== lowerCase) {
  49352. continue;
  49353. }
  49354. }
  49355. }
  49356. }
  49357. }
  49358. action._executeCurrent(evt);
  49359. }
  49360. }
  49361. };
  49362. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49363. var properties = propertyPath.split(".");
  49364. for (var index = 0; index < properties.length - 1; index++) {
  49365. target = target[properties[index]];
  49366. }
  49367. return target;
  49368. };
  49369. ActionManager.prototype._getProperty = function (propertyPath) {
  49370. var properties = propertyPath.split(".");
  49371. return properties[properties.length - 1];
  49372. };
  49373. ActionManager.prototype.serialize = function (name) {
  49374. var root = {
  49375. children: new Array(),
  49376. name: name,
  49377. type: 3,
  49378. properties: new Array() // Empty for root but required
  49379. };
  49380. for (var i = 0; i < this.actions.length; i++) {
  49381. var triggerObject = {
  49382. type: 0,
  49383. children: new Array(),
  49384. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49385. properties: new Array()
  49386. };
  49387. var triggerOptions = this.actions[i].triggerOptions;
  49388. if (triggerOptions && typeof triggerOptions !== "number") {
  49389. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49390. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49391. }
  49392. else {
  49393. var parameter = {};
  49394. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49395. if (triggerOptions.parameter.mesh) {
  49396. parameter._meshId = triggerOptions.parameter.mesh.id;
  49397. }
  49398. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49399. }
  49400. }
  49401. // Serialize child action, recursively
  49402. this.actions[i].serialize(triggerObject);
  49403. // Add serialized trigger
  49404. root.children.push(triggerObject);
  49405. }
  49406. return root;
  49407. };
  49408. ActionManager.Parse = function (parsedActions, object, scene) {
  49409. var actionManager = new ActionManager(scene);
  49410. if (object === null)
  49411. scene.actionManager = actionManager;
  49412. else
  49413. object.actionManager = actionManager;
  49414. // instanciate a new object
  49415. var instanciate = function (name, params) {
  49416. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49417. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49418. newInstance.constructor.apply(newInstance, params);
  49419. return newInstance;
  49420. };
  49421. var parseParameter = function (name, value, target, propertyPath) {
  49422. if (propertyPath === null) {
  49423. // String, boolean or float
  49424. var floatValue = parseFloat(value);
  49425. if (value === "true" || value === "false")
  49426. return value === "true";
  49427. else
  49428. return isNaN(floatValue) ? value : floatValue;
  49429. }
  49430. var effectiveTarget = propertyPath.split(".");
  49431. var values = value.split(",");
  49432. // Get effective Target
  49433. for (var i = 0; i < effectiveTarget.length; i++) {
  49434. target = target[effectiveTarget[i]];
  49435. }
  49436. // Return appropriate value with its type
  49437. if (typeof (target) === "boolean")
  49438. return values[0] === "true";
  49439. if (typeof (target) === "string")
  49440. return values[0];
  49441. // Parameters with multiple values such as Vector3 etc.
  49442. var split = new Array();
  49443. for (var i = 0; i < values.length; i++)
  49444. split.push(parseFloat(values[i]));
  49445. if (target instanceof BABYLON.Vector3)
  49446. return BABYLON.Vector3.FromArray(split);
  49447. if (target instanceof BABYLON.Vector4)
  49448. return BABYLON.Vector4.FromArray(split);
  49449. if (target instanceof BABYLON.Color3)
  49450. return BABYLON.Color3.FromArray(split);
  49451. if (target instanceof BABYLON.Color4)
  49452. return BABYLON.Color4.FromArray(split);
  49453. return parseFloat(values[0]);
  49454. };
  49455. // traverse graph per trigger
  49456. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49457. if (combineArray === void 0) { combineArray = null; }
  49458. if (parsedAction.detached)
  49459. return;
  49460. var parameters = new Array();
  49461. var target = null;
  49462. var propertyPath = null;
  49463. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49464. // Parameters
  49465. if (parsedAction.type === 2)
  49466. parameters.push(actionManager);
  49467. else
  49468. parameters.push(trigger);
  49469. if (combine) {
  49470. var actions = new Array();
  49471. for (var j = 0; j < parsedAction.combine.length; j++) {
  49472. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49473. }
  49474. parameters.push(actions);
  49475. }
  49476. else {
  49477. for (var i = 0; i < parsedAction.properties.length; i++) {
  49478. var value = parsedAction.properties[i].value;
  49479. var name = parsedAction.properties[i].name;
  49480. var targetType = parsedAction.properties[i].targetType;
  49481. if (name === "target")
  49482. if (targetType !== null && targetType === "SceneProperties")
  49483. value = target = scene;
  49484. else
  49485. value = target = scene.getNodeByName(value);
  49486. else if (name === "parent")
  49487. value = scene.getNodeByName(value);
  49488. else if (name === "sound")
  49489. value = scene.getSoundByName(value);
  49490. else if (name !== "propertyPath") {
  49491. if (parsedAction.type === 2 && name === "operator")
  49492. value = BABYLON.ValueCondition[value];
  49493. else
  49494. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49495. }
  49496. else {
  49497. propertyPath = value;
  49498. }
  49499. parameters.push(value);
  49500. }
  49501. }
  49502. if (combineArray === null) {
  49503. parameters.push(condition);
  49504. }
  49505. else {
  49506. parameters.push(null);
  49507. }
  49508. // If interpolate value action
  49509. if (parsedAction.name === "InterpolateValueAction") {
  49510. var param = parameters[parameters.length - 2];
  49511. parameters[parameters.length - 1] = param;
  49512. parameters[parameters.length - 2] = condition;
  49513. }
  49514. // Action or condition(s) and not CombineAction
  49515. var newAction = instanciate(parsedAction.name, parameters);
  49516. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49517. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49518. if (action)
  49519. action.then(nothing);
  49520. else
  49521. actionManager.registerAction(nothing);
  49522. action = nothing;
  49523. }
  49524. if (combineArray === null) {
  49525. if (newAction instanceof BABYLON.Condition) {
  49526. condition = newAction;
  49527. newAction = action;
  49528. }
  49529. else {
  49530. condition = null;
  49531. if (action)
  49532. action.then(newAction);
  49533. else
  49534. actionManager.registerAction(newAction);
  49535. }
  49536. }
  49537. else {
  49538. combineArray.push(newAction);
  49539. }
  49540. for (var i = 0; i < parsedAction.children.length; i++)
  49541. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49542. };
  49543. // triggers
  49544. for (var i = 0; i < parsedActions.children.length; i++) {
  49545. var triggerParams;
  49546. var trigger = parsedActions.children[i];
  49547. if (trigger.properties.length > 0) {
  49548. var param = trigger.properties[0].value;
  49549. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49550. if (value._meshId) {
  49551. value.mesh = scene.getMeshByID(value._meshId);
  49552. }
  49553. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49554. }
  49555. else
  49556. triggerParams = ActionManager[trigger.name];
  49557. for (var j = 0; j < trigger.children.length; j++) {
  49558. if (!trigger.detached)
  49559. traverse(trigger.children[j], triggerParams, null, null);
  49560. }
  49561. }
  49562. };
  49563. ActionManager.GetTriggerName = function (trigger) {
  49564. switch (trigger) {
  49565. case 0: return "NothingTrigger";
  49566. case 1: return "OnPickTrigger";
  49567. case 2: return "OnLeftPickTrigger";
  49568. case 3: return "OnRightPickTrigger";
  49569. case 4: return "OnCenterPickTrigger";
  49570. case 5: return "OnPickDownTrigger";
  49571. case 6: return "OnPickUpTrigger";
  49572. case 7: return "OnLongPressTrigger";
  49573. case 8: return "OnPointerOverTrigger";
  49574. case 9: return "OnPointerOutTrigger";
  49575. case 10: return "OnEveryFrameTrigger";
  49576. case 11: return "OnIntersectionEnterTrigger";
  49577. case 12: return "OnIntersectionExitTrigger";
  49578. case 13: return "OnKeyDownTrigger";
  49579. case 14: return "OnKeyUpTrigger";
  49580. case 15: return "OnPickOutTrigger";
  49581. default: return "";
  49582. }
  49583. };
  49584. // Statics
  49585. ActionManager._NothingTrigger = 0;
  49586. ActionManager._OnPickTrigger = 1;
  49587. ActionManager._OnLeftPickTrigger = 2;
  49588. ActionManager._OnRightPickTrigger = 3;
  49589. ActionManager._OnCenterPickTrigger = 4;
  49590. ActionManager._OnPickDownTrigger = 5;
  49591. ActionManager._OnDoublePickTrigger = 6;
  49592. ActionManager._OnPickUpTrigger = 7;
  49593. ActionManager._OnLongPressTrigger = 8;
  49594. ActionManager._OnPointerOverTrigger = 9;
  49595. ActionManager._OnPointerOutTrigger = 10;
  49596. ActionManager._OnEveryFrameTrigger = 11;
  49597. ActionManager._OnIntersectionEnterTrigger = 12;
  49598. ActionManager._OnIntersectionExitTrigger = 13;
  49599. ActionManager._OnKeyDownTrigger = 14;
  49600. ActionManager._OnKeyUpTrigger = 15;
  49601. ActionManager._OnPickOutTrigger = 16;
  49602. ActionManager.Triggers = {};
  49603. return ActionManager;
  49604. }());
  49605. BABYLON.ActionManager = ActionManager;
  49606. })(BABYLON || (BABYLON = {}));
  49607. //# sourceMappingURL=babylon.actionManager.js.map
  49608. "use strict";
  49609. var BABYLON;
  49610. (function (BABYLON) {
  49611. var InterpolateValueAction = /** @class */ (function (_super) {
  49612. __extends(InterpolateValueAction, _super);
  49613. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49614. if (duration === void 0) { duration = 1000; }
  49615. var _this = _super.call(this, triggerOptions, condition) || this;
  49616. _this.propertyPath = propertyPath;
  49617. _this.value = value;
  49618. _this.duration = duration;
  49619. _this.stopOtherAnimations = stopOtherAnimations;
  49620. _this.onInterpolationDone = onInterpolationDone;
  49621. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49622. _this._target = _this._effectiveTarget = target;
  49623. return _this;
  49624. }
  49625. InterpolateValueAction.prototype._prepare = function () {
  49626. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49627. this._property = this._getProperty(this.propertyPath);
  49628. };
  49629. InterpolateValueAction.prototype.execute = function () {
  49630. var _this = this;
  49631. var scene = this._actionManager.getScene();
  49632. var keys = [
  49633. {
  49634. frame: 0,
  49635. value: this._effectiveTarget[this._property]
  49636. }, {
  49637. frame: 100,
  49638. value: this.value
  49639. }
  49640. ];
  49641. var dataType;
  49642. if (typeof this.value === "number") {
  49643. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49644. }
  49645. else if (this.value instanceof BABYLON.Color3) {
  49646. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49647. }
  49648. else if (this.value instanceof BABYLON.Vector3) {
  49649. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49650. }
  49651. else if (this.value instanceof BABYLON.Matrix) {
  49652. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49653. }
  49654. else if (this.value instanceof BABYLON.Quaternion) {
  49655. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49656. }
  49657. else {
  49658. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49659. return;
  49660. }
  49661. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49662. animation.setKeys(keys);
  49663. if (this.stopOtherAnimations) {
  49664. scene.stopAnimation(this._effectiveTarget);
  49665. }
  49666. var wrapper = function () {
  49667. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49668. if (_this.onInterpolationDone) {
  49669. _this.onInterpolationDone();
  49670. }
  49671. };
  49672. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49673. };
  49674. InterpolateValueAction.prototype.serialize = function (parent) {
  49675. return _super.prototype._serialize.call(this, {
  49676. name: "InterpolateValueAction",
  49677. properties: [
  49678. BABYLON.Action._GetTargetProperty(this._target),
  49679. { name: "propertyPath", value: this.propertyPath },
  49680. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49681. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49682. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49683. ]
  49684. }, parent);
  49685. };
  49686. return InterpolateValueAction;
  49687. }(BABYLON.Action));
  49688. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49689. })(BABYLON || (BABYLON = {}));
  49690. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49691. "use strict";
  49692. var BABYLON;
  49693. (function (BABYLON) {
  49694. var SwitchBooleanAction = /** @class */ (function (_super) {
  49695. __extends(SwitchBooleanAction, _super);
  49696. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49697. var _this = _super.call(this, triggerOptions, condition) || this;
  49698. _this.propertyPath = propertyPath;
  49699. _this._target = _this._effectiveTarget = target;
  49700. return _this;
  49701. }
  49702. SwitchBooleanAction.prototype._prepare = function () {
  49703. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49704. this._property = this._getProperty(this.propertyPath);
  49705. };
  49706. SwitchBooleanAction.prototype.execute = function () {
  49707. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49708. };
  49709. SwitchBooleanAction.prototype.serialize = function (parent) {
  49710. return _super.prototype._serialize.call(this, {
  49711. name: "SwitchBooleanAction",
  49712. properties: [
  49713. BABYLON.Action._GetTargetProperty(this._target),
  49714. { name: "propertyPath", value: this.propertyPath }
  49715. ]
  49716. }, parent);
  49717. };
  49718. return SwitchBooleanAction;
  49719. }(BABYLON.Action));
  49720. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49721. var SetStateAction = /** @class */ (function (_super) {
  49722. __extends(SetStateAction, _super);
  49723. function SetStateAction(triggerOptions, target, value, condition) {
  49724. var _this = _super.call(this, triggerOptions, condition) || this;
  49725. _this.value = value;
  49726. _this._target = target;
  49727. return _this;
  49728. }
  49729. SetStateAction.prototype.execute = function () {
  49730. this._target.state = this.value;
  49731. };
  49732. SetStateAction.prototype.serialize = function (parent) {
  49733. return _super.prototype._serialize.call(this, {
  49734. name: "SetStateAction",
  49735. properties: [
  49736. BABYLON.Action._GetTargetProperty(this._target),
  49737. { name: "value", value: this.value }
  49738. ]
  49739. }, parent);
  49740. };
  49741. return SetStateAction;
  49742. }(BABYLON.Action));
  49743. BABYLON.SetStateAction = SetStateAction;
  49744. var SetValueAction = /** @class */ (function (_super) {
  49745. __extends(SetValueAction, _super);
  49746. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49747. var _this = _super.call(this, triggerOptions, condition) || this;
  49748. _this.propertyPath = propertyPath;
  49749. _this.value = value;
  49750. _this._target = _this._effectiveTarget = target;
  49751. return _this;
  49752. }
  49753. SetValueAction.prototype._prepare = function () {
  49754. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49755. this._property = this._getProperty(this.propertyPath);
  49756. };
  49757. SetValueAction.prototype.execute = function () {
  49758. this._effectiveTarget[this._property] = this.value;
  49759. if (this._target.markAsDirty) {
  49760. this._target.markAsDirty(this._property);
  49761. }
  49762. };
  49763. SetValueAction.prototype.serialize = function (parent) {
  49764. return _super.prototype._serialize.call(this, {
  49765. name: "SetValueAction",
  49766. properties: [
  49767. BABYLON.Action._GetTargetProperty(this._target),
  49768. { name: "propertyPath", value: this.propertyPath },
  49769. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49770. ]
  49771. }, parent);
  49772. };
  49773. return SetValueAction;
  49774. }(BABYLON.Action));
  49775. BABYLON.SetValueAction = SetValueAction;
  49776. var IncrementValueAction = /** @class */ (function (_super) {
  49777. __extends(IncrementValueAction, _super);
  49778. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49779. var _this = _super.call(this, triggerOptions, condition) || this;
  49780. _this.propertyPath = propertyPath;
  49781. _this.value = value;
  49782. _this._target = _this._effectiveTarget = target;
  49783. return _this;
  49784. }
  49785. IncrementValueAction.prototype._prepare = function () {
  49786. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49787. this._property = this._getProperty(this.propertyPath);
  49788. if (typeof this._effectiveTarget[this._property] !== "number") {
  49789. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49790. }
  49791. };
  49792. IncrementValueAction.prototype.execute = function () {
  49793. this._effectiveTarget[this._property] += this.value;
  49794. if (this._target.markAsDirty) {
  49795. this._target.markAsDirty(this._property);
  49796. }
  49797. };
  49798. IncrementValueAction.prototype.serialize = function (parent) {
  49799. return _super.prototype._serialize.call(this, {
  49800. name: "IncrementValueAction",
  49801. properties: [
  49802. BABYLON.Action._GetTargetProperty(this._target),
  49803. { name: "propertyPath", value: this.propertyPath },
  49804. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49805. ]
  49806. }, parent);
  49807. };
  49808. return IncrementValueAction;
  49809. }(BABYLON.Action));
  49810. BABYLON.IncrementValueAction = IncrementValueAction;
  49811. var PlayAnimationAction = /** @class */ (function (_super) {
  49812. __extends(PlayAnimationAction, _super);
  49813. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49814. var _this = _super.call(this, triggerOptions, condition) || this;
  49815. _this.from = from;
  49816. _this.to = to;
  49817. _this.loop = loop;
  49818. _this._target = target;
  49819. return _this;
  49820. }
  49821. PlayAnimationAction.prototype._prepare = function () {
  49822. };
  49823. PlayAnimationAction.prototype.execute = function () {
  49824. var scene = this._actionManager.getScene();
  49825. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49826. };
  49827. PlayAnimationAction.prototype.serialize = function (parent) {
  49828. return _super.prototype._serialize.call(this, {
  49829. name: "PlayAnimationAction",
  49830. properties: [
  49831. BABYLON.Action._GetTargetProperty(this._target),
  49832. { name: "from", value: String(this.from) },
  49833. { name: "to", value: String(this.to) },
  49834. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49835. ]
  49836. }, parent);
  49837. };
  49838. return PlayAnimationAction;
  49839. }(BABYLON.Action));
  49840. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49841. var StopAnimationAction = /** @class */ (function (_super) {
  49842. __extends(StopAnimationAction, _super);
  49843. function StopAnimationAction(triggerOptions, target, condition) {
  49844. var _this = _super.call(this, triggerOptions, condition) || this;
  49845. _this._target = target;
  49846. return _this;
  49847. }
  49848. StopAnimationAction.prototype._prepare = function () {
  49849. };
  49850. StopAnimationAction.prototype.execute = function () {
  49851. var scene = this._actionManager.getScene();
  49852. scene.stopAnimation(this._target);
  49853. };
  49854. StopAnimationAction.prototype.serialize = function (parent) {
  49855. return _super.prototype._serialize.call(this, {
  49856. name: "StopAnimationAction",
  49857. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49858. }, parent);
  49859. };
  49860. return StopAnimationAction;
  49861. }(BABYLON.Action));
  49862. BABYLON.StopAnimationAction = StopAnimationAction;
  49863. var DoNothingAction = /** @class */ (function (_super) {
  49864. __extends(DoNothingAction, _super);
  49865. function DoNothingAction(triggerOptions, condition) {
  49866. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49867. return _super.call(this, triggerOptions, condition) || this;
  49868. }
  49869. DoNothingAction.prototype.execute = function () {
  49870. };
  49871. DoNothingAction.prototype.serialize = function (parent) {
  49872. return _super.prototype._serialize.call(this, {
  49873. name: "DoNothingAction",
  49874. properties: []
  49875. }, parent);
  49876. };
  49877. return DoNothingAction;
  49878. }(BABYLON.Action));
  49879. BABYLON.DoNothingAction = DoNothingAction;
  49880. var CombineAction = /** @class */ (function (_super) {
  49881. __extends(CombineAction, _super);
  49882. function CombineAction(triggerOptions, children, condition) {
  49883. var _this = _super.call(this, triggerOptions, condition) || this;
  49884. _this.children = children;
  49885. return _this;
  49886. }
  49887. CombineAction.prototype._prepare = function () {
  49888. for (var index = 0; index < this.children.length; index++) {
  49889. this.children[index]._actionManager = this._actionManager;
  49890. this.children[index]._prepare();
  49891. }
  49892. };
  49893. CombineAction.prototype.execute = function (evt) {
  49894. for (var index = 0; index < this.children.length; index++) {
  49895. this.children[index].execute(evt);
  49896. }
  49897. };
  49898. CombineAction.prototype.serialize = function (parent) {
  49899. var serializationObject = _super.prototype._serialize.call(this, {
  49900. name: "CombineAction",
  49901. properties: [],
  49902. combine: []
  49903. }, parent);
  49904. for (var i = 0; i < this.children.length; i++) {
  49905. serializationObject.combine.push(this.children[i].serialize(null));
  49906. }
  49907. return serializationObject;
  49908. };
  49909. return CombineAction;
  49910. }(BABYLON.Action));
  49911. BABYLON.CombineAction = CombineAction;
  49912. var ExecuteCodeAction = /** @class */ (function (_super) {
  49913. __extends(ExecuteCodeAction, _super);
  49914. function ExecuteCodeAction(triggerOptions, func, condition) {
  49915. var _this = _super.call(this, triggerOptions, condition) || this;
  49916. _this.func = func;
  49917. return _this;
  49918. }
  49919. ExecuteCodeAction.prototype.execute = function (evt) {
  49920. this.func(evt);
  49921. };
  49922. return ExecuteCodeAction;
  49923. }(BABYLON.Action));
  49924. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49925. var SetParentAction = /** @class */ (function (_super) {
  49926. __extends(SetParentAction, _super);
  49927. function SetParentAction(triggerOptions, target, parent, condition) {
  49928. var _this = _super.call(this, triggerOptions, condition) || this;
  49929. _this._target = target;
  49930. _this._parent = parent;
  49931. return _this;
  49932. }
  49933. SetParentAction.prototype._prepare = function () {
  49934. };
  49935. SetParentAction.prototype.execute = function () {
  49936. if (this._target.parent === this._parent) {
  49937. return;
  49938. }
  49939. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49940. invertParentWorldMatrix.invert();
  49941. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49942. this._target.parent = this._parent;
  49943. };
  49944. SetParentAction.prototype.serialize = function (parent) {
  49945. return _super.prototype._serialize.call(this, {
  49946. name: "SetParentAction",
  49947. properties: [
  49948. BABYLON.Action._GetTargetProperty(this._target),
  49949. BABYLON.Action._GetTargetProperty(this._parent),
  49950. ]
  49951. }, parent);
  49952. };
  49953. return SetParentAction;
  49954. }(BABYLON.Action));
  49955. BABYLON.SetParentAction = SetParentAction;
  49956. var PlaySoundAction = /** @class */ (function (_super) {
  49957. __extends(PlaySoundAction, _super);
  49958. function PlaySoundAction(triggerOptions, sound, condition) {
  49959. var _this = _super.call(this, triggerOptions, condition) || this;
  49960. _this._sound = sound;
  49961. return _this;
  49962. }
  49963. PlaySoundAction.prototype._prepare = function () {
  49964. };
  49965. PlaySoundAction.prototype.execute = function () {
  49966. if (this._sound !== undefined)
  49967. this._sound.play();
  49968. };
  49969. PlaySoundAction.prototype.serialize = function (parent) {
  49970. return _super.prototype._serialize.call(this, {
  49971. name: "PlaySoundAction",
  49972. properties: [{ name: "sound", value: this._sound.name }]
  49973. }, parent);
  49974. };
  49975. return PlaySoundAction;
  49976. }(BABYLON.Action));
  49977. BABYLON.PlaySoundAction = PlaySoundAction;
  49978. var StopSoundAction = /** @class */ (function (_super) {
  49979. __extends(StopSoundAction, _super);
  49980. function StopSoundAction(triggerOptions, sound, condition) {
  49981. var _this = _super.call(this, triggerOptions, condition) || this;
  49982. _this._sound = sound;
  49983. return _this;
  49984. }
  49985. StopSoundAction.prototype._prepare = function () {
  49986. };
  49987. StopSoundAction.prototype.execute = function () {
  49988. if (this._sound !== undefined)
  49989. this._sound.stop();
  49990. };
  49991. StopSoundAction.prototype.serialize = function (parent) {
  49992. return _super.prototype._serialize.call(this, {
  49993. name: "StopSoundAction",
  49994. properties: [{ name: "sound", value: this._sound.name }]
  49995. }, parent);
  49996. };
  49997. return StopSoundAction;
  49998. }(BABYLON.Action));
  49999. BABYLON.StopSoundAction = StopSoundAction;
  50000. })(BABYLON || (BABYLON = {}));
  50001. //# sourceMappingURL=babylon.directActions.js.map
  50002. "use strict";
  50003. var BABYLON;
  50004. (function (BABYLON) {
  50005. var SpriteManager = /** @class */ (function () {
  50006. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  50007. if (epsilon === void 0) { epsilon = 0.01; }
  50008. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50009. this.name = name;
  50010. this.sprites = new Array();
  50011. this.renderingGroupId = 0;
  50012. this.layerMask = 0x0FFFFFFF;
  50013. this.fogEnabled = true;
  50014. this.isPickable = false;
  50015. /**
  50016. * An event triggered when the manager is disposed.
  50017. * @type {BABYLON.Observable}
  50018. */
  50019. this.onDisposeObservable = new BABYLON.Observable();
  50020. this._vertexBuffers = {};
  50021. this._capacity = capacity;
  50022. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50023. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50024. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50025. if (cellSize.width && cellSize.height) {
  50026. this.cellWidth = cellSize.width;
  50027. this.cellHeight = cellSize.height;
  50028. }
  50029. else if (cellSize !== undefined) {
  50030. this.cellWidth = cellSize;
  50031. this.cellHeight = cellSize;
  50032. }
  50033. else {
  50034. return;
  50035. }
  50036. this._epsilon = epsilon;
  50037. this._scene = scene;
  50038. this._scene.spriteManagers.push(this);
  50039. var indices = [];
  50040. var index = 0;
  50041. for (var count = 0; count < capacity; count++) {
  50042. indices.push(index);
  50043. indices.push(index + 1);
  50044. indices.push(index + 2);
  50045. indices.push(index);
  50046. indices.push(index + 2);
  50047. indices.push(index + 3);
  50048. index += 4;
  50049. }
  50050. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50051. // VBO
  50052. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50053. this._vertexData = new Float32Array(capacity * 16 * 4);
  50054. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50055. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50056. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50057. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50058. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50059. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50060. this._vertexBuffers["options"] = options;
  50061. this._vertexBuffers["cellInfo"] = cellInfo;
  50062. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50063. // Effects
  50064. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50065. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50066. }
  50067. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50068. set: function (callback) {
  50069. if (this._onDisposeObserver) {
  50070. this.onDisposeObservable.remove(this._onDisposeObserver);
  50071. }
  50072. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50073. },
  50074. enumerable: true,
  50075. configurable: true
  50076. });
  50077. Object.defineProperty(SpriteManager.prototype, "texture", {
  50078. get: function () {
  50079. return this._spriteTexture;
  50080. },
  50081. set: function (value) {
  50082. this._spriteTexture = value;
  50083. },
  50084. enumerable: true,
  50085. configurable: true
  50086. });
  50087. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50088. var arrayOffset = index * 16;
  50089. if (offsetX === 0)
  50090. offsetX = this._epsilon;
  50091. else if (offsetX === 1)
  50092. offsetX = 1 - this._epsilon;
  50093. if (offsetY === 0)
  50094. offsetY = this._epsilon;
  50095. else if (offsetY === 1)
  50096. offsetY = 1 - this._epsilon;
  50097. this._vertexData[arrayOffset] = sprite.position.x;
  50098. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50099. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50100. this._vertexData[arrayOffset + 3] = sprite.angle;
  50101. this._vertexData[arrayOffset + 4] = sprite.width;
  50102. this._vertexData[arrayOffset + 5] = sprite.height;
  50103. this._vertexData[arrayOffset + 6] = offsetX;
  50104. this._vertexData[arrayOffset + 7] = offsetY;
  50105. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50106. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50107. var offset = (sprite.cellIndex / rowSize) >> 0;
  50108. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50109. this._vertexData[arrayOffset + 11] = offset;
  50110. // Color
  50111. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50112. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50113. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50114. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50115. };
  50116. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50117. var count = Math.min(this._capacity, this.sprites.length);
  50118. var min = BABYLON.Vector3.Zero();
  50119. var max = BABYLON.Vector3.Zero();
  50120. var distance = Number.MAX_VALUE;
  50121. var currentSprite = null;
  50122. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50123. var cameraView = camera.getViewMatrix();
  50124. for (var index = 0; index < count; index++) {
  50125. var sprite = this.sprites[index];
  50126. if (!sprite) {
  50127. continue;
  50128. }
  50129. if (predicate) {
  50130. if (!predicate(sprite)) {
  50131. continue;
  50132. }
  50133. }
  50134. else if (!sprite.isPickable) {
  50135. continue;
  50136. }
  50137. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50138. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50139. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50140. if (ray.intersectsBoxMinMax(min, max)) {
  50141. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50142. if (distance > currentDistance) {
  50143. distance = currentDistance;
  50144. currentSprite = sprite;
  50145. if (fastCheck) {
  50146. break;
  50147. }
  50148. }
  50149. }
  50150. }
  50151. if (currentSprite) {
  50152. var result = new BABYLON.PickingInfo();
  50153. result.hit = true;
  50154. result.pickedSprite = currentSprite;
  50155. result.distance = distance;
  50156. return result;
  50157. }
  50158. return null;
  50159. };
  50160. SpriteManager.prototype.render = function () {
  50161. // Check
  50162. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50163. return;
  50164. var engine = this._scene.getEngine();
  50165. var baseSize = this._spriteTexture.getBaseSize();
  50166. // Sprites
  50167. var deltaTime = engine.getDeltaTime();
  50168. var max = Math.min(this._capacity, this.sprites.length);
  50169. var rowSize = baseSize.width / this.cellWidth;
  50170. var offset = 0;
  50171. for (var index = 0; index < max; index++) {
  50172. var sprite = this.sprites[index];
  50173. if (!sprite) {
  50174. continue;
  50175. }
  50176. sprite._animate(deltaTime);
  50177. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50178. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50179. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50180. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50181. }
  50182. this._buffer.update(this._vertexData);
  50183. // Render
  50184. var effect = this._effectBase;
  50185. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50186. effect = this._effectFog;
  50187. }
  50188. engine.enableEffect(effect);
  50189. var viewMatrix = this._scene.getViewMatrix();
  50190. effect.setTexture("diffuseSampler", this._spriteTexture);
  50191. effect.setMatrix("view", viewMatrix);
  50192. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50193. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50194. // Fog
  50195. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50196. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50197. effect.setColor3("vFogColor", this._scene.fogColor);
  50198. }
  50199. // VBOs
  50200. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50201. // Draw order
  50202. engine.setDepthFunctionToLessOrEqual();
  50203. effect.setBool("alphaTest", true);
  50204. engine.setColorWrite(false);
  50205. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50206. engine.setColorWrite(true);
  50207. effect.setBool("alphaTest", false);
  50208. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50209. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50210. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50211. };
  50212. SpriteManager.prototype.dispose = function () {
  50213. if (this._buffer) {
  50214. this._buffer.dispose();
  50215. this._buffer = null;
  50216. }
  50217. if (this._indexBuffer) {
  50218. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50219. this._indexBuffer = null;
  50220. }
  50221. if (this._spriteTexture) {
  50222. this._spriteTexture.dispose();
  50223. this._spriteTexture = null;
  50224. }
  50225. // Remove from scene
  50226. var index = this._scene.spriteManagers.indexOf(this);
  50227. this._scene.spriteManagers.splice(index, 1);
  50228. // Callback
  50229. this.onDisposeObservable.notifyObservers(this);
  50230. this.onDisposeObservable.clear();
  50231. };
  50232. return SpriteManager;
  50233. }());
  50234. BABYLON.SpriteManager = SpriteManager;
  50235. })(BABYLON || (BABYLON = {}));
  50236. //# sourceMappingURL=babylon.spriteManager.js.map
  50237. "use strict";
  50238. var BABYLON;
  50239. (function (BABYLON) {
  50240. var Sprite = /** @class */ (function () {
  50241. function Sprite(name, manager) {
  50242. this.name = name;
  50243. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50244. this.width = 1.0;
  50245. this.height = 1.0;
  50246. this.angle = 0;
  50247. this.cellIndex = 0;
  50248. this.invertU = 0;
  50249. this.invertV = 0;
  50250. this.animations = new Array();
  50251. this.isPickable = false;
  50252. this._animationStarted = false;
  50253. this._loopAnimation = false;
  50254. this._fromIndex = 0;
  50255. this._toIndex = 0;
  50256. this._delay = 0;
  50257. this._direction = 1;
  50258. this._time = 0;
  50259. this._manager = manager;
  50260. this._manager.sprites.push(this);
  50261. this.position = BABYLON.Vector3.Zero();
  50262. }
  50263. Object.defineProperty(Sprite.prototype, "size", {
  50264. get: function () {
  50265. return this.width;
  50266. },
  50267. set: function (value) {
  50268. this.width = value;
  50269. this.height = value;
  50270. },
  50271. enumerable: true,
  50272. configurable: true
  50273. });
  50274. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50275. this._fromIndex = from;
  50276. this._toIndex = to;
  50277. this._loopAnimation = loop;
  50278. this._delay = delay;
  50279. this._animationStarted = true;
  50280. this._direction = from < to ? 1 : -1;
  50281. this.cellIndex = from;
  50282. this._time = 0;
  50283. this._onAnimationEnd = onAnimationEnd;
  50284. };
  50285. Sprite.prototype.stopAnimation = function () {
  50286. this._animationStarted = false;
  50287. };
  50288. Sprite.prototype._animate = function (deltaTime) {
  50289. if (!this._animationStarted)
  50290. return;
  50291. this._time += deltaTime;
  50292. if (this._time > this._delay) {
  50293. this._time = this._time % this._delay;
  50294. this.cellIndex += this._direction;
  50295. if (this.cellIndex > this._toIndex) {
  50296. if (this._loopAnimation) {
  50297. this.cellIndex = this._fromIndex;
  50298. }
  50299. else {
  50300. this.cellIndex = this._toIndex;
  50301. this._animationStarted = false;
  50302. if (this._onAnimationEnd) {
  50303. this._onAnimationEnd();
  50304. }
  50305. if (this.disposeWhenFinishedAnimating) {
  50306. this.dispose();
  50307. }
  50308. }
  50309. }
  50310. }
  50311. };
  50312. Sprite.prototype.dispose = function () {
  50313. for (var i = 0; i < this._manager.sprites.length; i++) {
  50314. if (this._manager.sprites[i] == this) {
  50315. this._manager.sprites.splice(i, 1);
  50316. }
  50317. }
  50318. };
  50319. return Sprite;
  50320. }());
  50321. BABYLON.Sprite = Sprite;
  50322. })(BABYLON || (BABYLON = {}));
  50323. //# sourceMappingURL=babylon.sprite.js.map
  50324. "use strict";
  50325. var BABYLON;
  50326. (function (BABYLON) {
  50327. var IntersectionInfo = /** @class */ (function () {
  50328. function IntersectionInfo(bu, bv, distance) {
  50329. this.bu = bu;
  50330. this.bv = bv;
  50331. this.distance = distance;
  50332. this.faceId = 0;
  50333. this.subMeshId = 0;
  50334. }
  50335. return IntersectionInfo;
  50336. }());
  50337. BABYLON.IntersectionInfo = IntersectionInfo;
  50338. var PickingInfo = /** @class */ (function () {
  50339. function PickingInfo() {
  50340. this.hit = false;
  50341. this.distance = 0;
  50342. this.pickedPoint = null;
  50343. this.pickedMesh = null;
  50344. this.bu = 0;
  50345. this.bv = 0;
  50346. this.faceId = -1;
  50347. this.subMeshId = 0;
  50348. this.pickedSprite = null;
  50349. }
  50350. // Methods
  50351. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50352. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50353. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50354. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50355. return null;
  50356. }
  50357. var indices = this.pickedMesh.getIndices();
  50358. if (!indices) {
  50359. return null;
  50360. }
  50361. var result;
  50362. if (useVerticesNormals) {
  50363. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50364. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50365. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50366. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50367. normal0 = normal0.scale(this.bu);
  50368. normal1 = normal1.scale(this.bv);
  50369. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50370. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50371. }
  50372. else {
  50373. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50374. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50375. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50376. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50377. var p1p2 = vertex1.subtract(vertex2);
  50378. var p3p2 = vertex3.subtract(vertex2);
  50379. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50380. }
  50381. if (useWorldCoordinates) {
  50382. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50383. }
  50384. return BABYLON.Vector3.Normalize(result);
  50385. };
  50386. PickingInfo.prototype.getTextureCoordinates = function () {
  50387. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50388. return null;
  50389. }
  50390. var indices = this.pickedMesh.getIndices();
  50391. if (!indices) {
  50392. return null;
  50393. }
  50394. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50395. if (!uvs) {
  50396. return null;
  50397. }
  50398. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50399. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50400. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50401. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50402. uv1 = uv1.scale(this.bu);
  50403. uv2 = uv2.scale(this.bv);
  50404. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50405. };
  50406. return PickingInfo;
  50407. }());
  50408. BABYLON.PickingInfo = PickingInfo;
  50409. })(BABYLON || (BABYLON = {}));
  50410. //# sourceMappingURL=babylon.pickingInfo.js.map
  50411. "use strict";
  50412. var BABYLON;
  50413. (function (BABYLON) {
  50414. var Ray = /** @class */ (function () {
  50415. function Ray(origin, direction, length) {
  50416. if (length === void 0) { length = Number.MAX_VALUE; }
  50417. this.origin = origin;
  50418. this.direction = direction;
  50419. this.length = length;
  50420. }
  50421. // Methods
  50422. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50423. var d = 0.0;
  50424. var maxValue = Number.MAX_VALUE;
  50425. var inv;
  50426. var min;
  50427. var max;
  50428. var temp;
  50429. if (Math.abs(this.direction.x) < 0.0000001) {
  50430. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50431. return false;
  50432. }
  50433. }
  50434. else {
  50435. inv = 1.0 / this.direction.x;
  50436. min = (minimum.x - this.origin.x) * inv;
  50437. max = (maximum.x - this.origin.x) * inv;
  50438. if (max === -Infinity) {
  50439. max = Infinity;
  50440. }
  50441. if (min > max) {
  50442. temp = min;
  50443. min = max;
  50444. max = temp;
  50445. }
  50446. d = Math.max(min, d);
  50447. maxValue = Math.min(max, maxValue);
  50448. if (d > maxValue) {
  50449. return false;
  50450. }
  50451. }
  50452. if (Math.abs(this.direction.y) < 0.0000001) {
  50453. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50454. return false;
  50455. }
  50456. }
  50457. else {
  50458. inv = 1.0 / this.direction.y;
  50459. min = (minimum.y - this.origin.y) * inv;
  50460. max = (maximum.y - this.origin.y) * inv;
  50461. if (max === -Infinity) {
  50462. max = Infinity;
  50463. }
  50464. if (min > max) {
  50465. temp = min;
  50466. min = max;
  50467. max = temp;
  50468. }
  50469. d = Math.max(min, d);
  50470. maxValue = Math.min(max, maxValue);
  50471. if (d > maxValue) {
  50472. return false;
  50473. }
  50474. }
  50475. if (Math.abs(this.direction.z) < 0.0000001) {
  50476. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50477. return false;
  50478. }
  50479. }
  50480. else {
  50481. inv = 1.0 / this.direction.z;
  50482. min = (minimum.z - this.origin.z) * inv;
  50483. max = (maximum.z - this.origin.z) * inv;
  50484. if (max === -Infinity) {
  50485. max = Infinity;
  50486. }
  50487. if (min > max) {
  50488. temp = min;
  50489. min = max;
  50490. max = temp;
  50491. }
  50492. d = Math.max(min, d);
  50493. maxValue = Math.min(max, maxValue);
  50494. if (d > maxValue) {
  50495. return false;
  50496. }
  50497. }
  50498. return true;
  50499. };
  50500. Ray.prototype.intersectsBox = function (box) {
  50501. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50502. };
  50503. Ray.prototype.intersectsSphere = function (sphere) {
  50504. var x = sphere.center.x - this.origin.x;
  50505. var y = sphere.center.y - this.origin.y;
  50506. var z = sphere.center.z - this.origin.z;
  50507. var pyth = (x * x) + (y * y) + (z * z);
  50508. var rr = sphere.radius * sphere.radius;
  50509. if (pyth <= rr) {
  50510. return true;
  50511. }
  50512. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50513. if (dot < 0.0) {
  50514. return false;
  50515. }
  50516. var temp = pyth - (dot * dot);
  50517. return temp <= rr;
  50518. };
  50519. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50520. if (!this._edge1) {
  50521. this._edge1 = BABYLON.Vector3.Zero();
  50522. this._edge2 = BABYLON.Vector3.Zero();
  50523. this._pvec = BABYLON.Vector3.Zero();
  50524. this._tvec = BABYLON.Vector3.Zero();
  50525. this._qvec = BABYLON.Vector3.Zero();
  50526. }
  50527. vertex1.subtractToRef(vertex0, this._edge1);
  50528. vertex2.subtractToRef(vertex0, this._edge2);
  50529. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50530. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50531. if (det === 0) {
  50532. return null;
  50533. }
  50534. var invdet = 1 / det;
  50535. this.origin.subtractToRef(vertex0, this._tvec);
  50536. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50537. if (bu < 0 || bu > 1.0) {
  50538. return null;
  50539. }
  50540. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50541. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50542. if (bv < 0 || bu + bv > 1.0) {
  50543. return null;
  50544. }
  50545. //check if the distance is longer than the predefined length.
  50546. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50547. if (distance > this.length) {
  50548. return null;
  50549. }
  50550. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50551. };
  50552. Ray.prototype.intersectsPlane = function (plane) {
  50553. var distance;
  50554. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50555. if (Math.abs(result1) < 9.99999997475243E-07) {
  50556. return null;
  50557. }
  50558. else {
  50559. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50560. distance = (-plane.d - result2) / result1;
  50561. if (distance < 0.0) {
  50562. if (distance < -9.99999997475243E-07) {
  50563. return null;
  50564. }
  50565. else {
  50566. return 0;
  50567. }
  50568. }
  50569. return distance;
  50570. }
  50571. };
  50572. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50573. var tm = BABYLON.Tmp.Matrix[0];
  50574. mesh.getWorldMatrix().invertToRef(tm);
  50575. if (this._tmpRay) {
  50576. Ray.TransformToRef(this, tm, this._tmpRay);
  50577. }
  50578. else {
  50579. this._tmpRay = Ray.Transform(this, tm);
  50580. }
  50581. return mesh.intersects(this._tmpRay, fastCheck);
  50582. };
  50583. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50584. if (results) {
  50585. results.length = 0;
  50586. }
  50587. else {
  50588. results = [];
  50589. }
  50590. for (var i = 0; i < meshes.length; i++) {
  50591. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50592. if (pickInfo.hit) {
  50593. results.push(pickInfo);
  50594. }
  50595. }
  50596. results.sort(this._comparePickingInfo);
  50597. return results;
  50598. };
  50599. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50600. if (pickingInfoA.distance < pickingInfoB.distance) {
  50601. return -1;
  50602. }
  50603. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50604. return 1;
  50605. }
  50606. else {
  50607. return 0;
  50608. }
  50609. };
  50610. /**
  50611. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50612. * @param sega the first point of the segment to test the intersection against
  50613. * @param segb the second point of the segment to test the intersection against
  50614. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50615. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50616. */
  50617. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50618. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50619. var u = segb.subtract(sega);
  50620. var v = rsegb.subtract(this.origin);
  50621. var w = sega.subtract(this.origin);
  50622. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50623. var b = BABYLON.Vector3.Dot(u, v);
  50624. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50625. var d = BABYLON.Vector3.Dot(u, w);
  50626. var e = BABYLON.Vector3.Dot(v, w);
  50627. var D = a * c - b * b; // always >= 0
  50628. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50629. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50630. // compute the line parameters of the two closest points
  50631. if (D < Ray.smallnum) {
  50632. sN = 0.0; // force using point P0 on segment S1
  50633. sD = 1.0; // to prevent possible division by 0.0 later
  50634. tN = e;
  50635. tD = c;
  50636. }
  50637. else {
  50638. sN = (b * e - c * d);
  50639. tN = (a * e - b * d);
  50640. if (sN < 0.0) {
  50641. sN = 0.0;
  50642. tN = e;
  50643. tD = c;
  50644. }
  50645. else if (sN > sD) {
  50646. sN = sD;
  50647. tN = e + b;
  50648. tD = c;
  50649. }
  50650. }
  50651. if (tN < 0.0) {
  50652. tN = 0.0;
  50653. // recompute sc for this edge
  50654. if (-d < 0.0) {
  50655. sN = 0.0;
  50656. }
  50657. else if (-d > a)
  50658. sN = sD;
  50659. else {
  50660. sN = -d;
  50661. sD = a;
  50662. }
  50663. }
  50664. else if (tN > tD) {
  50665. tN = tD;
  50666. // recompute sc for this edge
  50667. if ((-d + b) < 0.0) {
  50668. sN = 0;
  50669. }
  50670. else if ((-d + b) > a) {
  50671. sN = sD;
  50672. }
  50673. else {
  50674. sN = (-d + b);
  50675. sD = a;
  50676. }
  50677. }
  50678. // finally do the division to get sc and tc
  50679. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50680. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50681. // get the difference of the two closest points
  50682. var qtc = v.multiplyByFloats(tc, tc, tc);
  50683. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50684. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50685. if (isIntersected) {
  50686. return qtc.length();
  50687. }
  50688. return -1;
  50689. };
  50690. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50691. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50692. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50693. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50694. this.direction.normalize();
  50695. return this;
  50696. };
  50697. // Statics
  50698. Ray.Zero = function () {
  50699. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50700. };
  50701. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50702. var result = Ray.Zero();
  50703. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50704. };
  50705. /**
  50706. * 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
  50707. * transformed to the given world matrix.
  50708. * @param origin The origin point
  50709. * @param end The end point
  50710. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50711. */
  50712. Ray.CreateNewFromTo = function (origin, end, world) {
  50713. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50714. var direction = end.subtract(origin);
  50715. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50716. direction.normalize();
  50717. return Ray.Transform(new Ray(origin, direction, length), world);
  50718. };
  50719. Ray.Transform = function (ray, matrix) {
  50720. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50721. Ray.TransformToRef(ray, matrix, result);
  50722. return result;
  50723. };
  50724. Ray.TransformToRef = function (ray, matrix, result) {
  50725. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50726. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50727. result.length = ray.length;
  50728. var dir = result.direction;
  50729. var len = dir.length();
  50730. if (!(len === 0 || len === 1)) {
  50731. var num = 1.0 / len;
  50732. dir.x *= num;
  50733. dir.y *= num;
  50734. dir.z *= num;
  50735. result.length *= len;
  50736. }
  50737. };
  50738. Ray.smallnum = 0.00000001;
  50739. Ray.rayl = 10e8;
  50740. return Ray;
  50741. }());
  50742. BABYLON.Ray = Ray;
  50743. })(BABYLON || (BABYLON = {}));
  50744. //# sourceMappingURL=babylon.ray.js.map
  50745. "use strict";
  50746. var BABYLON;
  50747. (function (BABYLON) {
  50748. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50749. if (boxMin.x > sphereCenter.x + sphereRadius)
  50750. return false;
  50751. if (sphereCenter.x - sphereRadius > boxMax.x)
  50752. return false;
  50753. if (boxMin.y > sphereCenter.y + sphereRadius)
  50754. return false;
  50755. if (sphereCenter.y - sphereRadius > boxMax.y)
  50756. return false;
  50757. if (boxMin.z > sphereCenter.z + sphereRadius)
  50758. return false;
  50759. if (sphereCenter.z - sphereRadius > boxMax.z)
  50760. return false;
  50761. return true;
  50762. };
  50763. var getLowestRoot = (function () {
  50764. var result = { root: 0, found: false };
  50765. return function (a, b, c, maxR) {
  50766. result.root = 0;
  50767. result.found = false;
  50768. var determinant = b * b - 4.0 * a * c;
  50769. if (determinant < 0)
  50770. return result;
  50771. var sqrtD = Math.sqrt(determinant);
  50772. var r1 = (-b - sqrtD) / (2.0 * a);
  50773. var r2 = (-b + sqrtD) / (2.0 * a);
  50774. if (r1 > r2) {
  50775. var temp = r2;
  50776. r2 = r1;
  50777. r1 = temp;
  50778. }
  50779. if (r1 > 0 && r1 < maxR) {
  50780. result.root = r1;
  50781. result.found = true;
  50782. return result;
  50783. }
  50784. if (r2 > 0 && r2 < maxR) {
  50785. result.root = r2;
  50786. result.found = true;
  50787. return result;
  50788. }
  50789. return result;
  50790. };
  50791. })();
  50792. var Collider = /** @class */ (function () {
  50793. function Collider() {
  50794. this._collisionPoint = BABYLON.Vector3.Zero();
  50795. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50796. this._tempVector = BABYLON.Vector3.Zero();
  50797. this._tempVector2 = BABYLON.Vector3.Zero();
  50798. this._tempVector3 = BABYLON.Vector3.Zero();
  50799. this._tempVector4 = BABYLON.Vector3.Zero();
  50800. this._edge = BABYLON.Vector3.Zero();
  50801. this._baseToVertex = BABYLON.Vector3.Zero();
  50802. this._destinationPoint = BABYLON.Vector3.Zero();
  50803. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50804. this._displacementVector = BABYLON.Vector3.Zero();
  50805. this._radius = BABYLON.Vector3.One();
  50806. this._retry = 0;
  50807. this._basePointWorld = BABYLON.Vector3.Zero();
  50808. this._velocityWorld = BABYLON.Vector3.Zero();
  50809. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50810. this._collisionMask = -1;
  50811. }
  50812. Object.defineProperty(Collider.prototype, "collisionMask", {
  50813. get: function () {
  50814. return this._collisionMask;
  50815. },
  50816. set: function (mask) {
  50817. this._collisionMask = !isNaN(mask) ? mask : -1;
  50818. },
  50819. enumerable: true,
  50820. configurable: true
  50821. });
  50822. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50823. /**
  50824. * Gets the plane normal used to compute the sliding response (in local space)
  50825. */
  50826. get: function () {
  50827. return this._slidePlaneNormal;
  50828. },
  50829. enumerable: true,
  50830. configurable: true
  50831. });
  50832. // Methods
  50833. Collider.prototype._initialize = function (source, dir, e) {
  50834. this._velocity = dir;
  50835. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50836. this._basePoint = source;
  50837. source.multiplyToRef(this._radius, this._basePointWorld);
  50838. dir.multiplyToRef(this._radius, this._velocityWorld);
  50839. this._velocityWorldLength = this._velocityWorld.length();
  50840. this._epsilon = e;
  50841. this.collisionFound = false;
  50842. };
  50843. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50844. pa.subtractToRef(point, this._tempVector);
  50845. pb.subtractToRef(point, this._tempVector2);
  50846. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50847. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50848. if (d < 0)
  50849. return false;
  50850. pc.subtractToRef(point, this._tempVector3);
  50851. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50852. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50853. if (d < 0)
  50854. return false;
  50855. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50856. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50857. return d >= 0;
  50858. };
  50859. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50860. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50861. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50862. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50863. return false;
  50864. }
  50865. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50866. return false;
  50867. return true;
  50868. };
  50869. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50870. var t0;
  50871. var embeddedInPlane = false;
  50872. //defensive programming, actually not needed.
  50873. if (!trianglePlaneArray) {
  50874. trianglePlaneArray = [];
  50875. }
  50876. if (!trianglePlaneArray[faceIndex]) {
  50877. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50878. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50879. }
  50880. var trianglePlane = trianglePlaneArray[faceIndex];
  50881. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50882. return;
  50883. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50884. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50885. if (normalDotVelocity == 0) {
  50886. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50887. return;
  50888. embeddedInPlane = true;
  50889. t0 = 0;
  50890. }
  50891. else {
  50892. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50893. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50894. if (t0 > t1) {
  50895. var temp = t1;
  50896. t1 = t0;
  50897. t0 = temp;
  50898. }
  50899. if (t0 > 1.0 || t1 < 0.0)
  50900. return;
  50901. if (t0 < 0)
  50902. t0 = 0;
  50903. if (t0 > 1.0)
  50904. t0 = 1.0;
  50905. }
  50906. this._collisionPoint.copyFromFloats(0, 0, 0);
  50907. var found = false;
  50908. var t = 1.0;
  50909. if (!embeddedInPlane) {
  50910. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50911. this._velocity.scaleToRef(t0, this._tempVector);
  50912. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50913. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50914. found = true;
  50915. t = t0;
  50916. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50917. }
  50918. }
  50919. if (!found) {
  50920. var velocitySquaredLength = this._velocity.lengthSquared();
  50921. var a = velocitySquaredLength;
  50922. this._basePoint.subtractToRef(p1, this._tempVector);
  50923. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50924. var c = this._tempVector.lengthSquared() - 1.0;
  50925. var lowestRoot = getLowestRoot(a, b, c, t);
  50926. if (lowestRoot.found) {
  50927. t = lowestRoot.root;
  50928. found = true;
  50929. this._collisionPoint.copyFrom(p1);
  50930. }
  50931. this._basePoint.subtractToRef(p2, this._tempVector);
  50932. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50933. c = this._tempVector.lengthSquared() - 1.0;
  50934. lowestRoot = getLowestRoot(a, b, c, t);
  50935. if (lowestRoot.found) {
  50936. t = lowestRoot.root;
  50937. found = true;
  50938. this._collisionPoint.copyFrom(p2);
  50939. }
  50940. this._basePoint.subtractToRef(p3, this._tempVector);
  50941. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50942. c = this._tempVector.lengthSquared() - 1.0;
  50943. lowestRoot = getLowestRoot(a, b, c, t);
  50944. if (lowestRoot.found) {
  50945. t = lowestRoot.root;
  50946. found = true;
  50947. this._collisionPoint.copyFrom(p3);
  50948. }
  50949. p2.subtractToRef(p1, this._edge);
  50950. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50951. var edgeSquaredLength = this._edge.lengthSquared();
  50952. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50953. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50954. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50955. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50956. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50957. lowestRoot = getLowestRoot(a, b, c, t);
  50958. if (lowestRoot.found) {
  50959. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50960. if (f >= 0.0 && f <= 1.0) {
  50961. t = lowestRoot.root;
  50962. found = true;
  50963. this._edge.scaleInPlace(f);
  50964. p1.addToRef(this._edge, this._collisionPoint);
  50965. }
  50966. }
  50967. p3.subtractToRef(p2, this._edge);
  50968. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50969. edgeSquaredLength = this._edge.lengthSquared();
  50970. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50971. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50972. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50973. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50974. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50975. lowestRoot = getLowestRoot(a, b, c, t);
  50976. if (lowestRoot.found) {
  50977. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50978. if (f >= 0.0 && f <= 1.0) {
  50979. t = lowestRoot.root;
  50980. found = true;
  50981. this._edge.scaleInPlace(f);
  50982. p2.addToRef(this._edge, this._collisionPoint);
  50983. }
  50984. }
  50985. p1.subtractToRef(p3, this._edge);
  50986. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50987. edgeSquaredLength = this._edge.lengthSquared();
  50988. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50989. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50990. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50991. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50992. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50993. lowestRoot = getLowestRoot(a, b, c, t);
  50994. if (lowestRoot.found) {
  50995. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50996. if (f >= 0.0 && f <= 1.0) {
  50997. t = lowestRoot.root;
  50998. found = true;
  50999. this._edge.scaleInPlace(f);
  51000. p3.addToRef(this._edge, this._collisionPoint);
  51001. }
  51002. }
  51003. }
  51004. if (found) {
  51005. var distToCollision = t * this._velocity.length();
  51006. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  51007. if (!this.intersectionPoint) {
  51008. this.intersectionPoint = this._collisionPoint.clone();
  51009. }
  51010. else {
  51011. this.intersectionPoint.copyFrom(this._collisionPoint);
  51012. }
  51013. this._nearestDistance = distToCollision;
  51014. this.collisionFound = true;
  51015. }
  51016. }
  51017. };
  51018. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51019. for (var i = indexStart; i < indexEnd; i += 3) {
  51020. var p1 = pts[indices[i] - decal];
  51021. var p2 = pts[indices[i + 1] - decal];
  51022. var p3 = pts[indices[i + 2] - decal];
  51023. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51024. }
  51025. };
  51026. Collider.prototype._getResponse = function (pos, vel) {
  51027. pos.addToRef(vel, this._destinationPoint);
  51028. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51029. this._basePoint.addToRef(vel, pos);
  51030. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51031. this._slidePlaneNormal.normalize();
  51032. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51033. pos.addInPlace(this._displacementVector);
  51034. this.intersectionPoint.addInPlace(this._displacementVector);
  51035. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51036. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51037. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51038. };
  51039. return Collider;
  51040. }());
  51041. BABYLON.Collider = Collider;
  51042. })(BABYLON || (BABYLON = {}));
  51043. //# sourceMappingURL=babylon.collider.js.map
  51044. "use strict";
  51045. var BABYLON;
  51046. (function (BABYLON) {
  51047. //WebWorker code will be inserted to this variable.
  51048. BABYLON.CollisionWorker = "";
  51049. var WorkerTaskType;
  51050. (function (WorkerTaskType) {
  51051. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51052. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51053. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51054. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51055. var WorkerReplyType;
  51056. (function (WorkerReplyType) {
  51057. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51058. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51059. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51060. var CollisionCoordinatorWorker = /** @class */ (function () {
  51061. function CollisionCoordinatorWorker() {
  51062. var _this = this;
  51063. this._scaledPosition = BABYLON.Vector3.Zero();
  51064. this._scaledVelocity = BABYLON.Vector3.Zero();
  51065. this.onMeshUpdated = function (transformNode) {
  51066. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51067. };
  51068. this.onGeometryUpdated = function (geometry) {
  51069. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51070. };
  51071. this._afterRender = function () {
  51072. if (!_this._init)
  51073. return;
  51074. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51075. return;
  51076. }
  51077. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51078. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51079. if (_this._runningUpdated > 4) {
  51080. return;
  51081. }
  51082. ++_this._runningUpdated;
  51083. var payload = {
  51084. updatedMeshes: _this._addUpdateMeshesList,
  51085. updatedGeometries: _this._addUpdateGeometriesList,
  51086. removedGeometries: _this._toRemoveGeometryArray,
  51087. removedMeshes: _this._toRemoveMeshesArray
  51088. };
  51089. var message = {
  51090. payload: payload,
  51091. taskType: WorkerTaskType.UPDATE
  51092. };
  51093. var serializable = [];
  51094. for (var id in payload.updatedGeometries) {
  51095. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51096. //prepare transferables
  51097. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51098. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51099. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51100. }
  51101. }
  51102. _this._worker.postMessage(message, serializable);
  51103. _this._addUpdateMeshesList = {};
  51104. _this._addUpdateGeometriesList = {};
  51105. _this._toRemoveGeometryArray = [];
  51106. _this._toRemoveMeshesArray = [];
  51107. };
  51108. this._onMessageFromWorker = function (e) {
  51109. var returnData = e.data;
  51110. if (returnData.error != WorkerReplyType.SUCCESS) {
  51111. //TODO what errors can be returned from the worker?
  51112. BABYLON.Tools.Warn("error returned from worker!");
  51113. return;
  51114. }
  51115. switch (returnData.taskType) {
  51116. case WorkerTaskType.INIT:
  51117. _this._init = true;
  51118. //Update the worked with ALL of the scene's current state
  51119. _this._scene.meshes.forEach(function (mesh) {
  51120. _this.onMeshAdded(mesh);
  51121. });
  51122. _this._scene.getGeometries().forEach(function (geometry) {
  51123. _this.onGeometryAdded(geometry);
  51124. });
  51125. break;
  51126. case WorkerTaskType.UPDATE:
  51127. _this._runningUpdated--;
  51128. break;
  51129. case WorkerTaskType.COLLIDE:
  51130. var returnPayload = returnData.payload;
  51131. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51132. return;
  51133. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51134. if (callback) {
  51135. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51136. if (mesh) {
  51137. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51138. }
  51139. }
  51140. //cleanup
  51141. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51142. break;
  51143. }
  51144. };
  51145. this._collisionsCallbackArray = [];
  51146. this._init = false;
  51147. this._runningUpdated = 0;
  51148. this._addUpdateMeshesList = {};
  51149. this._addUpdateGeometriesList = {};
  51150. this._toRemoveGeometryArray = [];
  51151. this._toRemoveMeshesArray = [];
  51152. }
  51153. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51154. if (!this._init)
  51155. return;
  51156. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51157. return;
  51158. position.divideToRef(collider._radius, this._scaledPosition);
  51159. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51160. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51161. var payload = {
  51162. collider: {
  51163. position: this._scaledPosition.asArray(),
  51164. velocity: this._scaledVelocity.asArray(),
  51165. radius: collider._radius.asArray()
  51166. },
  51167. collisionId: collisionIndex,
  51168. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51169. maximumRetry: maximumRetry
  51170. };
  51171. var message = {
  51172. payload: payload,
  51173. taskType: WorkerTaskType.COLLIDE
  51174. };
  51175. this._worker.postMessage(message);
  51176. };
  51177. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51178. this._scene = scene;
  51179. this._scene.registerAfterRender(this._afterRender);
  51180. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51181. this._worker = new Worker(workerUrl);
  51182. this._worker.onmessage = this._onMessageFromWorker;
  51183. var message = {
  51184. payload: {},
  51185. taskType: WorkerTaskType.INIT
  51186. };
  51187. this._worker.postMessage(message);
  51188. };
  51189. CollisionCoordinatorWorker.prototype.destroy = function () {
  51190. this._scene.unregisterAfterRender(this._afterRender);
  51191. this._worker.terminate();
  51192. };
  51193. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51194. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51195. this.onMeshUpdated(mesh);
  51196. };
  51197. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51198. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51199. };
  51200. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51201. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51202. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51203. this.onGeometryUpdated(geometry);
  51204. };
  51205. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51206. this._toRemoveGeometryArray.push(geometry.id);
  51207. };
  51208. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51209. var submeshes = [];
  51210. if (mesh.subMeshes) {
  51211. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51212. var boundingInfo = sm.getBoundingInfo();
  51213. return {
  51214. position: idx,
  51215. verticesStart: sm.verticesStart,
  51216. verticesCount: sm.verticesCount,
  51217. indexStart: sm.indexStart,
  51218. indexCount: sm.indexCount,
  51219. hasMaterial: !!sm.getMaterial(),
  51220. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51221. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51222. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51223. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51224. };
  51225. });
  51226. }
  51227. var geometryId = null;
  51228. if (mesh instanceof BABYLON.Mesh) {
  51229. var geometry = mesh.geometry;
  51230. geometryId = geometry ? geometry.id : null;
  51231. }
  51232. else if (mesh instanceof BABYLON.InstancedMesh) {
  51233. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51234. geometryId = geometry ? geometry.id : null;
  51235. }
  51236. var boundingInfo = mesh.getBoundingInfo();
  51237. return {
  51238. uniqueId: mesh.uniqueId,
  51239. id: mesh.id,
  51240. name: mesh.name,
  51241. geometryId: geometryId,
  51242. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51243. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51244. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51245. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51246. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51247. subMeshes: submeshes,
  51248. checkCollisions: mesh.checkCollisions
  51249. };
  51250. };
  51251. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51252. return {
  51253. id: geometry.id,
  51254. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51255. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51256. indices: new Uint32Array(geometry.getIndices() || []),
  51257. };
  51258. };
  51259. return CollisionCoordinatorWorker;
  51260. }());
  51261. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51262. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51263. function CollisionCoordinatorLegacy() {
  51264. this._scaledPosition = BABYLON.Vector3.Zero();
  51265. this._scaledVelocity = BABYLON.Vector3.Zero();
  51266. this._finalPosition = BABYLON.Vector3.Zero();
  51267. }
  51268. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51269. position.divideToRef(collider._radius, this._scaledPosition);
  51270. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51271. collider.collidedMesh = null;
  51272. collider._retry = 0;
  51273. collider._initialVelocity = this._scaledVelocity;
  51274. collider._initialPosition = this._scaledPosition;
  51275. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51276. this._finalPosition.multiplyInPlace(collider._radius);
  51277. //run the callback
  51278. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51279. };
  51280. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51281. this._scene = scene;
  51282. };
  51283. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51284. //Legacy need no destruction method.
  51285. };
  51286. //No update in legacy mode
  51287. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51288. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51289. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51290. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51291. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51292. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51293. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51294. if (excludedMesh === void 0) { excludedMesh = null; }
  51295. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51296. if (collider._retry >= maximumRetry) {
  51297. finalPosition.copyFrom(position);
  51298. return;
  51299. }
  51300. // Check if this is a mesh else camera or -1
  51301. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51302. collider._initialize(position, velocity, closeDistance);
  51303. // Check all meshes
  51304. for (var index = 0; index < this._scene.meshes.length; index++) {
  51305. var mesh = this._scene.meshes[index];
  51306. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51307. mesh._checkCollision(collider);
  51308. }
  51309. }
  51310. if (!collider.collisionFound) {
  51311. position.addToRef(velocity, finalPosition);
  51312. return;
  51313. }
  51314. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51315. collider._getResponse(position, velocity);
  51316. }
  51317. if (velocity.length() <= closeDistance) {
  51318. finalPosition.copyFrom(position);
  51319. return;
  51320. }
  51321. collider._retry++;
  51322. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51323. };
  51324. return CollisionCoordinatorLegacy;
  51325. }());
  51326. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51327. })(BABYLON || (BABYLON = {}));
  51328. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51329. "use strict";
  51330. var BABYLON;
  51331. (function (BABYLON) {
  51332. /**
  51333. * A particle represents one of the element emitted by a particle system.
  51334. * This is mainly define by its coordinates, direction, velocity and age.
  51335. */
  51336. var Particle = /** @class */ (function () {
  51337. /**
  51338. * Creates a new instance of @see Particle
  51339. * @param particleSystem the particle system the particle belongs to
  51340. */
  51341. function Particle(
  51342. /**
  51343. * particleSystem the particle system the particle belongs to.
  51344. */
  51345. particleSystem) {
  51346. this.particleSystem = particleSystem;
  51347. /**
  51348. * The world position of the particle in the scene.
  51349. */
  51350. this.position = BABYLON.Vector3.Zero();
  51351. /**
  51352. * The world direction of the particle in the scene.
  51353. */
  51354. this.direction = BABYLON.Vector3.Zero();
  51355. /**
  51356. * The color of the particle.
  51357. */
  51358. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51359. /**
  51360. * The color change of the particle per step.
  51361. */
  51362. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51363. /**
  51364. * Defines how long will the life of the particle be.
  51365. */
  51366. this.lifeTime = 1.0;
  51367. /**
  51368. * The current age of the particle.
  51369. */
  51370. this.age = 0;
  51371. /**
  51372. * The current size of the particle.
  51373. */
  51374. this.size = 0;
  51375. /**
  51376. * The current angle of the particle.
  51377. */
  51378. this.angle = 0;
  51379. /**
  51380. * Defines how fast is the angle changing.
  51381. */
  51382. this.angularSpeed = 0;
  51383. /**
  51384. * Defines the cell index used by the particle to be rendered from a sprite.
  51385. */
  51386. this.cellIndex = 0;
  51387. this._currentFrameCounter = 0;
  51388. if (!this.particleSystem.isAnimationSheetEnabled) {
  51389. return;
  51390. }
  51391. this.updateCellInfoFromSystem();
  51392. }
  51393. Particle.prototype.updateCellInfoFromSystem = function () {
  51394. this.cellIndex = this.particleSystem.startSpriteCellID;
  51395. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51396. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51397. }
  51398. else {
  51399. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51400. }
  51401. };
  51402. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51403. // (ageOffset / scaledUpdateSpeed) / available cells
  51404. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51405. this._currentFrameCounter += scaledUpdateSpeed;
  51406. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51407. this._currentFrameCounter = 0;
  51408. this.cellIndex++;
  51409. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51410. this.cellIndex = this.particleSystem.endSpriteCellID;
  51411. }
  51412. }
  51413. };
  51414. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51415. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51416. this.cellIndex++;
  51417. this._currentFrameCounter = 0;
  51418. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51419. if (this.particleSystem.spriteCellLoop) {
  51420. this.cellIndex = this.particleSystem.startSpriteCellID;
  51421. }
  51422. else {
  51423. this.cellIndex = this.particleSystem.endSpriteCellID;
  51424. }
  51425. }
  51426. }
  51427. else {
  51428. this._currentFrameCounter++;
  51429. }
  51430. };
  51431. /**
  51432. * Copy the properties of particle to another one.
  51433. * @param other the particle to copy the information to.
  51434. */
  51435. Particle.prototype.copyTo = function (other) {
  51436. other.position.copyFrom(this.position);
  51437. other.direction.copyFrom(this.direction);
  51438. other.color.copyFrom(this.color);
  51439. other.colorStep.copyFrom(this.colorStep);
  51440. other.lifeTime = this.lifeTime;
  51441. other.age = this.age;
  51442. other.size = this.size;
  51443. other.angle = this.angle;
  51444. other.angularSpeed = this.angularSpeed;
  51445. other.particleSystem = this.particleSystem;
  51446. other.cellIndex = this.cellIndex;
  51447. };
  51448. return Particle;
  51449. }());
  51450. BABYLON.Particle = Particle;
  51451. })(BABYLON || (BABYLON = {}));
  51452. //# sourceMappingURL=babylon.particle.js.map
  51453. "use strict";
  51454. var BABYLON;
  51455. (function (BABYLON) {
  51456. /**
  51457. * This represents a particle system in Babylon.
  51458. * 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.
  51459. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51460. * @example https://doc.babylonjs.com/babylon101/particles
  51461. */
  51462. var ParticleSystem = /** @class */ (function () {
  51463. /**
  51464. * Instantiates a particle system.
  51465. * 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.
  51466. * @param name The name of the particle system
  51467. * @param capacity The max number of particles alive at the same time
  51468. * @param scene The scene the particle system belongs to
  51469. * @param customEffect a custom effect used to change the way particles are rendered by default
  51470. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51471. * @param epsilon Offset used to render the particles
  51472. */
  51473. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51474. if (customEffect === void 0) { customEffect = null; }
  51475. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51476. if (epsilon === void 0) { epsilon = 0.01; }
  51477. var _this = this;
  51478. /**
  51479. * List of animations used by the particle system.
  51480. */
  51481. this.animations = [];
  51482. /**
  51483. * The rendering group used by the Particle system to chose when to render.
  51484. */
  51485. this.renderingGroupId = 0;
  51486. /**
  51487. * The emitter represents the Mesh or position we are attaching the particle system to.
  51488. */
  51489. this.emitter = null;
  51490. /**
  51491. * The maximum number of particles to emit per frame
  51492. */
  51493. this.emitRate = 10;
  51494. /**
  51495. * If you want to launch only a few particles at once, that can be done, as well.
  51496. */
  51497. this.manualEmitCount = -1;
  51498. /**
  51499. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51500. */
  51501. this.updateSpeed = 0.01;
  51502. /**
  51503. * The amount of time the particle system is running (depends of the overall update speed).
  51504. */
  51505. this.targetStopDuration = 0;
  51506. /**
  51507. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51508. */
  51509. this.disposeOnStop = false;
  51510. /**
  51511. * Minimum power of emitting particles.
  51512. */
  51513. this.minEmitPower = 1;
  51514. /**
  51515. * Maximum power of emitting particles.
  51516. */
  51517. this.maxEmitPower = 1;
  51518. /**
  51519. * Minimum life time of emitting particles.
  51520. */
  51521. this.minLifeTime = 1;
  51522. /**
  51523. * Maximum life time of emitting particles.
  51524. */
  51525. this.maxLifeTime = 1;
  51526. /**
  51527. * Minimum Size of emitting particles.
  51528. */
  51529. this.minSize = 1;
  51530. /**
  51531. * Maximum Size of emitting particles.
  51532. */
  51533. this.maxSize = 1;
  51534. /**
  51535. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51536. */
  51537. this.minAngularSpeed = 0;
  51538. /**
  51539. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51540. */
  51541. this.maxAngularSpeed = 0;
  51542. /**
  51543. * The layer mask we are rendering the particles through.
  51544. */
  51545. this.layerMask = 0x0FFFFFFF;
  51546. /**
  51547. * This can help using your own shader to render the particle system.
  51548. * The according effect will be created
  51549. */
  51550. this.customShader = null;
  51551. /**
  51552. * By default particle system starts as soon as they are created. This prevents the
  51553. * automatic start to happen and let you decide when to start emitting particles.
  51554. */
  51555. this.preventAutoStart = false;
  51556. /**
  51557. * Callback triggered when the particle animation is ending.
  51558. */
  51559. this.onAnimationEnd = null;
  51560. /**
  51561. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51562. */
  51563. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51564. /**
  51565. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51566. * to override the particles.
  51567. */
  51568. this.forceDepthWrite = false;
  51569. /**
  51570. * You can use gravity if you want to give an orientation to your particles.
  51571. */
  51572. this.gravity = BABYLON.Vector3.Zero();
  51573. /**
  51574. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51575. */
  51576. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51577. /**
  51578. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51579. */
  51580. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51581. /**
  51582. * Color the particle will have at the end of its lifetime.
  51583. */
  51584. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51585. /**
  51586. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51587. */
  51588. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51589. /**
  51590. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51591. */
  51592. this.spriteCellLoop = true;
  51593. /**
  51594. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51595. */
  51596. this.spriteCellChangeSpeed = 0;
  51597. /**
  51598. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51599. */
  51600. this.startSpriteCellID = 0;
  51601. /**
  51602. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51603. */
  51604. this.endSpriteCellID = 0;
  51605. /**
  51606. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51607. */
  51608. this.spriteCellWidth = 0;
  51609. /**
  51610. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51611. */
  51612. this.spriteCellHeight = 0;
  51613. /**
  51614. * An event triggered when the system is disposed.
  51615. */
  51616. this.onDisposeObservable = new BABYLON.Observable();
  51617. this._particles = new Array();
  51618. this._stockParticles = new Array();
  51619. this._newPartsExcess = 0;
  51620. this._vertexBuffers = {};
  51621. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51622. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51623. this._scaledDirection = BABYLON.Vector3.Zero();
  51624. this._scaledGravity = BABYLON.Vector3.Zero();
  51625. this._currentRenderId = -1;
  51626. this._started = false;
  51627. this._stopped = false;
  51628. this._actualFrame = 0;
  51629. this._vertexBufferSize = 11;
  51630. // start of sub system methods
  51631. /**
  51632. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51633. * Its lifetime will start back at 0.
  51634. */
  51635. this.recycleParticle = function (particle) {
  51636. var lastParticle = _this._particles.pop();
  51637. if (lastParticle !== particle) {
  51638. lastParticle.copyTo(particle);
  51639. }
  51640. _this._stockParticles.push(lastParticle);
  51641. };
  51642. this._createParticle = function () {
  51643. var particle;
  51644. if (_this._stockParticles.length !== 0) {
  51645. particle = _this._stockParticles.pop();
  51646. particle.age = 0;
  51647. particle.cellIndex = _this.startSpriteCellID;
  51648. }
  51649. else {
  51650. particle = new BABYLON.Particle(_this);
  51651. }
  51652. return particle;
  51653. };
  51654. this._emitFromParticle = function (particle) {
  51655. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51656. return;
  51657. }
  51658. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51659. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51660. subSystem._rootParticleSystem = _this;
  51661. _this.activeSubSystems.push(subSystem);
  51662. subSystem.start();
  51663. };
  51664. this._appendParticleVertexes = null;
  51665. this.id = name;
  51666. this.name = name;
  51667. this._capacity = capacity;
  51668. this._epsilon = epsilon;
  51669. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51670. if (isAnimationSheetEnabled) {
  51671. this._vertexBufferSize = 12;
  51672. }
  51673. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51674. this._customEffect = customEffect;
  51675. scene.particleSystems.push(this);
  51676. this._createIndexBuffer();
  51677. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51678. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51679. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51680. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51681. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51682. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51683. if (this._isAnimationSheetEnabled) {
  51684. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51685. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51686. }
  51687. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51688. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51689. this._vertexBuffers["options"] = options;
  51690. // Default emitter type
  51691. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51692. this.updateFunction = function (particles) {
  51693. for (var index = 0; index < particles.length; index++) {
  51694. var particle = particles[index];
  51695. particle.age += _this._scaledUpdateSpeed;
  51696. if (particle.age >= particle.lifeTime) {
  51697. _this._emitFromParticle(particle);
  51698. _this.recycleParticle(particle);
  51699. index--;
  51700. continue;
  51701. }
  51702. else {
  51703. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51704. particle.color.addInPlace(_this._scaledColorStep);
  51705. if (particle.color.a < 0)
  51706. particle.color.a = 0;
  51707. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51708. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51709. particle.position.addInPlace(_this._scaledDirection);
  51710. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51711. particle.direction.addInPlace(_this._scaledGravity);
  51712. if (_this._isAnimationSheetEnabled) {
  51713. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51714. }
  51715. }
  51716. }
  51717. };
  51718. }
  51719. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51720. /**
  51721. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51722. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51723. */
  51724. get: function () {
  51725. if (this.particleEmitterType.direction1) {
  51726. return this.particleEmitterType.direction1;
  51727. }
  51728. return BABYLON.Vector3.Zero();
  51729. },
  51730. set: function (value) {
  51731. if (this.particleEmitterType.direction1) {
  51732. this.particleEmitterType.direction1 = value;
  51733. }
  51734. },
  51735. enumerable: true,
  51736. configurable: true
  51737. });
  51738. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51739. /**
  51740. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51741. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51742. */
  51743. get: function () {
  51744. if (this.particleEmitterType.direction2) {
  51745. return this.particleEmitterType.direction2;
  51746. }
  51747. return BABYLON.Vector3.Zero();
  51748. },
  51749. set: function (value) {
  51750. if (this.particleEmitterType.direction2) {
  51751. this.particleEmitterType.direction2 = value;
  51752. }
  51753. },
  51754. enumerable: true,
  51755. configurable: true
  51756. });
  51757. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51758. /**
  51759. * 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.
  51760. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51761. */
  51762. get: function () {
  51763. if (this.particleEmitterType.minEmitBox) {
  51764. return this.particleEmitterType.minEmitBox;
  51765. }
  51766. return BABYLON.Vector3.Zero();
  51767. },
  51768. set: function (value) {
  51769. if (this.particleEmitterType.minEmitBox) {
  51770. this.particleEmitterType.minEmitBox = value;
  51771. }
  51772. },
  51773. enumerable: true,
  51774. configurable: true
  51775. });
  51776. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51777. /**
  51778. * 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.
  51779. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51780. */
  51781. get: function () {
  51782. if (this.particleEmitterType.maxEmitBox) {
  51783. return this.particleEmitterType.maxEmitBox;
  51784. }
  51785. return BABYLON.Vector3.Zero();
  51786. },
  51787. set: function (value) {
  51788. if (this.particleEmitterType.maxEmitBox) {
  51789. this.particleEmitterType.maxEmitBox = value;
  51790. }
  51791. },
  51792. enumerable: true,
  51793. configurable: true
  51794. });
  51795. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51796. /**
  51797. * Sets a callback that will be triggered when the system is disposed.
  51798. */
  51799. set: function (callback) {
  51800. if (this._onDisposeObserver) {
  51801. this.onDisposeObservable.remove(this._onDisposeObserver);
  51802. }
  51803. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51804. },
  51805. enumerable: true,
  51806. configurable: true
  51807. });
  51808. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51809. /**
  51810. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51811. */
  51812. get: function () {
  51813. return this._isAnimationSheetEnabled;
  51814. },
  51815. enumerable: true,
  51816. configurable: true
  51817. });
  51818. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51819. //end of Sub-emitter
  51820. /**
  51821. * Gets the current list of active particles
  51822. */
  51823. get: function () {
  51824. return this._particles;
  51825. },
  51826. enumerable: true,
  51827. configurable: true
  51828. });
  51829. /**
  51830. * Returns the string "ParticleSystem"
  51831. * @returns a string containing the class name
  51832. */
  51833. ParticleSystem.prototype.getClassName = function () {
  51834. return "ParticleSystem";
  51835. };
  51836. ParticleSystem.prototype._createIndexBuffer = function () {
  51837. var indices = [];
  51838. var index = 0;
  51839. for (var count = 0; count < this._capacity; count++) {
  51840. indices.push(index);
  51841. indices.push(index + 1);
  51842. indices.push(index + 2);
  51843. indices.push(index);
  51844. indices.push(index + 2);
  51845. indices.push(index + 3);
  51846. index += 4;
  51847. }
  51848. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51849. };
  51850. /**
  51851. * Gets the maximum number of particles active at the same time.
  51852. * @returns The max number of active particles.
  51853. */
  51854. ParticleSystem.prototype.getCapacity = function () {
  51855. return this._capacity;
  51856. };
  51857. /**
  51858. * Gets Wether there are still active particles in the system.
  51859. * @returns True if it is alive, otherwise false.
  51860. */
  51861. ParticleSystem.prototype.isAlive = function () {
  51862. return this._alive;
  51863. };
  51864. /**
  51865. * Gets Wether the system has been started.
  51866. * @returns True if it has been started, otherwise false.
  51867. */
  51868. ParticleSystem.prototype.isStarted = function () {
  51869. return this._started;
  51870. };
  51871. /**
  51872. * Starts the particle system and begins to emit.
  51873. */
  51874. ParticleSystem.prototype.start = function () {
  51875. this._started = true;
  51876. this._stopped = false;
  51877. this._actualFrame = 0;
  51878. if (this.subEmitters && this.subEmitters.length != 0) {
  51879. this.activeSubSystems = new Array();
  51880. }
  51881. };
  51882. /**
  51883. * Stops the particle system.
  51884. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  51885. */
  51886. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51887. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51888. this._stopped = true;
  51889. if (stopSubEmitters) {
  51890. this._stopSubEmitters();
  51891. }
  51892. };
  51893. // animation sheet
  51894. /**
  51895. * Remove all active particles
  51896. */
  51897. ParticleSystem.prototype.reset = function () {
  51898. this._stockParticles = [];
  51899. this._particles = [];
  51900. };
  51901. /**
  51902. * @ignore (for internal use only)
  51903. */
  51904. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51905. var offset = index * this._vertexBufferSize;
  51906. this._vertexData[offset] = particle.position.x;
  51907. this._vertexData[offset + 1] = particle.position.y;
  51908. this._vertexData[offset + 2] = particle.position.z;
  51909. this._vertexData[offset + 3] = particle.color.r;
  51910. this._vertexData[offset + 4] = particle.color.g;
  51911. this._vertexData[offset + 5] = particle.color.b;
  51912. this._vertexData[offset + 6] = particle.color.a;
  51913. this._vertexData[offset + 7] = particle.angle;
  51914. this._vertexData[offset + 8] = particle.size;
  51915. this._vertexData[offset + 9] = offsetX;
  51916. this._vertexData[offset + 10] = offsetY;
  51917. };
  51918. /**
  51919. * @ignore (for internal use only)
  51920. */
  51921. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51922. if (offsetX === 0)
  51923. offsetX = this._epsilon;
  51924. else if (offsetX === 1)
  51925. offsetX = 1 - this._epsilon;
  51926. if (offsetY === 0)
  51927. offsetY = this._epsilon;
  51928. else if (offsetY === 1)
  51929. offsetY = 1 - this._epsilon;
  51930. var offset = index * this._vertexBufferSize;
  51931. this._vertexData[offset] = particle.position.x;
  51932. this._vertexData[offset + 1] = particle.position.y;
  51933. this._vertexData[offset + 2] = particle.position.z;
  51934. this._vertexData[offset + 3] = particle.color.r;
  51935. this._vertexData[offset + 4] = particle.color.g;
  51936. this._vertexData[offset + 5] = particle.color.b;
  51937. this._vertexData[offset + 6] = particle.color.a;
  51938. this._vertexData[offset + 7] = particle.angle;
  51939. this._vertexData[offset + 8] = particle.size;
  51940. this._vertexData[offset + 9] = offsetX;
  51941. this._vertexData[offset + 10] = offsetY;
  51942. this._vertexData[offset + 11] = particle.cellIndex;
  51943. };
  51944. ParticleSystem.prototype._stopSubEmitters = function () {
  51945. if (!this.activeSubSystems) {
  51946. return;
  51947. }
  51948. this.activeSubSystems.forEach(function (subSystem) {
  51949. subSystem.stop(true);
  51950. });
  51951. this.activeSubSystems = new Array();
  51952. };
  51953. ParticleSystem.prototype._removeFromRoot = function () {
  51954. if (!this._rootParticleSystem) {
  51955. return;
  51956. }
  51957. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51958. if (index !== -1) {
  51959. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51960. }
  51961. };
  51962. // end of sub system methods
  51963. ParticleSystem.prototype._update = function (newParticles) {
  51964. // Update current
  51965. this._alive = this._particles.length > 0;
  51966. this.updateFunction(this._particles);
  51967. // Add new ones
  51968. var worldMatrix;
  51969. if (this.emitter.position) {
  51970. var emitterMesh = this.emitter;
  51971. worldMatrix = emitterMesh.getWorldMatrix();
  51972. }
  51973. else {
  51974. var emitterPosition = this.emitter;
  51975. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51976. }
  51977. var particle;
  51978. for (var index = 0; index < newParticles; index++) {
  51979. if (this._particles.length === this._capacity) {
  51980. break;
  51981. }
  51982. particle = this._createParticle();
  51983. this._particles.push(particle);
  51984. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51985. if (this.startPositionFunction) {
  51986. this.startPositionFunction(worldMatrix, particle.position, particle);
  51987. }
  51988. else {
  51989. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51990. }
  51991. if (this.startDirectionFunction) {
  51992. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51993. }
  51994. else {
  51995. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51996. }
  51997. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51998. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51999. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  52000. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  52001. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  52002. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  52003. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  52004. }
  52005. };
  52006. ParticleSystem.prototype._getEffect = function () {
  52007. if (this._customEffect) {
  52008. return this._customEffect;
  52009. }
  52010. ;
  52011. var defines = [];
  52012. if (this._scene.clipPlane) {
  52013. defines.push("#define CLIPPLANE");
  52014. }
  52015. if (this._isAnimationSheetEnabled) {
  52016. defines.push("#define ANIMATESHEET");
  52017. }
  52018. // Effect
  52019. var join = defines.join("\n");
  52020. if (this._cachedDefines !== join) {
  52021. this._cachedDefines = join;
  52022. var attributesNamesOrOptions;
  52023. var effectCreationOption;
  52024. if (this._isAnimationSheetEnabled) {
  52025. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52026. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52027. }
  52028. else {
  52029. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52030. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52031. }
  52032. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52033. }
  52034. return this._effect;
  52035. };
  52036. /**
  52037. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52038. */
  52039. ParticleSystem.prototype.animate = function () {
  52040. if (!this._started)
  52041. return;
  52042. var effect = this._getEffect();
  52043. // Check
  52044. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52045. return;
  52046. if (this._currentRenderId === this._scene.getRenderId()) {
  52047. return;
  52048. }
  52049. this._currentRenderId = this._scene.getRenderId();
  52050. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52051. // determine the number of particles we need to create
  52052. var newParticles;
  52053. if (this.manualEmitCount > -1) {
  52054. newParticles = this.manualEmitCount;
  52055. this._newPartsExcess = 0;
  52056. this.manualEmitCount = 0;
  52057. }
  52058. else {
  52059. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52060. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52061. }
  52062. if (this._newPartsExcess > 1.0) {
  52063. newParticles += this._newPartsExcess >> 0;
  52064. this._newPartsExcess -= this._newPartsExcess >> 0;
  52065. }
  52066. this._alive = false;
  52067. if (!this._stopped) {
  52068. this._actualFrame += this._scaledUpdateSpeed;
  52069. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52070. this.stop();
  52071. }
  52072. else {
  52073. newParticles = 0;
  52074. }
  52075. this._update(newParticles);
  52076. // Stopped?
  52077. if (this._stopped) {
  52078. if (!this._alive) {
  52079. this._started = false;
  52080. if (this.onAnimationEnd) {
  52081. this.onAnimationEnd();
  52082. }
  52083. if (this.disposeOnStop) {
  52084. this._scene._toBeDisposed.push(this);
  52085. }
  52086. }
  52087. }
  52088. // Animation sheet
  52089. if (this._isAnimationSheetEnabled) {
  52090. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52091. }
  52092. else {
  52093. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52094. }
  52095. // Update VBO
  52096. var offset = 0;
  52097. for (var index = 0; index < this._particles.length; index++) {
  52098. var particle = this._particles[index];
  52099. this._appendParticleVertexes(offset, particle);
  52100. offset += 4;
  52101. }
  52102. if (this._vertexBuffer) {
  52103. this._vertexBuffer.update(this._vertexData);
  52104. }
  52105. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52106. this.stop();
  52107. }
  52108. };
  52109. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52110. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52111. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52112. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52113. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52114. };
  52115. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52116. this._appendParticleVertex(offset++, particle, 0, 0);
  52117. this._appendParticleVertex(offset++, particle, 1, 0);
  52118. this._appendParticleVertex(offset++, particle, 1, 1);
  52119. this._appendParticleVertex(offset++, particle, 0, 1);
  52120. };
  52121. /**
  52122. * Rebuilds the particle system.
  52123. */
  52124. ParticleSystem.prototype.rebuild = function () {
  52125. this._createIndexBuffer();
  52126. if (this._vertexBuffer) {
  52127. this._vertexBuffer._rebuild();
  52128. }
  52129. };
  52130. /**
  52131. * Is this system ready to be used/rendered
  52132. * @return true if the system is ready
  52133. */
  52134. ParticleSystem.prototype.isReady = function () {
  52135. var effect = this._getEffect();
  52136. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52137. return false;
  52138. }
  52139. return true;
  52140. };
  52141. /**
  52142. * Renders the particle system in its current state.
  52143. * @returns the current number of particles
  52144. */
  52145. ParticleSystem.prototype.render = function () {
  52146. var effect = this._getEffect();
  52147. // Check
  52148. if (!this.isReady() || !this._particles.length) {
  52149. return 0;
  52150. }
  52151. var engine = this._scene.getEngine();
  52152. // Render
  52153. engine.enableEffect(effect);
  52154. engine.setState(false);
  52155. var viewMatrix = this._scene.getViewMatrix();
  52156. effect.setTexture("diffuseSampler", this.particleTexture);
  52157. effect.setMatrix("view", viewMatrix);
  52158. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52159. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52160. var baseSize = this.particleTexture.getBaseSize();
  52161. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52162. }
  52163. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52164. if (this._scene.clipPlane) {
  52165. var clipPlane = this._scene.clipPlane;
  52166. var invView = viewMatrix.clone();
  52167. invView.invert();
  52168. effect.setMatrix("invView", invView);
  52169. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52170. }
  52171. // VBOs
  52172. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52173. // Draw order
  52174. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52175. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52176. }
  52177. else {
  52178. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52179. }
  52180. if (this.forceDepthWrite) {
  52181. engine.setDepthWrite(true);
  52182. }
  52183. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52184. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52185. return this._particles.length;
  52186. };
  52187. /**
  52188. * Disposes the particle system and free the associated resources
  52189. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52190. */
  52191. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52192. if (disposeTexture === void 0) { disposeTexture = true; }
  52193. if (this._vertexBuffer) {
  52194. this._vertexBuffer.dispose();
  52195. this._vertexBuffer = null;
  52196. }
  52197. if (this._indexBuffer) {
  52198. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52199. this._indexBuffer = null;
  52200. }
  52201. if (disposeTexture && this.particleTexture) {
  52202. this.particleTexture.dispose();
  52203. this.particleTexture = null;
  52204. }
  52205. this._removeFromRoot();
  52206. // Remove from scene
  52207. var index = this._scene.particleSystems.indexOf(this);
  52208. if (index > -1) {
  52209. this._scene.particleSystems.splice(index, 1);
  52210. }
  52211. // Callback
  52212. this.onDisposeObservable.notifyObservers(this);
  52213. this.onDisposeObservable.clear();
  52214. };
  52215. /**
  52216. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52217. * @param radius The radius of the sphere to emit from
  52218. * @returns the emitter
  52219. */
  52220. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52221. if (radius === void 0) { radius = 1; }
  52222. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52223. this.particleEmitterType = particleEmitter;
  52224. return particleEmitter;
  52225. };
  52226. /**
  52227. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52228. * @param radius The radius of the sphere to emit from
  52229. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52230. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52231. * @returns the emitter
  52232. */
  52233. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52234. if (radius === void 0) { radius = 1; }
  52235. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52236. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52237. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52238. this.particleEmitterType = particleEmitter;
  52239. return particleEmitter;
  52240. };
  52241. /**
  52242. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52243. * @param radius The radius of the cone to emit from
  52244. * @param angle The base angle of the cone
  52245. * @returns the emitter
  52246. */
  52247. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52248. if (radius === void 0) { radius = 1; }
  52249. if (angle === void 0) { angle = Math.PI / 4; }
  52250. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52251. this.particleEmitterType = particleEmitter;
  52252. return particleEmitter;
  52253. };
  52254. // 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.
  52255. /**
  52256. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52257. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52258. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52259. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52260. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52261. * @returns the emitter
  52262. */
  52263. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52264. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52265. this.direction1 = direction1;
  52266. this.direction2 = direction2;
  52267. this.minEmitBox = minEmitBox;
  52268. this.maxEmitBox = maxEmitBox;
  52269. this.particleEmitterType = particleEmitter;
  52270. return particleEmitter;
  52271. };
  52272. // Clone
  52273. /**
  52274. * Clones the particle system.
  52275. * @param name The name of the cloned object
  52276. * @param newEmitter The new emitter to use
  52277. * @returns the cloned particle system
  52278. */
  52279. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52280. var custom = null;
  52281. var program = null;
  52282. if (this.customShader != null) {
  52283. program = this.customShader;
  52284. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52285. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52286. }
  52287. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52288. result.customShader = program;
  52289. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52290. if (newEmitter === undefined) {
  52291. newEmitter = this.emitter;
  52292. }
  52293. result.emitter = newEmitter;
  52294. if (this.particleTexture) {
  52295. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52296. }
  52297. if (!this.preventAutoStart) {
  52298. result.start();
  52299. }
  52300. return result;
  52301. };
  52302. /**
  52303. * Serializes the particle system to a JSON object.
  52304. * @returns the JSON object
  52305. */
  52306. ParticleSystem.prototype.serialize = function () {
  52307. var serializationObject = {};
  52308. serializationObject.name = this.name;
  52309. serializationObject.id = this.id;
  52310. // Emitter
  52311. if (this.emitter.position) {
  52312. var emitterMesh = this.emitter;
  52313. serializationObject.emitterId = emitterMesh.id;
  52314. }
  52315. else {
  52316. var emitterPosition = this.emitter;
  52317. serializationObject.emitter = emitterPosition.asArray();
  52318. }
  52319. serializationObject.capacity = this.getCapacity();
  52320. if (this.particleTexture) {
  52321. serializationObject.textureName = this.particleTexture.name;
  52322. }
  52323. // Animations
  52324. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52325. // Particle system
  52326. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52327. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52328. serializationObject.minSize = this.minSize;
  52329. serializationObject.maxSize = this.maxSize;
  52330. serializationObject.minEmitPower = this.minEmitPower;
  52331. serializationObject.maxEmitPower = this.maxEmitPower;
  52332. serializationObject.minLifeTime = this.minLifeTime;
  52333. serializationObject.maxLifeTime = this.maxLifeTime;
  52334. serializationObject.emitRate = this.emitRate;
  52335. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52336. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52337. serializationObject.gravity = this.gravity.asArray();
  52338. serializationObject.direction1 = this.direction1.asArray();
  52339. serializationObject.direction2 = this.direction2.asArray();
  52340. serializationObject.color1 = this.color1.asArray();
  52341. serializationObject.color2 = this.color2.asArray();
  52342. serializationObject.colorDead = this.colorDead.asArray();
  52343. serializationObject.updateSpeed = this.updateSpeed;
  52344. serializationObject.targetStopDuration = this.targetStopDuration;
  52345. serializationObject.textureMask = this.textureMask.asArray();
  52346. serializationObject.blendMode = this.blendMode;
  52347. serializationObject.customShader = this.customShader;
  52348. serializationObject.preventAutoStart = this.preventAutoStart;
  52349. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52350. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52351. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52352. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52353. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52354. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52355. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52356. // Emitter
  52357. if (this.particleEmitterType) {
  52358. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52359. }
  52360. return serializationObject;
  52361. };
  52362. /**
  52363. * Parses a JSON object to create a particle system.
  52364. * @param parsedParticleSystem The JSON object to parse
  52365. * @param scene The scene to create the particle system in
  52366. * @param rootUrl The root url to use to load external dependencies like texture
  52367. * @returns the Parsed particle system
  52368. */
  52369. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52370. var name = parsedParticleSystem.name;
  52371. var custom = null;
  52372. var program = null;
  52373. if (parsedParticleSystem.customShader) {
  52374. program = parsedParticleSystem.customShader;
  52375. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52376. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52377. }
  52378. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52379. particleSystem.customShader = program;
  52380. if (parsedParticleSystem.id) {
  52381. particleSystem.id = parsedParticleSystem.id;
  52382. }
  52383. // Auto start
  52384. if (parsedParticleSystem.preventAutoStart) {
  52385. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52386. }
  52387. // Texture
  52388. if (parsedParticleSystem.textureName) {
  52389. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52390. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52391. }
  52392. // Emitter
  52393. if (parsedParticleSystem.emitterId) {
  52394. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52395. }
  52396. else {
  52397. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52398. }
  52399. // Animations
  52400. if (parsedParticleSystem.animations) {
  52401. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52402. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52403. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52404. }
  52405. }
  52406. if (parsedParticleSystem.autoAnimate) {
  52407. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52408. }
  52409. // Particle system
  52410. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52411. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52412. particleSystem.minSize = parsedParticleSystem.minSize;
  52413. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52414. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52415. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52416. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52417. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52418. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52419. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52420. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52421. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52422. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52423. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52424. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52425. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52426. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52427. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52428. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52429. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52430. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52431. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52432. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52433. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52434. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52435. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52436. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52437. if (!particleSystem.preventAutoStart) {
  52438. particleSystem.start();
  52439. }
  52440. return particleSystem;
  52441. };
  52442. /**
  52443. * Source color is added to the destination color without alpha affecting the result.
  52444. */
  52445. ParticleSystem.BLENDMODE_ONEONE = 0;
  52446. /**
  52447. * Blend current color and particle color using particle’s alpha.
  52448. */
  52449. ParticleSystem.BLENDMODE_STANDARD = 1;
  52450. return ParticleSystem;
  52451. }());
  52452. BABYLON.ParticleSystem = ParticleSystem;
  52453. })(BABYLON || (BABYLON = {}));
  52454. //# sourceMappingURL=babylon.particleSystem.js.map
  52455. "use strict";
  52456. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52457. "use strict";
  52458. var BABYLON;
  52459. (function (BABYLON) {
  52460. /**
  52461. * Particle emitter emitting particles from the inside of a box.
  52462. * It emits the particles randomly between 2 given directions.
  52463. */
  52464. var BoxParticleEmitter = /** @class */ (function () {
  52465. /**
  52466. * Creates a new instance of @see BoxParticleEmitter
  52467. */
  52468. function BoxParticleEmitter() {
  52469. /**
  52470. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52471. */
  52472. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52473. /**
  52474. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52475. */
  52476. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52477. /**
  52478. * 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.
  52479. */
  52480. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52481. /**
  52482. * 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.
  52483. */
  52484. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52485. }
  52486. /**
  52487. * Called by the particle System when the direction is computed for the created particle.
  52488. * @param emitPower is the power of the particle (speed)
  52489. * @param worldMatrix is the world matrix of the particle system
  52490. * @param directionToUpdate is the direction vector to update with the result
  52491. * @param particle is the particle we are computed the direction for
  52492. */
  52493. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52494. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52495. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52496. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52497. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52498. };
  52499. /**
  52500. * Called by the particle System when the position is computed for the created particle.
  52501. * @param worldMatrix is the world matrix of the particle system
  52502. * @param positionToUpdate is the position vector to update with the result
  52503. * @param particle is the particle we are computed the position for
  52504. */
  52505. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52506. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52507. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52508. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52509. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52510. };
  52511. /**
  52512. * Clones the current emitter and returns a copy of it
  52513. * @returns the new emitter
  52514. */
  52515. BoxParticleEmitter.prototype.clone = function () {
  52516. var newOne = new BoxParticleEmitter();
  52517. BABYLON.Tools.DeepCopy(this, newOne);
  52518. return newOne;
  52519. };
  52520. /**
  52521. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52522. * @param effect defines the update shader
  52523. */
  52524. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52525. effect.setVector3("direction1", this.direction1);
  52526. effect.setVector3("direction2", this.direction2);
  52527. effect.setVector3("minEmitBox", this.minEmitBox);
  52528. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52529. };
  52530. /**
  52531. * Returns a string to use to update the GPU particles update shader
  52532. * @returns a string containng the defines string
  52533. */
  52534. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52535. return "#define BOXEMITTER";
  52536. };
  52537. /**
  52538. * Returns the string "BoxEmitter"
  52539. * @returns a string containing the class name
  52540. */
  52541. BoxParticleEmitter.prototype.getClassName = function () {
  52542. return "BoxEmitter";
  52543. };
  52544. /**
  52545. * Serializes the particle system to a JSON object.
  52546. * @returns the JSON object
  52547. */
  52548. BoxParticleEmitter.prototype.serialize = function () {
  52549. var serializationObject = {};
  52550. serializationObject.type = this.getClassName();
  52551. serializationObject.direction1 = this.direction1.asArray();
  52552. ;
  52553. serializationObject.direction2 = this.direction2.asArray();
  52554. ;
  52555. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52556. ;
  52557. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52558. ;
  52559. return serializationObject;
  52560. };
  52561. /**
  52562. * Parse properties from a JSON object
  52563. * @param serializationObject defines the JSON object
  52564. */
  52565. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52566. this.direction1.copyFrom(serializationObject.direction1);
  52567. this.direction2.copyFrom(serializationObject.direction2);
  52568. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52569. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52570. };
  52571. return BoxParticleEmitter;
  52572. }());
  52573. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52574. })(BABYLON || (BABYLON = {}));
  52575. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52576. "use strict";
  52577. var BABYLON;
  52578. (function (BABYLON) {
  52579. /**
  52580. * Particle emitter emitting particles from the inside of a cone.
  52581. * It emits the particles alongside the cone volume from the base to the particle.
  52582. * The emission direction might be randomized.
  52583. */
  52584. var ConeParticleEmitter = /** @class */ (function () {
  52585. /**
  52586. * Creates a new instance of @see ConeParticleEmitter
  52587. * @param radius the radius of the emission cone (1 by default)
  52588. * @param angles the cone base angle (PI by default)
  52589. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52590. */
  52591. function ConeParticleEmitter(radius,
  52592. /**
  52593. * The radius of the emission cone.
  52594. */
  52595. angle,
  52596. /**
  52597. * The cone base angle.
  52598. */
  52599. directionRandomizer) {
  52600. if (radius === void 0) { radius = 1; }
  52601. if (angle === void 0) { angle = Math.PI; }
  52602. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52603. this.angle = angle;
  52604. this.directionRandomizer = directionRandomizer;
  52605. this.radius = radius;
  52606. }
  52607. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52608. /**
  52609. * Gets the radius of the emission cone.
  52610. */
  52611. get: function () {
  52612. return this._radius;
  52613. },
  52614. /**
  52615. * Sets the radius of the emission cone.
  52616. */
  52617. set: function (value) {
  52618. this._radius = value;
  52619. if (this.angle !== 0) {
  52620. this._height = value / Math.tan(this.angle / 2);
  52621. }
  52622. else {
  52623. this._height = 1;
  52624. }
  52625. },
  52626. enumerable: true,
  52627. configurable: true
  52628. });
  52629. /**
  52630. * Called by the particle System when the direction is computed for the created particle.
  52631. * @param emitPower is the power of the particle (speed)
  52632. * @param worldMatrix is the world matrix of the particle system
  52633. * @param directionToUpdate is the direction vector to update with the result
  52634. * @param particle is the particle we are computed the direction for
  52635. */
  52636. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52637. if (this.angle === 0) {
  52638. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52639. }
  52640. else {
  52641. // measure the direction Vector from the emitter to the particle.
  52642. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52643. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52644. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52645. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52646. direction.x += randX;
  52647. direction.y += randY;
  52648. direction.z += randZ;
  52649. direction.normalize();
  52650. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52651. }
  52652. };
  52653. /**
  52654. * Called by the particle System when the position is computed for the created particle.
  52655. * @param worldMatrix is the world matrix of the particle system
  52656. * @param positionToUpdate is the position vector to update with the result
  52657. * @param particle is the particle we are computed the position for
  52658. */
  52659. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52660. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52661. var h = BABYLON.Scalar.RandomRange(0, 1);
  52662. // Better distribution in a cone at normal angles.
  52663. h = 1 - h * h;
  52664. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52665. radius = radius * h / this._height;
  52666. var randX = radius * Math.sin(s);
  52667. var randZ = radius * Math.cos(s);
  52668. var randY = h * this._height;
  52669. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52670. };
  52671. /**
  52672. * Clones the current emitter and returns a copy of it
  52673. * @returns the new emitter
  52674. */
  52675. ConeParticleEmitter.prototype.clone = function () {
  52676. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52677. BABYLON.Tools.DeepCopy(this, newOne);
  52678. return newOne;
  52679. };
  52680. /**
  52681. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52682. * @param effect defines the update shader
  52683. */
  52684. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52685. effect.setFloat("radius", this.radius);
  52686. effect.setFloat("angle", this.angle);
  52687. effect.setFloat("height", this._height);
  52688. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52689. };
  52690. /**
  52691. * Returns a string to use to update the GPU particles update shader
  52692. * @returns a string containng the defines string
  52693. */
  52694. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52695. return "#define CONEEMITTER";
  52696. };
  52697. /**
  52698. * Returns the string "BoxEmitter"
  52699. * @returns a string containing the class name
  52700. */
  52701. ConeParticleEmitter.prototype.getClassName = function () {
  52702. return "ConeEmitter";
  52703. };
  52704. /**
  52705. * Serializes the particle system to a JSON object.
  52706. * @returns the JSON object
  52707. */
  52708. ConeParticleEmitter.prototype.serialize = function () {
  52709. var serializationObject = {};
  52710. serializationObject.type = this.getClassName();
  52711. serializationObject.radius = this.radius;
  52712. serializationObject.angle = this.angle;
  52713. serializationObject.directionRandomizer = this.directionRandomizer;
  52714. return serializationObject;
  52715. };
  52716. /**
  52717. * Parse properties from a JSON object
  52718. * @param serializationObject defines the JSON object
  52719. */
  52720. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52721. this.radius = serializationObject.radius;
  52722. this.angle = serializationObject.angle;
  52723. this.directionRandomizer = serializationObject.directionRandomizer;
  52724. };
  52725. return ConeParticleEmitter;
  52726. }());
  52727. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52728. })(BABYLON || (BABYLON = {}));
  52729. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52730. "use strict";
  52731. var BABYLON;
  52732. (function (BABYLON) {
  52733. /**
  52734. * Particle emitter emitting particles from the inside of a sphere.
  52735. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52736. */
  52737. var SphereParticleEmitter = /** @class */ (function () {
  52738. /**
  52739. * Creates a new instance of @see SphereParticleEmitter
  52740. * @param radius the radius of the emission sphere (1 by default)
  52741. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52742. */
  52743. function SphereParticleEmitter(
  52744. /**
  52745. * The radius of the emission sphere.
  52746. */
  52747. radius,
  52748. /**
  52749. * How much to randomize the particle direction [0-1].
  52750. */
  52751. directionRandomizer) {
  52752. if (radius === void 0) { radius = 1; }
  52753. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52754. this.radius = radius;
  52755. this.directionRandomizer = directionRandomizer;
  52756. }
  52757. /**
  52758. * Called by the particle System when the direction is computed for the created particle.
  52759. * @param emitPower is the power of the particle (speed)
  52760. * @param worldMatrix is the world matrix of the particle system
  52761. * @param directionToUpdate is the direction vector to update with the result
  52762. * @param particle is the particle we are computed the direction for
  52763. */
  52764. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52765. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52766. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52767. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52768. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52769. direction.x += randX;
  52770. direction.y += randY;
  52771. direction.z += randZ;
  52772. direction.normalize();
  52773. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52774. };
  52775. /**
  52776. * Called by the particle System when the position is computed for the created particle.
  52777. * @param worldMatrix is the world matrix of the particle system
  52778. * @param positionToUpdate is the position vector to update with the result
  52779. * @param particle is the particle we are computed the position for
  52780. */
  52781. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52782. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52783. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52784. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52785. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52786. var randY = randRadius * Math.cos(theta);
  52787. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52788. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52789. };
  52790. /**
  52791. * Clones the current emitter and returns a copy of it
  52792. * @returns the new emitter
  52793. */
  52794. SphereParticleEmitter.prototype.clone = function () {
  52795. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52796. BABYLON.Tools.DeepCopy(this, newOne);
  52797. return newOne;
  52798. };
  52799. /**
  52800. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52801. * @param effect defines the update shader
  52802. */
  52803. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52804. effect.setFloat("radius", this.radius);
  52805. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52806. };
  52807. /**
  52808. * Returns a string to use to update the GPU particles update shader
  52809. * @returns a string containng the defines string
  52810. */
  52811. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52812. return "#define SPHEREEMITTER";
  52813. };
  52814. /**
  52815. * Returns the string "SphereParticleEmitter"
  52816. * @returns a string containing the class name
  52817. */
  52818. SphereParticleEmitter.prototype.getClassName = function () {
  52819. return "SphereParticleEmitter";
  52820. };
  52821. /**
  52822. * Serializes the particle system to a JSON object.
  52823. * @returns the JSON object
  52824. */
  52825. SphereParticleEmitter.prototype.serialize = function () {
  52826. var serializationObject = {};
  52827. serializationObject.type = this.getClassName();
  52828. serializationObject.radius = this.radius;
  52829. serializationObject.directionRandomizer = this.directionRandomizer;
  52830. return serializationObject;
  52831. };
  52832. /**
  52833. * Parse properties from a JSON object
  52834. * @param serializationObject defines the JSON object
  52835. */
  52836. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52837. this.radius = serializationObject.radius;
  52838. this.directionRandomizer = serializationObject.directionRandomizer;
  52839. };
  52840. return SphereParticleEmitter;
  52841. }());
  52842. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52843. /**
  52844. * Particle emitter emitting particles from the inside of a sphere.
  52845. * It emits the particles randomly between two vectors.
  52846. */
  52847. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52848. __extends(SphereDirectedParticleEmitter, _super);
  52849. /**
  52850. * Creates a new instance of @see SphereDirectedParticleEmitter
  52851. * @param radius the radius of the emission sphere (1 by default)
  52852. * @param direction1 the min limit of the emission direction (up vector by default)
  52853. * @param direction2 the max limit of the emission direction (up vector by default)
  52854. */
  52855. function SphereDirectedParticleEmitter(radius,
  52856. /**
  52857. * The min limit of the emission direction.
  52858. */
  52859. direction1,
  52860. /**
  52861. * The max limit of the emission direction.
  52862. */
  52863. direction2) {
  52864. if (radius === void 0) { radius = 1; }
  52865. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52866. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52867. var _this = _super.call(this, radius) || this;
  52868. _this.direction1 = direction1;
  52869. _this.direction2 = direction2;
  52870. return _this;
  52871. }
  52872. /**
  52873. * Called by the particle System when the direction is computed for the created particle.
  52874. * @param emitPower is the power of the particle (speed)
  52875. * @param worldMatrix is the world matrix of the particle system
  52876. * @param directionToUpdate is the direction vector to update with the result
  52877. * @param particle is the particle we are computed the direction for
  52878. */
  52879. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52880. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52881. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52882. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52883. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52884. };
  52885. /**
  52886. * Clones the current emitter and returns a copy of it
  52887. * @returns the new emitter
  52888. */
  52889. SphereDirectedParticleEmitter.prototype.clone = function () {
  52890. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52891. BABYLON.Tools.DeepCopy(this, newOne);
  52892. return newOne;
  52893. };
  52894. /**
  52895. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52896. * @param effect defines the update shader
  52897. */
  52898. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52899. effect.setFloat("radius", this.radius);
  52900. effect.setVector3("direction1", this.direction1);
  52901. effect.setVector3("direction2", this.direction2);
  52902. };
  52903. /**
  52904. * Returns a string to use to update the GPU particles update shader
  52905. * @returns a string containng the defines string
  52906. */
  52907. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52908. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52909. };
  52910. /**
  52911. * Returns the string "SphereDirectedParticleEmitter"
  52912. * @returns a string containing the class name
  52913. */
  52914. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52915. return "SphereDirectedParticleEmitter";
  52916. };
  52917. /**
  52918. * Serializes the particle system to a JSON object.
  52919. * @returns the JSON object
  52920. */
  52921. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52922. var serializationObject = _super.prototype.serialize.call(this);
  52923. ;
  52924. serializationObject.direction1 = this.direction1.asArray();
  52925. ;
  52926. serializationObject.direction2 = this.direction2.asArray();
  52927. ;
  52928. return serializationObject;
  52929. };
  52930. /**
  52931. * Parse properties from a JSON object
  52932. * @param serializationObject defines the JSON object
  52933. */
  52934. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52935. _super.prototype.parse.call(this, serializationObject);
  52936. this.direction1.copyFrom(serializationObject.direction1);
  52937. this.direction2.copyFrom(serializationObject.direction2);
  52938. };
  52939. return SphereDirectedParticleEmitter;
  52940. }(SphereParticleEmitter));
  52941. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52942. })(BABYLON || (BABYLON = {}));
  52943. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52944. "use strict";
  52945. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52946. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52947. s = arguments[i];
  52948. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52949. t[p] = s[p];
  52950. }
  52951. return t;
  52952. };
  52953. var BABYLON;
  52954. (function (BABYLON) {
  52955. /**
  52956. * This represents a GPU particle system in Babylon
  52957. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52958. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52959. */
  52960. var GPUParticleSystem = /** @class */ (function () {
  52961. /**
  52962. * Instantiates a GPU particle system.
  52963. * 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.
  52964. * @param name The name of the particle system
  52965. * @param capacity The max number of particles alive at the same time
  52966. * @param scene The scene the particle system belongs to
  52967. */
  52968. function GPUParticleSystem(name, options, scene) {
  52969. /**
  52970. * The emitter represents the Mesh or position we are attaching the particle system to.
  52971. */
  52972. this.emitter = null;
  52973. /**
  52974. * The rendering group used by the Particle system to chose when to render.
  52975. */
  52976. this.renderingGroupId = 0;
  52977. /**
  52978. * The layer mask we are rendering the particles through.
  52979. */
  52980. this.layerMask = 0x0FFFFFFF;
  52981. this._targetIndex = 0;
  52982. this._currentRenderId = -1;
  52983. this._started = false;
  52984. this._stopped = false;
  52985. this._timeDelta = 0;
  52986. this._attributesStrideSize = 14;
  52987. this._actualFrame = 0;
  52988. /**
  52989. * List of animations used by the particle system.
  52990. */
  52991. this.animations = [];
  52992. /**
  52993. * An event triggered when the system is disposed.
  52994. */
  52995. this.onDisposeObservable = new BABYLON.Observable();
  52996. /**
  52997. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52998. */
  52999. this.updateSpeed = 0.01;
  53000. /**
  53001. * The amount of time the particle system is running (depends of the overall update speed).
  53002. */
  53003. this.targetStopDuration = 0;
  53004. /**
  53005. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53006. */
  53007. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  53008. /**
  53009. * Minimum life time of emitting particles.
  53010. */
  53011. this.minLifeTime = 1;
  53012. /**
  53013. * Maximum life time of emitting particles.
  53014. */
  53015. this.maxLifeTime = 1;
  53016. /**
  53017. * Minimum Size of emitting particles.
  53018. */
  53019. this.minSize = 1;
  53020. /**
  53021. * Maximum Size of emitting particles.
  53022. */
  53023. this.maxSize = 1;
  53024. /**
  53025. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53026. */
  53027. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53028. /**
  53029. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53030. */
  53031. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53032. /**
  53033. * Color the particle will have at the end of its lifetime.
  53034. */
  53035. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53036. /**
  53037. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53038. */
  53039. this.emitRate = 100;
  53040. /**
  53041. * You can use gravity if you want to give an orientation to your particles.
  53042. */
  53043. this.gravity = BABYLON.Vector3.Zero();
  53044. /**
  53045. * Minimum power of emitting particles.
  53046. */
  53047. this.minEmitPower = 1;
  53048. /**
  53049. * Maximum power of emitting particles.
  53050. */
  53051. this.maxEmitPower = 1;
  53052. /**
  53053. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53054. * to override the particles.
  53055. */
  53056. this.forceDepthWrite = false;
  53057. this.id = name;
  53058. this.name = name;
  53059. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53060. this._engine = this._scene.getEngine();
  53061. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53062. this._capacity = fullOptions.capacity;
  53063. this._activeCount = fullOptions.capacity;
  53064. this._currentActiveCount = 0;
  53065. this._scene.particleSystems.push(this);
  53066. this._updateEffectOptions = {
  53067. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53068. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53069. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53070. uniformBuffersNames: [],
  53071. samplers: ["randomSampler"],
  53072. defines: "",
  53073. fallbacks: null,
  53074. onCompiled: null,
  53075. onError: null,
  53076. indexParameters: null,
  53077. maxSimultaneousLights: 0,
  53078. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53079. };
  53080. // Random data
  53081. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53082. var d = [];
  53083. for (var i = 0; i < maxTextureSize; ++i) {
  53084. d.push(Math.random());
  53085. d.push(Math.random());
  53086. d.push(Math.random());
  53087. d.push(Math.random());
  53088. }
  53089. 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);
  53090. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53091. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53092. this._randomTextureSize = maxTextureSize;
  53093. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53094. }
  53095. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53096. /**
  53097. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53098. */
  53099. get: function () {
  53100. if (!BABYLON.Engine.LastCreatedEngine) {
  53101. return false;
  53102. }
  53103. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53104. },
  53105. enumerable: true,
  53106. configurable: true
  53107. });
  53108. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53109. /**
  53110. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53111. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53112. */
  53113. get: function () {
  53114. if (this.particleEmitterType.direction1) {
  53115. return this.particleEmitterType.direction1;
  53116. }
  53117. return BABYLON.Vector3.Zero();
  53118. },
  53119. set: function (value) {
  53120. if (this.particleEmitterType.direction1) {
  53121. this.particleEmitterType.direction1 = value;
  53122. }
  53123. },
  53124. enumerable: true,
  53125. configurable: true
  53126. });
  53127. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53128. /**
  53129. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53130. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53131. */
  53132. get: function () {
  53133. if (this.particleEmitterType.direction2) {
  53134. return this.particleEmitterType.direction2;
  53135. }
  53136. return BABYLON.Vector3.Zero();
  53137. },
  53138. set: function (value) {
  53139. if (this.particleEmitterType.direction2) {
  53140. this.particleEmitterType.direction2 = value;
  53141. }
  53142. },
  53143. enumerable: true,
  53144. configurable: true
  53145. });
  53146. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53147. /**
  53148. * 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.
  53149. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53150. */
  53151. get: function () {
  53152. if (this.particleEmitterType.minEmitBox) {
  53153. return this.particleEmitterType.minEmitBox;
  53154. }
  53155. return BABYLON.Vector3.Zero();
  53156. },
  53157. set: function (value) {
  53158. if (this.particleEmitterType.minEmitBox) {
  53159. this.particleEmitterType.minEmitBox = value;
  53160. }
  53161. },
  53162. enumerable: true,
  53163. configurable: true
  53164. });
  53165. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53166. /**
  53167. * 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.
  53168. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53169. */
  53170. get: function () {
  53171. if (this.particleEmitterType.maxEmitBox) {
  53172. return this.particleEmitterType.maxEmitBox;
  53173. }
  53174. return BABYLON.Vector3.Zero();
  53175. },
  53176. set: function (value) {
  53177. if (this.particleEmitterType.maxEmitBox) {
  53178. this.particleEmitterType.maxEmitBox = value;
  53179. }
  53180. },
  53181. enumerable: true,
  53182. configurable: true
  53183. });
  53184. /**
  53185. * Gets the maximum number of particles active at the same time.
  53186. * @returns The max number of active particles.
  53187. */
  53188. GPUParticleSystem.prototype.getCapacity = function () {
  53189. return this._capacity;
  53190. };
  53191. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53192. /**
  53193. * Gets or set the number of active particles
  53194. */
  53195. get: function () {
  53196. return this._activeCount;
  53197. },
  53198. set: function (value) {
  53199. this._activeCount = Math.min(value, this._capacity);
  53200. },
  53201. enumerable: true,
  53202. configurable: true
  53203. });
  53204. /**
  53205. * Is this system ready to be used/rendered
  53206. * @return true if the system is ready
  53207. */
  53208. GPUParticleSystem.prototype.isReady = function () {
  53209. if (!this.emitter || !this._updateEffect || !this._renderEffect ||
  53210. !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53211. return false;
  53212. }
  53213. return true;
  53214. };
  53215. /**
  53216. * Gets Wether the system has been started.
  53217. * @returns True if it has been started, otherwise false.
  53218. */
  53219. GPUParticleSystem.prototype.isStarted = function () {
  53220. return this._started;
  53221. };
  53222. /**
  53223. * Starts the particle system and begins to emit.
  53224. */
  53225. GPUParticleSystem.prototype.start = function () {
  53226. this._started = true;
  53227. this._stopped = false;
  53228. };
  53229. /**
  53230. * Stops the particle system.
  53231. */
  53232. GPUParticleSystem.prototype.stop = function () {
  53233. this._stopped = true;
  53234. };
  53235. /**
  53236. * Remove all active particles
  53237. */
  53238. GPUParticleSystem.prototype.reset = function () {
  53239. this._releaseBuffers();
  53240. this._releaseVAOs();
  53241. this._currentActiveCount = 0;
  53242. this._targetIndex = 0;
  53243. };
  53244. /**
  53245. * Returns the string "GPUParticleSystem"
  53246. * @returns a string containing the class name
  53247. */
  53248. GPUParticleSystem.prototype.getClassName = function () {
  53249. return "GPUParticleSystem";
  53250. };
  53251. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53252. var updateVertexBuffers = {};
  53253. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53254. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53255. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53256. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53257. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53258. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53259. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53260. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53261. this._engine.bindArrayBuffer(null);
  53262. return vao;
  53263. };
  53264. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53265. var renderVertexBuffers = {};
  53266. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53267. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53268. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53269. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53270. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53271. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53272. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53273. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53274. this._engine.bindArrayBuffer(null);
  53275. return vao;
  53276. };
  53277. GPUParticleSystem.prototype._initialize = function (force) {
  53278. if (force === void 0) { force = false; }
  53279. if (this._buffer0 && !force) {
  53280. return;
  53281. }
  53282. var engine = this._scene.getEngine();
  53283. var data = new Array();
  53284. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53285. // position
  53286. data.push(0.0);
  53287. data.push(0.0);
  53288. data.push(0.0);
  53289. // Age and life
  53290. data.push(0.0); // create the particle as a dead one to create a new one at start
  53291. data.push(0.0);
  53292. // Seed
  53293. data.push(Math.random());
  53294. // Size
  53295. data.push(0.0);
  53296. // color
  53297. data.push(0.0);
  53298. data.push(0.0);
  53299. data.push(0.0);
  53300. data.push(0.0);
  53301. // direction
  53302. data.push(0.0);
  53303. data.push(0.0);
  53304. data.push(0.0);
  53305. }
  53306. // Sprite data
  53307. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53308. -0.5, 0.5, 0, 1,
  53309. -0.5, -0.5, 0, 0,
  53310. 0.5, -0.5, 1, 0]);
  53311. // Buffers
  53312. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53313. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53314. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53315. // Update VAO
  53316. this._updateVAO = [];
  53317. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53318. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53319. // Render VAO
  53320. this._renderVAO = [];
  53321. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53322. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53323. // Links
  53324. this._sourceBuffer = this._buffer0;
  53325. this._targetBuffer = this._buffer1;
  53326. };
  53327. /** @ignore */
  53328. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53329. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53330. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53331. return;
  53332. }
  53333. this._updateEffectOptions.defines = defines;
  53334. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53335. };
  53336. /** @ignore */
  53337. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53338. var defines = "";
  53339. if (this._scene.clipPlane) {
  53340. defines = "\n#define CLIPPLANE";
  53341. }
  53342. if (this._renderEffect && this._renderEffect.defines === defines) {
  53343. return;
  53344. }
  53345. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53346. };
  53347. /**
  53348. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53349. */
  53350. GPUParticleSystem.prototype.animate = function () {
  53351. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53352. this._actualFrame += this._timeDelta;
  53353. if (!this._stopped) {
  53354. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53355. this.stop();
  53356. }
  53357. }
  53358. };
  53359. /**
  53360. * Renders the particle system in its current state.
  53361. * @returns the current number of particles
  53362. */
  53363. GPUParticleSystem.prototype.render = function () {
  53364. if (!this._started) {
  53365. return 0;
  53366. }
  53367. this._recreateUpdateEffect();
  53368. this._recreateRenderEffect();
  53369. if (!this.isReady()) {
  53370. return 0;
  53371. }
  53372. if (this._currentRenderId === this._scene.getRenderId()) {
  53373. return 0;
  53374. }
  53375. this._currentRenderId = this._scene.getRenderId();
  53376. // Get everything ready to render
  53377. this._initialize();
  53378. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53379. // Enable update effect
  53380. this._engine.enableEffect(this._updateEffect);
  53381. this._engine.setState(false);
  53382. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53383. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53384. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53385. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53386. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53387. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53388. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53389. this._updateEffect.setDirectColor4("color1", this.color1);
  53390. this._updateEffect.setDirectColor4("color2", this.color2);
  53391. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53392. this._updateEffect.setVector3("gravity", this.gravity);
  53393. if (this.particleEmitterType) {
  53394. this.particleEmitterType.applyToShader(this._updateEffect);
  53395. }
  53396. var emitterWM;
  53397. if (this.emitter.position) {
  53398. var emitterMesh = this.emitter;
  53399. emitterWM = emitterMesh.getWorldMatrix();
  53400. }
  53401. else {
  53402. var emitterPosition = this.emitter;
  53403. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53404. }
  53405. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53406. // Bind source VAO
  53407. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53408. // Update
  53409. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53410. this._engine.setRasterizerState(false);
  53411. this._engine.beginTransformFeedback();
  53412. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53413. this._engine.endTransformFeedback();
  53414. this._engine.setRasterizerState(true);
  53415. this._engine.bindTransformFeedbackBuffer(null);
  53416. // Enable render effect
  53417. this._engine.enableEffect(this._renderEffect);
  53418. var viewMatrix = this._scene.getViewMatrix();
  53419. this._renderEffect.setMatrix("view", viewMatrix);
  53420. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53421. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53422. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53423. if (this._scene.clipPlane) {
  53424. var clipPlane = this._scene.clipPlane;
  53425. var invView = viewMatrix.clone();
  53426. invView.invert();
  53427. this._renderEffect.setMatrix("invView", invView);
  53428. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53429. }
  53430. // Draw order
  53431. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53432. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53433. }
  53434. else {
  53435. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53436. }
  53437. if (this.forceDepthWrite) {
  53438. this._engine.setDepthWrite(true);
  53439. }
  53440. // Bind source VAO
  53441. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53442. // Render
  53443. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53444. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53445. // Switch VAOs
  53446. this._targetIndex++;
  53447. if (this._targetIndex === 2) {
  53448. this._targetIndex = 0;
  53449. }
  53450. // Switch buffers
  53451. var tmpBuffer = this._sourceBuffer;
  53452. this._sourceBuffer = this._targetBuffer;
  53453. this._targetBuffer = tmpBuffer;
  53454. return this._currentActiveCount;
  53455. };
  53456. /**
  53457. * Rebuilds the particle system
  53458. */
  53459. GPUParticleSystem.prototype.rebuild = function () {
  53460. this._initialize(true);
  53461. };
  53462. GPUParticleSystem.prototype._releaseBuffers = function () {
  53463. if (this._buffer0) {
  53464. this._buffer0.dispose();
  53465. this._buffer0 = null;
  53466. }
  53467. if (this._buffer1) {
  53468. this._buffer1.dispose();
  53469. this._buffer1 = null;
  53470. }
  53471. if (this._spriteBuffer) {
  53472. this._spriteBuffer.dispose();
  53473. this._spriteBuffer = null;
  53474. }
  53475. };
  53476. GPUParticleSystem.prototype._releaseVAOs = function () {
  53477. if (!this._updateVAO) {
  53478. return;
  53479. }
  53480. for (var index = 0; index < this._updateVAO.length; index++) {
  53481. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53482. }
  53483. this._updateVAO = [];
  53484. for (var index = 0; index < this._renderVAO.length; index++) {
  53485. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53486. }
  53487. this._renderVAO = [];
  53488. };
  53489. /**
  53490. * Disposes the particle system and free the associated resources
  53491. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53492. */
  53493. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53494. if (disposeTexture === void 0) { disposeTexture = true; }
  53495. var index = this._scene.particleSystems.indexOf(this);
  53496. if (index > -1) {
  53497. this._scene.particleSystems.splice(index, 1);
  53498. }
  53499. this._releaseBuffers();
  53500. this._releaseVAOs();
  53501. if (this._randomTexture) {
  53502. this._randomTexture.dispose();
  53503. this._randomTexture = null;
  53504. }
  53505. if (disposeTexture && this.particleTexture) {
  53506. this.particleTexture.dispose();
  53507. this.particleTexture = null;
  53508. }
  53509. // Callback
  53510. this.onDisposeObservable.notifyObservers(this);
  53511. this.onDisposeObservable.clear();
  53512. };
  53513. /**
  53514. * Clones the particle system.
  53515. * @param name The name of the cloned object
  53516. * @param newEmitter The new emitter to use
  53517. * @returns the cloned particle system
  53518. */
  53519. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53520. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53521. BABYLON.Tools.DeepCopy(this, result);
  53522. if (newEmitter === undefined) {
  53523. newEmitter = this.emitter;
  53524. }
  53525. result.emitter = newEmitter;
  53526. if (this.particleTexture) {
  53527. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53528. }
  53529. return result;
  53530. };
  53531. /**
  53532. * Serializes the particle system to a JSON object.
  53533. * @returns the JSON object
  53534. */
  53535. GPUParticleSystem.prototype.serialize = function () {
  53536. var serializationObject = {};
  53537. serializationObject.name = this.name;
  53538. serializationObject.id = this.id;
  53539. // Emitter
  53540. if (this.emitter.position) {
  53541. var emitterMesh = this.emitter;
  53542. serializationObject.emitterId = emitterMesh.id;
  53543. }
  53544. else {
  53545. var emitterPosition = this.emitter;
  53546. serializationObject.emitter = emitterPosition.asArray();
  53547. }
  53548. serializationObject.capacity = this.getCapacity();
  53549. if (this.particleTexture) {
  53550. serializationObject.textureName = this.particleTexture.name;
  53551. }
  53552. // Animations
  53553. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53554. // Particle system
  53555. serializationObject.activeParticleCount = this.activeParticleCount;
  53556. serializationObject.randomTextureSize = this._randomTextureSize;
  53557. serializationObject.minSize = this.minSize;
  53558. serializationObject.maxSize = this.maxSize;
  53559. serializationObject.minEmitPower = this.minEmitPower;
  53560. serializationObject.maxEmitPower = this.maxEmitPower;
  53561. serializationObject.minLifeTime = this.minLifeTime;
  53562. serializationObject.maxLifeTime = this.maxLifeTime;
  53563. serializationObject.emitRate = this.emitRate;
  53564. serializationObject.gravity = this.gravity.asArray();
  53565. serializationObject.color1 = this.color1.asArray();
  53566. serializationObject.color2 = this.color2.asArray();
  53567. serializationObject.colorDead = this.colorDead.asArray();
  53568. serializationObject.updateSpeed = this.updateSpeed;
  53569. serializationObject.targetStopDuration = this.targetStopDuration;
  53570. serializationObject.blendMode = this.blendMode;
  53571. // Emitter
  53572. if (this.particleEmitterType) {
  53573. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53574. }
  53575. return serializationObject;
  53576. };
  53577. /**
  53578. * Parses a JSON object to create a GPU particle system.
  53579. * @param parsedParticleSystem The JSON object to parse
  53580. * @param scene The scene to create the particle system in
  53581. * @param rootUrl The root url to use to load external dependencies like texture
  53582. * @returns the parsed GPU particle system
  53583. */
  53584. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53585. var name = parsedParticleSystem.name;
  53586. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53587. if (parsedParticleSystem.id) {
  53588. particleSystem.id = parsedParticleSystem.id;
  53589. }
  53590. // Texture
  53591. if (parsedParticleSystem.textureName) {
  53592. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53593. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53594. }
  53595. // Emitter
  53596. if (parsedParticleSystem.emitterId) {
  53597. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53598. }
  53599. else {
  53600. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53601. }
  53602. // Animations
  53603. if (parsedParticleSystem.animations) {
  53604. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53605. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53606. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53607. }
  53608. }
  53609. // Particle system
  53610. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53611. particleSystem.minSize = parsedParticleSystem.minSize;
  53612. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53613. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53614. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53615. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53616. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53617. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53618. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53619. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53620. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53621. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53622. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53623. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53624. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53625. // Emitter
  53626. if (parsedParticleSystem.particleEmitterType) {
  53627. var emitterType = void 0;
  53628. switch (parsedParticleSystem.particleEmitterType.type) {
  53629. case "SphereEmitter":
  53630. emitterType = new BABYLON.SphereParticleEmitter();
  53631. break;
  53632. case "SphereDirectedParticleEmitter":
  53633. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53634. break;
  53635. case "ConeEmitter":
  53636. emitterType = new BABYLON.ConeParticleEmitter();
  53637. break;
  53638. case "BoxEmitter":
  53639. default:
  53640. emitterType = new BABYLON.BoxParticleEmitter();
  53641. break;
  53642. }
  53643. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53644. particleSystem.particleEmitterType = emitterType;
  53645. }
  53646. return particleSystem;
  53647. };
  53648. return GPUParticleSystem;
  53649. }());
  53650. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53651. })(BABYLON || (BABYLON = {}));
  53652. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53653. "use strict";
  53654. var BABYLON;
  53655. (function (BABYLON) {
  53656. /**
  53657. * Represents one particle of a solid particle system.
  53658. * @see SolidParticleSystem
  53659. */
  53660. var SolidParticle = /** @class */ (function () {
  53661. /**
  53662. * Creates a Solid Particle object.
  53663. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53664. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53665. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53666. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53667. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53668. * @param shapeId (integer) is the model shape identifier in the SPS.
  53669. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53670. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53671. */
  53672. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53673. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53674. /**
  53675. * particle global index
  53676. */
  53677. this.idx = 0;
  53678. /**
  53679. * The color of the particle
  53680. */
  53681. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53682. /**
  53683. * The world space position of the particle.
  53684. */
  53685. this.position = BABYLON.Vector3.Zero();
  53686. /**
  53687. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53688. */
  53689. this.rotation = BABYLON.Vector3.Zero();
  53690. /**
  53691. * The scaling of the particle.
  53692. */
  53693. this.scaling = BABYLON.Vector3.One();
  53694. /**
  53695. * The uvs of the particle.
  53696. */
  53697. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53698. /**
  53699. * The current speed of the particle.
  53700. */
  53701. this.velocity = BABYLON.Vector3.Zero();
  53702. /**
  53703. * The pivot point in the particle local space.
  53704. */
  53705. this.pivot = BABYLON.Vector3.Zero();
  53706. /**
  53707. * Must the particle be translated from its pivot point in its local space ?
  53708. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53709. * Default : false
  53710. */
  53711. this.translateFromPivot = false;
  53712. /**
  53713. * Is the particle active or not ?
  53714. */
  53715. this.alive = true;
  53716. /**
  53717. * Is the particle visible or not ?
  53718. */
  53719. this.isVisible = true;
  53720. /**
  53721. * Index of this particle in the global "positions" array (Internal use)
  53722. */
  53723. this._pos = 0;
  53724. /**
  53725. * Index of this particle in the global "indices" array (Internal use)
  53726. */
  53727. this._ind = 0;
  53728. /**
  53729. * ModelShape id of this particle
  53730. */
  53731. this.shapeId = 0;
  53732. /**
  53733. * Index of the particle in its shape id (Internal use)
  53734. */
  53735. this.idxInShape = 0;
  53736. /**
  53737. * Still set as invisible in order to skip useless computations (Internal use)
  53738. */
  53739. this._stillInvisible = false;
  53740. /**
  53741. * Last computed particle rotation matrix
  53742. */
  53743. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53744. /**
  53745. * Parent particle Id, if any.
  53746. * Default null.
  53747. */
  53748. this.parentId = null;
  53749. /**
  53750. * Internal global position in the SPS.
  53751. */
  53752. this._globalPosition = BABYLON.Vector3.Zero();
  53753. this.idx = particleIndex;
  53754. this._pos = positionIndex;
  53755. this._ind = indiceIndex;
  53756. this._model = model;
  53757. this.shapeId = shapeId;
  53758. this.idxInShape = idxInShape;
  53759. this._sps = sps;
  53760. if (modelBoundingInfo) {
  53761. this._modelBoundingInfo = modelBoundingInfo;
  53762. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53763. }
  53764. }
  53765. Object.defineProperty(SolidParticle.prototype, "scale", {
  53766. /**
  53767. * Legacy support, changed scale to scaling
  53768. */
  53769. get: function () {
  53770. return this.scaling;
  53771. },
  53772. /**
  53773. * Legacy support, changed scale to scaling
  53774. */
  53775. set: function (scale) {
  53776. this.scaling = scale;
  53777. },
  53778. enumerable: true,
  53779. configurable: true
  53780. });
  53781. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53782. /**
  53783. * Legacy support, changed quaternion to rotationQuaternion
  53784. */
  53785. get: function () {
  53786. return this.rotationQuaternion;
  53787. },
  53788. /**
  53789. * Legacy support, changed quaternion to rotationQuaternion
  53790. */
  53791. set: function (q) {
  53792. this.rotationQuaternion = q;
  53793. },
  53794. enumerable: true,
  53795. configurable: true
  53796. });
  53797. /**
  53798. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53799. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53800. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53801. * @returns true if it intersects
  53802. */
  53803. SolidParticle.prototype.intersectsMesh = function (target) {
  53804. if (!this._boundingInfo || !target._boundingInfo) {
  53805. return false;
  53806. }
  53807. if (this._sps._bSphereOnly) {
  53808. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53809. }
  53810. return this._boundingInfo.intersects(target._boundingInfo, false);
  53811. };
  53812. return SolidParticle;
  53813. }());
  53814. BABYLON.SolidParticle = SolidParticle;
  53815. /**
  53816. * Represents the shape of the model used by one particle of a solid particle system.
  53817. * SPS internal tool, don't use it manually.
  53818. * @see SolidParticleSystem
  53819. */
  53820. var ModelShape = /** @class */ (function () {
  53821. /**
  53822. * 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.
  53823. * SPS internal tool, don't use it manually.
  53824. * @ignore
  53825. */
  53826. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53827. /**
  53828. * length of the shape in the model indices array (internal use)
  53829. */
  53830. this._indicesLength = 0;
  53831. this.shapeID = id;
  53832. this._shape = shape;
  53833. this._indicesLength = indicesLength;
  53834. this._shapeUV = shapeUV;
  53835. this._positionFunction = posFunction;
  53836. this._vertexFunction = vtxFunction;
  53837. }
  53838. return ModelShape;
  53839. }());
  53840. BABYLON.ModelShape = ModelShape;
  53841. /**
  53842. * Represents a Depth Sorted Particle in the solid particle system.
  53843. * @see SolidParticleSystem
  53844. */
  53845. var DepthSortedParticle = /** @class */ (function () {
  53846. function DepthSortedParticle() {
  53847. /**
  53848. * Index of the particle in the "indices" array
  53849. */
  53850. this.ind = 0;
  53851. /**
  53852. * Length of the particle shape in the "indices" array
  53853. */
  53854. this.indicesLength = 0;
  53855. /**
  53856. * Squared distance from the particle to the camera
  53857. */
  53858. this.sqDistance = 0.0;
  53859. }
  53860. return DepthSortedParticle;
  53861. }());
  53862. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53863. })(BABYLON || (BABYLON = {}));
  53864. //# sourceMappingURL=babylon.solidParticle.js.map
  53865. "use strict";
  53866. var BABYLON;
  53867. (function (BABYLON) {
  53868. /**
  53869. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53870. *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.
  53871. * The SPS is also a particle system. It provides some methods to manage the particles.
  53872. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53873. *
  53874. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53875. */
  53876. var SolidParticleSystem = /** @class */ (function () {
  53877. /**
  53878. * Creates a SPS (Solid Particle System) object.
  53879. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53880. * @param scene (Scene) is the scene in which the SPS is added.
  53881. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53882. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53883. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53884. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53885. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53886. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53887. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53888. */
  53889. function SolidParticleSystem(name, scene, options) {
  53890. /**
  53891. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53892. * Example : var p = SPS.particles[i];
  53893. */
  53894. this.particles = new Array();
  53895. /**
  53896. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53897. */
  53898. this.nbParticles = 0;
  53899. /**
  53900. * If the particles must ever face the camera (default false). Useful for planar particles.
  53901. */
  53902. this.billboard = false;
  53903. /**
  53904. * Recompute normals when adding a shape
  53905. */
  53906. this.recomputeNormals = true;
  53907. /**
  53908. * This a counter ofr your own usage. It's not set by any SPS functions.
  53909. */
  53910. this.counter = 0;
  53911. /**
  53912. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53913. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53914. */
  53915. this.vars = {};
  53916. /**
  53917. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53918. */
  53919. this._bSphereOnly = false;
  53920. /**
  53921. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53922. */
  53923. this._bSphereRadiusFactor = 1.0;
  53924. this._positions = new Array();
  53925. this._indices = new Array();
  53926. this._normals = new Array();
  53927. this._colors = new Array();
  53928. this._uvs = new Array();
  53929. this._index = 0; // indices index
  53930. this._updatable = true;
  53931. this._pickable = false;
  53932. this._isVisibilityBoxLocked = false;
  53933. this._alwaysVisible = false;
  53934. this._depthSort = false;
  53935. this._shapeCounter = 0;
  53936. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53937. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53938. this._computeParticleColor = true;
  53939. this._computeParticleTexture = true;
  53940. this._computeParticleRotation = true;
  53941. this._computeParticleVertex = false;
  53942. this._computeBoundingBox = false;
  53943. this._depthSortParticles = true;
  53944. this._cam_axisZ = BABYLON.Vector3.Zero();
  53945. this._cam_axisY = BABYLON.Vector3.Zero();
  53946. this._cam_axisX = BABYLON.Vector3.Zero();
  53947. this._axisZ = BABYLON.Axis.Z;
  53948. this._camDir = BABYLON.Vector3.Zero();
  53949. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53950. this._rotMatrix = new BABYLON.Matrix();
  53951. this._invertMatrix = new BABYLON.Matrix();
  53952. this._rotated = BABYLON.Vector3.Zero();
  53953. this._quaternion = new BABYLON.Quaternion();
  53954. this._vertex = BABYLON.Vector3.Zero();
  53955. this._normal = BABYLON.Vector3.Zero();
  53956. this._yaw = 0.0;
  53957. this._pitch = 0.0;
  53958. this._roll = 0.0;
  53959. this._halfroll = 0.0;
  53960. this._halfpitch = 0.0;
  53961. this._halfyaw = 0.0;
  53962. this._sinRoll = 0.0;
  53963. this._cosRoll = 0.0;
  53964. this._sinPitch = 0.0;
  53965. this._cosPitch = 0.0;
  53966. this._sinYaw = 0.0;
  53967. this._cosYaw = 0.0;
  53968. this._mustUnrotateFixedNormals = false;
  53969. this._minimum = BABYLON.Vector3.Zero();
  53970. this._maximum = BABYLON.Vector3.Zero();
  53971. this._minBbox = BABYLON.Vector3.Zero();
  53972. this._maxBbox = BABYLON.Vector3.Zero();
  53973. this._particlesIntersect = false;
  53974. this._depthSortFunction = function (p1, p2) {
  53975. return (p2.sqDistance - p1.sqDistance);
  53976. };
  53977. this._needs32Bits = false;
  53978. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53979. this._scaledPivot = BABYLON.Vector3.Zero();
  53980. this._particleHasParent = false;
  53981. this.name = name;
  53982. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53983. this._camera = scene.activeCamera;
  53984. this._pickable = options ? options.isPickable : false;
  53985. this._depthSort = options ? options.enableDepthSort : false;
  53986. this._particlesIntersect = options ? options.particleIntersection : false;
  53987. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53988. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53989. if (options && options.updatable) {
  53990. this._updatable = options.updatable;
  53991. }
  53992. else {
  53993. this._updatable = true;
  53994. }
  53995. if (this._pickable) {
  53996. this.pickedParticles = [];
  53997. }
  53998. if (this._depthSort) {
  53999. this.depthSortedParticles = [];
  54000. }
  54001. }
  54002. /**
  54003. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54004. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54005. * @returns the created mesh
  54006. */
  54007. SolidParticleSystem.prototype.buildMesh = function () {
  54008. if (this.nbParticles === 0) {
  54009. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54010. this.addShape(triangle, 1);
  54011. triangle.dispose();
  54012. }
  54013. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54014. this._positions32 = new Float32Array(this._positions);
  54015. this._uvs32 = new Float32Array(this._uvs);
  54016. this._colors32 = new Float32Array(this._colors);
  54017. if (this.recomputeNormals) {
  54018. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54019. }
  54020. this._normals32 = new Float32Array(this._normals);
  54021. this._fixedNormal32 = new Float32Array(this._normals);
  54022. if (this._mustUnrotateFixedNormals) {
  54023. this._unrotateFixedNormals();
  54024. }
  54025. var vertexData = new BABYLON.VertexData();
  54026. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54027. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54028. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54029. if (this._uvs32) {
  54030. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54031. ;
  54032. }
  54033. if (this._colors32) {
  54034. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54035. }
  54036. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54037. vertexData.applyToMesh(mesh, this._updatable);
  54038. this.mesh = mesh;
  54039. this.mesh.isPickable = this._pickable;
  54040. // free memory
  54041. if (!this._depthSort) {
  54042. this._indices = null;
  54043. }
  54044. this._positions = null;
  54045. this._normals = null;
  54046. this._uvs = null;
  54047. this._colors = null;
  54048. if (!this._updatable) {
  54049. this.particles.length = 0;
  54050. }
  54051. return mesh;
  54052. };
  54053. /**
  54054. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54055. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54056. * Thus the particles generated from `digest()` have their property `position` set yet.
  54057. * @param mesh ( Mesh ) is the mesh to be digested
  54058. * @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
  54059. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54060. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54061. * @returns the current SPS
  54062. */
  54063. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54064. var size = (options && options.facetNb) || 1;
  54065. var number = (options && options.number) || 0;
  54066. var delta = (options && options.delta) || 0;
  54067. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54068. var meshInd = mesh.getIndices();
  54069. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54070. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54071. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54072. var f = 0; // facet counter
  54073. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54074. // compute size from number
  54075. if (number) {
  54076. number = (number > totalFacets) ? totalFacets : number;
  54077. size = Math.round(totalFacets / number);
  54078. delta = 0;
  54079. }
  54080. else {
  54081. size = (size > totalFacets) ? totalFacets : size;
  54082. }
  54083. var facetPos = []; // submesh positions
  54084. var facetInd = []; // submesh indices
  54085. var facetUV = []; // submesh UV
  54086. var facetCol = []; // submesh colors
  54087. var barycenter = BABYLON.Vector3.Zero();
  54088. var sizeO = size;
  54089. while (f < totalFacets) {
  54090. size = sizeO + Math.floor((1 + delta) * Math.random());
  54091. if (f > totalFacets - size) {
  54092. size = totalFacets - f;
  54093. }
  54094. // reset temp arrays
  54095. facetPos.length = 0;
  54096. facetInd.length = 0;
  54097. facetUV.length = 0;
  54098. facetCol.length = 0;
  54099. // iterate over "size" facets
  54100. var fi = 0;
  54101. for (var j = f * 3; j < (f + size) * 3; j++) {
  54102. facetInd.push(fi);
  54103. var i = meshInd[j];
  54104. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54105. if (meshUV) {
  54106. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54107. }
  54108. if (meshCol) {
  54109. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54110. }
  54111. fi++;
  54112. }
  54113. // create a model shape for each single particle
  54114. var idx = this.nbParticles;
  54115. var shape = this._posToShape(facetPos);
  54116. var shapeUV = this._uvsToShapeUV(facetUV);
  54117. // compute the barycenter of the shape
  54118. var v;
  54119. for (v = 0; v < shape.length; v++) {
  54120. barycenter.addInPlace(shape[v]);
  54121. }
  54122. barycenter.scaleInPlace(1 / shape.length);
  54123. // shift the shape from its barycenter to the origin
  54124. for (v = 0; v < shape.length; v++) {
  54125. shape[v].subtractInPlace(barycenter);
  54126. }
  54127. var bInfo;
  54128. if (this._particlesIntersect) {
  54129. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54130. }
  54131. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54132. // add the particle in the SPS
  54133. var currentPos = this._positions.length;
  54134. var currentInd = this._indices.length;
  54135. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54136. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54137. // initialize the particle position
  54138. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54139. this._index += shape.length;
  54140. idx++;
  54141. this.nbParticles++;
  54142. this._shapeCounter++;
  54143. f += size;
  54144. }
  54145. return this;
  54146. };
  54147. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54148. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54149. var index = 0;
  54150. var idx = 0;
  54151. for (var p = 0; p < this.particles.length; p++) {
  54152. this._particle = this.particles[p];
  54153. this._shape = this._particle._model._shape;
  54154. if (this._particle.rotationQuaternion) {
  54155. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54156. }
  54157. else {
  54158. this._yaw = this._particle.rotation.y;
  54159. this._pitch = this._particle.rotation.x;
  54160. this._roll = this._particle.rotation.z;
  54161. this._quaternionRotationYPR();
  54162. }
  54163. this._quaternionToRotationMatrix();
  54164. this._rotMatrix.invertToRef(this._invertMatrix);
  54165. for (var pt = 0; pt < this._shape.length; pt++) {
  54166. idx = index + pt * 3;
  54167. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54168. this._fixedNormal32[idx] = this._normal.x;
  54169. this._fixedNormal32[idx + 1] = this._normal.y;
  54170. this._fixedNormal32[idx + 2] = this._normal.z;
  54171. }
  54172. index = idx + 3;
  54173. }
  54174. };
  54175. //reset copy
  54176. SolidParticleSystem.prototype._resetCopy = function () {
  54177. this._copy.position.x = 0;
  54178. this._copy.position.y = 0;
  54179. this._copy.position.z = 0;
  54180. this._copy.rotation.x = 0;
  54181. this._copy.rotation.y = 0;
  54182. this._copy.rotation.z = 0;
  54183. this._copy.rotationQuaternion = null;
  54184. this._copy.scaling.x = 1.0;
  54185. this._copy.scaling.y = 1.0;
  54186. this._copy.scaling.z = 1.0;
  54187. this._copy.uvs.x = 0;
  54188. this._copy.uvs.y = 0;
  54189. this._copy.uvs.z = 1.0;
  54190. this._copy.uvs.w = 1.0;
  54191. this._copy.color = null;
  54192. this._copy.translateFromPivot = false;
  54193. };
  54194. // _meshBuilder : inserts the shape model in the global SPS mesh
  54195. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54196. var i;
  54197. var u = 0;
  54198. var c = 0;
  54199. var n = 0;
  54200. this._resetCopy();
  54201. if (options && options.positionFunction) {
  54202. options.positionFunction(this._copy, idx, idxInShape);
  54203. this._mustUnrotateFixedNormals = true;
  54204. }
  54205. if (this._copy.rotationQuaternion) {
  54206. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54207. }
  54208. else {
  54209. this._yaw = this._copy.rotation.y;
  54210. this._pitch = this._copy.rotation.x;
  54211. this._roll = this._copy.rotation.z;
  54212. this._quaternionRotationYPR();
  54213. }
  54214. this._quaternionToRotationMatrix();
  54215. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54216. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54217. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54218. if (this._copy.translateFromPivot) {
  54219. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54220. }
  54221. else {
  54222. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54223. }
  54224. for (i = 0; i < shape.length; i++) {
  54225. this._vertex.x = shape[i].x;
  54226. this._vertex.y = shape[i].y;
  54227. this._vertex.z = shape[i].z;
  54228. if (options && options.vertexFunction) {
  54229. options.vertexFunction(this._copy, this._vertex, i);
  54230. }
  54231. this._vertex.x *= this._copy.scaling.x;
  54232. this._vertex.y *= this._copy.scaling.y;
  54233. this._vertex.z *= this._copy.scaling.z;
  54234. this._vertex.x -= this._scaledPivot.x;
  54235. this._vertex.y -= this._scaledPivot.y;
  54236. this._vertex.z -= this._scaledPivot.z;
  54237. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54238. this._rotated.addInPlace(this._pivotBackTranslation);
  54239. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54240. if (meshUV) {
  54241. 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);
  54242. u += 2;
  54243. }
  54244. if (this._copy.color) {
  54245. this._color = this._copy.color;
  54246. }
  54247. else if (meshCol && meshCol[c] !== undefined) {
  54248. this._color.r = meshCol[c];
  54249. this._color.g = meshCol[c + 1];
  54250. this._color.b = meshCol[c + 2];
  54251. this._color.a = meshCol[c + 3];
  54252. }
  54253. else {
  54254. this._color.r = 1.0;
  54255. this._color.g = 1.0;
  54256. this._color.b = 1.0;
  54257. this._color.a = 1.0;
  54258. }
  54259. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54260. c += 4;
  54261. if (!this.recomputeNormals && meshNor) {
  54262. this._normal.x = meshNor[n];
  54263. this._normal.y = meshNor[n + 1];
  54264. this._normal.z = meshNor[n + 2];
  54265. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54266. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54267. n += 3;
  54268. }
  54269. }
  54270. for (i = 0; i < meshInd.length; i++) {
  54271. var current_ind = p + meshInd[i];
  54272. indices.push(current_ind);
  54273. if (current_ind > 65535) {
  54274. this._needs32Bits = true;
  54275. }
  54276. }
  54277. if (this._pickable) {
  54278. var nbfaces = meshInd.length / 3;
  54279. for (i = 0; i < nbfaces; i++) {
  54280. this.pickedParticles.push({ idx: idx, faceId: i });
  54281. }
  54282. }
  54283. if (this._depthSort) {
  54284. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54285. }
  54286. return this._copy;
  54287. };
  54288. // returns a shape array from positions array
  54289. SolidParticleSystem.prototype._posToShape = function (positions) {
  54290. var shape = [];
  54291. for (var i = 0; i < positions.length; i += 3) {
  54292. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54293. }
  54294. return shape;
  54295. };
  54296. // returns a shapeUV array from a Vector4 uvs
  54297. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54298. var shapeUV = [];
  54299. if (uvs) {
  54300. for (var i = 0; i < uvs.length; i++)
  54301. shapeUV.push(uvs[i]);
  54302. }
  54303. return shapeUV;
  54304. };
  54305. // adds a new particle object in the particles array
  54306. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54307. if (bInfo === void 0) { bInfo = null; }
  54308. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54309. this.particles.push(sp);
  54310. return sp;
  54311. };
  54312. /**
  54313. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54314. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54315. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54316. * @param nb (positive integer) the number of particles to be created from this model
  54317. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54318. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54319. * @returns the number of shapes in the system
  54320. */
  54321. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54322. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54323. var meshInd = mesh.getIndices();
  54324. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54325. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54326. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54327. var bbInfo;
  54328. if (this._particlesIntersect) {
  54329. bbInfo = mesh.getBoundingInfo();
  54330. }
  54331. var shape = this._posToShape(meshPos);
  54332. var shapeUV = this._uvsToShapeUV(meshUV);
  54333. var posfunc = options ? options.positionFunction : null;
  54334. var vtxfunc = options ? options.vertexFunction : null;
  54335. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54336. // particles
  54337. var sp;
  54338. var currentCopy;
  54339. var idx = this.nbParticles;
  54340. for (var i = 0; i < nb; i++) {
  54341. var currentPos = this._positions.length;
  54342. var currentInd = this._indices.length;
  54343. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54344. if (this._updatable) {
  54345. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54346. sp.position.copyFrom(currentCopy.position);
  54347. sp.rotation.copyFrom(currentCopy.rotation);
  54348. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54349. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54350. }
  54351. if (currentCopy.color && sp.color) {
  54352. sp.color.copyFrom(currentCopy.color);
  54353. }
  54354. sp.scaling.copyFrom(currentCopy.scaling);
  54355. sp.uvs.copyFrom(currentCopy.uvs);
  54356. }
  54357. this._index += shape.length;
  54358. idx++;
  54359. }
  54360. this.nbParticles += nb;
  54361. this._shapeCounter++;
  54362. return this._shapeCounter - 1;
  54363. };
  54364. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54365. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54366. this._resetCopy();
  54367. if (particle._model._positionFunction) {
  54368. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54369. }
  54370. if (this._copy.rotationQuaternion) {
  54371. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54372. }
  54373. else {
  54374. this._yaw = this._copy.rotation.y;
  54375. this._pitch = this._copy.rotation.x;
  54376. this._roll = this._copy.rotation.z;
  54377. this._quaternionRotationYPR();
  54378. }
  54379. this._quaternionToRotationMatrix();
  54380. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54381. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54382. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54383. if (this._copy.translateFromPivot) {
  54384. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54385. }
  54386. else {
  54387. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54388. }
  54389. this._shape = particle._model._shape;
  54390. for (var pt = 0; pt < this._shape.length; pt++) {
  54391. this._vertex.x = this._shape[pt].x;
  54392. this._vertex.y = this._shape[pt].y;
  54393. this._vertex.z = this._shape[pt].z;
  54394. if (particle._model._vertexFunction) {
  54395. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54396. }
  54397. this._vertex.x *= this._copy.scaling.x;
  54398. this._vertex.y *= this._copy.scaling.y;
  54399. this._vertex.z *= this._copy.scaling.z;
  54400. this._vertex.x -= this._scaledPivot.x;
  54401. this._vertex.y -= this._scaledPivot.y;
  54402. this._vertex.z -= this._scaledPivot.z;
  54403. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54404. this._rotated.addInPlace(this._pivotBackTranslation);
  54405. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54406. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54407. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54408. }
  54409. particle.position.x = 0.0;
  54410. particle.position.y = 0.0;
  54411. particle.position.z = 0.0;
  54412. particle.rotation.x = 0.0;
  54413. particle.rotation.y = 0.0;
  54414. particle.rotation.z = 0.0;
  54415. particle.rotationQuaternion = null;
  54416. particle.scaling.x = 1.0;
  54417. particle.scaling.y = 1.0;
  54418. particle.scaling.z = 1.0;
  54419. particle.uvs.x = 0.0;
  54420. particle.uvs.y = 0.0;
  54421. particle.uvs.z = 1.0;
  54422. particle.uvs.w = 1.0;
  54423. particle.pivot.x = 0.0;
  54424. particle.pivot.y = 0.0;
  54425. particle.pivot.z = 0.0;
  54426. particle.translateFromPivot = false;
  54427. particle.parentId = null;
  54428. };
  54429. /**
  54430. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54431. * @returns the SPS.
  54432. */
  54433. SolidParticleSystem.prototype.rebuildMesh = function () {
  54434. for (var p = 0; p < this.particles.length; p++) {
  54435. this._rebuildParticle(this.particles[p]);
  54436. }
  54437. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54438. return this;
  54439. };
  54440. /**
  54441. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54442. * This method calls `updateParticle()` for each particle of the SPS.
  54443. * For an animated SPS, it is usually called within the render loop.
  54444. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54445. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54446. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54447. * @returns the SPS.
  54448. */
  54449. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54450. if (start === void 0) { start = 0; }
  54451. if (end === void 0) { end = this.nbParticles - 1; }
  54452. if (update === void 0) { update = true; }
  54453. if (!this._updatable) {
  54454. return this;
  54455. }
  54456. // custom beforeUpdate
  54457. this.beforeUpdateParticles(start, end, update);
  54458. this._cam_axisX.x = 1.0;
  54459. this._cam_axisX.y = 0.0;
  54460. this._cam_axisX.z = 0.0;
  54461. this._cam_axisY.x = 0.0;
  54462. this._cam_axisY.y = 1.0;
  54463. this._cam_axisY.z = 0.0;
  54464. this._cam_axisZ.x = 0.0;
  54465. this._cam_axisZ.y = 0.0;
  54466. this._cam_axisZ.z = 1.0;
  54467. // cases when the World Matrix is to be computed first
  54468. if (this.billboard || this._depthSort) {
  54469. this.mesh.computeWorldMatrix(true);
  54470. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54471. }
  54472. // if the particles will always face the camera
  54473. if (this.billboard) {
  54474. // compute the camera position and un-rotate it by the current mesh rotation
  54475. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54476. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54477. this._cam_axisZ.normalize();
  54478. // same for camera up vector extracted from the cam view matrix
  54479. var view = this._camera.getViewMatrix(true);
  54480. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54481. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54482. this._cam_axisY.normalize();
  54483. this._cam_axisX.normalize();
  54484. }
  54485. // if depthSort, compute the camera global position in the mesh local system
  54486. if (this._depthSort) {
  54487. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54488. }
  54489. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54490. var idx = 0; // current position index in the global array positions32
  54491. var index = 0; // position start index in the global array positions32 of the current particle
  54492. var colidx = 0; // current color index in the global array colors32
  54493. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54494. var uvidx = 0; // current uv index in the global array uvs32
  54495. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54496. var pt = 0; // current index in the particle model shape
  54497. if (this.mesh.isFacetDataEnabled) {
  54498. this._computeBoundingBox = true;
  54499. }
  54500. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54501. if (this._computeBoundingBox) {
  54502. if (start == 0 && end == this.nbParticles - 1) {
  54503. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54504. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54505. }
  54506. else {
  54507. if (this.mesh._boundingInfo) {
  54508. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54509. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54510. }
  54511. }
  54512. }
  54513. // particle loop
  54514. index = this.particles[start]._pos;
  54515. var vpos = (index / 3) | 0;
  54516. colorIndex = vpos * 4;
  54517. uvIndex = vpos * 2;
  54518. for (var p = start; p <= end; p++) {
  54519. this._particle = this.particles[p];
  54520. this._shape = this._particle._model._shape;
  54521. this._shapeUV = this._particle._model._shapeUV;
  54522. // call to custom user function to update the particle properties
  54523. this.updateParticle(this._particle);
  54524. // camera-particle distance for depth sorting
  54525. if (this._depthSort && this._depthSortParticles) {
  54526. var dsp = this.depthSortedParticles[p];
  54527. dsp.ind = this._particle._ind;
  54528. dsp.indicesLength = this._particle._model._indicesLength;
  54529. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54530. }
  54531. // skip the computations for inactive or already invisible particles
  54532. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54533. // increment indexes for the next particle
  54534. pt = this._shape.length;
  54535. index += pt * 3;
  54536. colorIndex += pt * 4;
  54537. uvIndex += pt * 2;
  54538. continue;
  54539. }
  54540. if (this._particle.isVisible) {
  54541. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54542. this._particleHasParent = (this._particle.parentId !== null);
  54543. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54544. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54545. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54546. // particle rotation matrix
  54547. if (this.billboard) {
  54548. this._particle.rotation.x = 0.0;
  54549. this._particle.rotation.y = 0.0;
  54550. }
  54551. if (this._computeParticleRotation || this.billboard) {
  54552. if (this._particle.rotationQuaternion) {
  54553. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54554. }
  54555. else {
  54556. this._yaw = this._particle.rotation.y;
  54557. this._pitch = this._particle.rotation.x;
  54558. this._roll = this._particle.rotation.z;
  54559. this._quaternionRotationYPR();
  54560. }
  54561. this._quaternionToRotationMatrix();
  54562. }
  54563. if (this._particleHasParent) {
  54564. this._parent = this.particles[this._particle.parentId];
  54565. 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];
  54566. 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];
  54567. 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];
  54568. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54569. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54570. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54571. if (this._computeParticleRotation || this.billboard) {
  54572. 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];
  54573. 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];
  54574. 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];
  54575. 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];
  54576. 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];
  54577. 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];
  54578. 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];
  54579. 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];
  54580. 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];
  54581. }
  54582. }
  54583. else {
  54584. this._particle._globalPosition.x = this._particle.position.x;
  54585. this._particle._globalPosition.y = this._particle.position.y;
  54586. this._particle._globalPosition.z = this._particle.position.z;
  54587. if (this._computeParticleRotation || this.billboard) {
  54588. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54589. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54590. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54591. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54592. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54593. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54594. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54595. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54596. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54597. }
  54598. }
  54599. if (this._particle.translateFromPivot) {
  54600. this._pivotBackTranslation.x = 0.0;
  54601. this._pivotBackTranslation.y = 0.0;
  54602. this._pivotBackTranslation.z = 0.0;
  54603. }
  54604. else {
  54605. this._pivotBackTranslation.x = this._scaledPivot.x;
  54606. this._pivotBackTranslation.y = this._scaledPivot.y;
  54607. this._pivotBackTranslation.z = this._scaledPivot.z;
  54608. }
  54609. // particle vertex loop
  54610. for (pt = 0; pt < this._shape.length; pt++) {
  54611. idx = index + pt * 3;
  54612. colidx = colorIndex + pt * 4;
  54613. uvidx = uvIndex + pt * 2;
  54614. this._vertex.x = this._shape[pt].x;
  54615. this._vertex.y = this._shape[pt].y;
  54616. this._vertex.z = this._shape[pt].z;
  54617. if (this._computeParticleVertex) {
  54618. this.updateParticleVertex(this._particle, this._vertex, pt);
  54619. }
  54620. // positions
  54621. this._vertex.x *= this._particle.scaling.x;
  54622. this._vertex.y *= this._particle.scaling.y;
  54623. this._vertex.z *= this._particle.scaling.z;
  54624. this._vertex.x -= this._scaledPivot.x;
  54625. this._vertex.y -= this._scaledPivot.y;
  54626. this._vertex.z -= this._scaledPivot.z;
  54627. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54628. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54629. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54630. this._rotated.x += this._pivotBackTranslation.x;
  54631. this._rotated.y += this._pivotBackTranslation.y;
  54632. this._rotated.z += this._pivotBackTranslation.z;
  54633. 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;
  54634. 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;
  54635. 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;
  54636. if (this._computeBoundingBox) {
  54637. if (this._positions32[idx] < this._minimum.x) {
  54638. this._minimum.x = this._positions32[idx];
  54639. }
  54640. if (this._positions32[idx] > this._maximum.x) {
  54641. this._maximum.x = this._positions32[idx];
  54642. }
  54643. if (this._positions32[idx + 1] < this._minimum.y) {
  54644. this._minimum.y = this._positions32[idx + 1];
  54645. }
  54646. if (this._positions32[idx + 1] > this._maximum.y) {
  54647. this._maximum.y = this._positions32[idx + 1];
  54648. }
  54649. if (this._positions32[idx + 2] < this._minimum.z) {
  54650. this._minimum.z = this._positions32[idx + 2];
  54651. }
  54652. if (this._positions32[idx + 2] > this._maximum.z) {
  54653. this._maximum.z = this._positions32[idx + 2];
  54654. }
  54655. }
  54656. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54657. if (!this._computeParticleVertex) {
  54658. this._normal.x = this._fixedNormal32[idx];
  54659. this._normal.y = this._fixedNormal32[idx + 1];
  54660. this._normal.z = this._fixedNormal32[idx + 2];
  54661. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54662. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54663. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54664. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54665. 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;
  54666. 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;
  54667. }
  54668. if (this._computeParticleColor && this._particle.color) {
  54669. this._colors32[colidx] = this._particle.color.r;
  54670. this._colors32[colidx + 1] = this._particle.color.g;
  54671. this._colors32[colidx + 2] = this._particle.color.b;
  54672. this._colors32[colidx + 3] = this._particle.color.a;
  54673. }
  54674. if (this._computeParticleTexture) {
  54675. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54676. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54677. }
  54678. }
  54679. }
  54680. else {
  54681. this._particle._stillInvisible = true; // mark the particle as invisible
  54682. for (pt = 0; pt < this._shape.length; pt++) {
  54683. idx = index + pt * 3;
  54684. colidx = colorIndex + pt * 4;
  54685. uvidx = uvIndex + pt * 2;
  54686. this._positions32[idx] = 0.0;
  54687. this._positions32[idx + 1] = 0.0;
  54688. this._positions32[idx + 2] = 0.0;
  54689. this._normals32[idx] = 0.0;
  54690. this._normals32[idx + 1] = 0.0;
  54691. this._normals32[idx + 2] = 0.0;
  54692. if (this._computeParticleColor && this._particle.color) {
  54693. this._colors32[colidx] = this._particle.color.r;
  54694. this._colors32[colidx + 1] = this._particle.color.g;
  54695. this._colors32[colidx + 2] = this._particle.color.b;
  54696. this._colors32[colidx + 3] = this._particle.color.a;
  54697. }
  54698. if (this._computeParticleTexture) {
  54699. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54700. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54701. }
  54702. }
  54703. }
  54704. // if the particle intersections must be computed : update the bbInfo
  54705. if (this._particlesIntersect) {
  54706. var bInfo = this._particle._boundingInfo;
  54707. var bBox = bInfo.boundingBox;
  54708. var bSphere = bInfo.boundingSphere;
  54709. if (!this._bSphereOnly) {
  54710. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54711. for (var b = 0; b < bBox.vectors.length; b++) {
  54712. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54713. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54714. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54715. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54716. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54717. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54718. 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;
  54719. 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;
  54720. 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;
  54721. }
  54722. bBox._update(this.mesh._worldMatrix);
  54723. }
  54724. // place and scale the particle bouding sphere in the SPS local system, then update it
  54725. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54726. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54727. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54728. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54729. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54730. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54731. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54732. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54733. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54734. 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));
  54735. bSphere._update(this.mesh._worldMatrix);
  54736. }
  54737. // increment indexes for the next particle
  54738. index = idx + 3;
  54739. colorIndex = colidx + 4;
  54740. uvIndex = uvidx + 2;
  54741. }
  54742. // if the VBO must be updated
  54743. if (update) {
  54744. if (this._computeParticleColor) {
  54745. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54746. }
  54747. if (this._computeParticleTexture) {
  54748. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54749. }
  54750. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54751. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54752. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54753. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54754. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54755. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54756. for (var i = 0; i < this._normals32.length; i++) {
  54757. this._fixedNormal32[i] = this._normals32[i];
  54758. }
  54759. }
  54760. if (!this.mesh.areNormalsFrozen) {
  54761. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54762. }
  54763. }
  54764. if (this._depthSort && this._depthSortParticles) {
  54765. this.depthSortedParticles.sort(this._depthSortFunction);
  54766. var dspl = this.depthSortedParticles.length;
  54767. var sorted = 0;
  54768. var lind = 0;
  54769. var sind = 0;
  54770. var sid = 0;
  54771. for (sorted = 0; sorted < dspl; sorted++) {
  54772. lind = this.depthSortedParticles[sorted].indicesLength;
  54773. sind = this.depthSortedParticles[sorted].ind;
  54774. for (var i = 0; i < lind; i++) {
  54775. this._indices32[sid] = this._indices[sind + i];
  54776. sid++;
  54777. }
  54778. }
  54779. this.mesh.updateIndices(this._indices32);
  54780. }
  54781. }
  54782. if (this._computeBoundingBox) {
  54783. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54784. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54785. }
  54786. this.afterUpdateParticles(start, end, update);
  54787. return this;
  54788. };
  54789. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54790. this._halfroll = this._roll * 0.5;
  54791. this._halfpitch = this._pitch * 0.5;
  54792. this._halfyaw = this._yaw * 0.5;
  54793. this._sinRoll = Math.sin(this._halfroll);
  54794. this._cosRoll = Math.cos(this._halfroll);
  54795. this._sinPitch = Math.sin(this._halfpitch);
  54796. this._cosPitch = Math.cos(this._halfpitch);
  54797. this._sinYaw = Math.sin(this._halfyaw);
  54798. this._cosYaw = Math.cos(this._halfyaw);
  54799. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54800. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54801. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54802. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54803. };
  54804. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54805. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54806. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54807. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54808. this._rotMatrix.m[3] = 0;
  54809. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54810. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54811. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54812. this._rotMatrix.m[7] = 0;
  54813. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54814. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54815. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54816. this._rotMatrix.m[11] = 0;
  54817. this._rotMatrix.m[12] = 0;
  54818. this._rotMatrix.m[13] = 0;
  54819. this._rotMatrix.m[14] = 0;
  54820. this._rotMatrix.m[15] = 1.0;
  54821. };
  54822. /**
  54823. * Disposes the SPS.
  54824. */
  54825. SolidParticleSystem.prototype.dispose = function () {
  54826. this.mesh.dispose();
  54827. this.vars = null;
  54828. // drop references to internal big arrays for the GC
  54829. this._positions = null;
  54830. this._indices = null;
  54831. this._normals = null;
  54832. this._uvs = null;
  54833. this._colors = null;
  54834. this._indices32 = null;
  54835. this._positions32 = null;
  54836. this._normals32 = null;
  54837. this._fixedNormal32 = null;
  54838. this._uvs32 = null;
  54839. this._colors32 = null;
  54840. this.pickedParticles = null;
  54841. };
  54842. /**
  54843. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54844. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54845. * @returns the SPS.
  54846. */
  54847. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54848. if (!this._isVisibilityBoxLocked) {
  54849. this.mesh.refreshBoundingInfo();
  54850. }
  54851. return this;
  54852. };
  54853. /**
  54854. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54855. * @param size the size (float) of the visibility box
  54856. * note : this doesn't lock the SPS mesh bounding box.
  54857. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54858. */
  54859. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54860. var vis = size / 2;
  54861. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54862. };
  54863. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54864. /**
  54865. * Gets whether the SPS as always visible or not
  54866. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54867. */
  54868. get: function () {
  54869. return this._alwaysVisible;
  54870. },
  54871. /**
  54872. * Sets the SPS as always visible or not
  54873. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54874. */
  54875. set: function (val) {
  54876. this._alwaysVisible = val;
  54877. this.mesh.alwaysSelectAsActiveMesh = val;
  54878. },
  54879. enumerable: true,
  54880. configurable: true
  54881. });
  54882. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54883. /**
  54884. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54885. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54886. */
  54887. get: function () {
  54888. return this._isVisibilityBoxLocked;
  54889. },
  54890. /**
  54891. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54892. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54893. */
  54894. set: function (val) {
  54895. this._isVisibilityBoxLocked = val;
  54896. var boundingInfo = this.mesh.getBoundingInfo();
  54897. boundingInfo.isLocked = val;
  54898. },
  54899. enumerable: true,
  54900. configurable: true
  54901. });
  54902. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54903. /**
  54904. * Gets if `setParticles()` computes the particle rotations or not.
  54905. * Default value : true. The SPS is faster when it's set to false.
  54906. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54907. */
  54908. get: function () {
  54909. return this._computeParticleRotation;
  54910. },
  54911. /**
  54912. * Tells to `setParticles()` to compute the particle rotations or not.
  54913. * Default value : true. The SPS is faster when it's set to false.
  54914. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54915. */
  54916. set: function (val) {
  54917. this._computeParticleRotation = val;
  54918. },
  54919. enumerable: true,
  54920. configurable: true
  54921. });
  54922. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54923. /**
  54924. * Gets if `setParticles()` computes the particle colors or not.
  54925. * Default value : true. The SPS is faster when it's set to false.
  54926. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54927. */
  54928. get: function () {
  54929. return this._computeParticleColor;
  54930. },
  54931. /**
  54932. * Tells to `setParticles()` to compute the particle colors or not.
  54933. * Default value : true. The SPS is faster when it's set to false.
  54934. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54935. */
  54936. set: function (val) {
  54937. this._computeParticleColor = val;
  54938. },
  54939. enumerable: true,
  54940. configurable: true
  54941. });
  54942. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54943. /**
  54944. * Gets if `setParticles()` computes the particle textures or not.
  54945. * Default value : true. The SPS is faster when it's set to false.
  54946. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54947. */
  54948. get: function () {
  54949. return this._computeParticleTexture;
  54950. },
  54951. set: function (val) {
  54952. this._computeParticleTexture = val;
  54953. },
  54954. enumerable: true,
  54955. configurable: true
  54956. });
  54957. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54958. /**
  54959. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54960. * Default value : false. The SPS is faster when it's set to false.
  54961. * Note : the particle custom vertex positions aren't stored values.
  54962. */
  54963. get: function () {
  54964. return this._computeParticleVertex;
  54965. },
  54966. /**
  54967. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54968. * Default value : false. The SPS is faster when it's set to false.
  54969. * Note : the particle custom vertex positions aren't stored values.
  54970. */
  54971. set: function (val) {
  54972. this._computeParticleVertex = val;
  54973. },
  54974. enumerable: true,
  54975. configurable: true
  54976. });
  54977. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54978. /**
  54979. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54980. */
  54981. get: function () {
  54982. return this._computeBoundingBox;
  54983. },
  54984. /**
  54985. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54986. */
  54987. set: function (val) {
  54988. this._computeBoundingBox = val;
  54989. },
  54990. enumerable: true,
  54991. configurable: true
  54992. });
  54993. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54994. /**
  54995. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54996. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54997. * Default : `true`
  54998. */
  54999. get: function () {
  55000. return this._depthSortParticles;
  55001. },
  55002. /**
  55003. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  55004. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55005. * Default : `true`
  55006. */
  55007. set: function (val) {
  55008. this._depthSortParticles = val;
  55009. },
  55010. enumerable: true,
  55011. configurable: true
  55012. });
  55013. // =======================================================================
  55014. // Particle behavior logic
  55015. // these following methods may be overwritten by the user to fit his needs
  55016. /**
  55017. * This function does nothing. It may be overwritten to set all the particle first values.
  55018. * The SPS doesn't call this function, you may have to call it by your own.
  55019. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55020. */
  55021. SolidParticleSystem.prototype.initParticles = function () {
  55022. };
  55023. /**
  55024. * This function does nothing. It may be overwritten to recycle a particle.
  55025. * The SPS doesn't call this function, you may have to call it by your own.
  55026. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55027. * @param particle The particle to recycle
  55028. * @returns the recycled particle
  55029. */
  55030. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55031. return particle;
  55032. };
  55033. /**
  55034. * Updates a particle : this function should be overwritten by the user.
  55035. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55036. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55037. * @example : just set a particle position or velocity and recycle conditions
  55038. * @param particle The particle to update
  55039. * @returns the updated particle
  55040. */
  55041. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55042. return particle;
  55043. };
  55044. /**
  55045. * Updates a vertex of a particle : it can be overwritten by the user.
  55046. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55047. * @param particle the current particle
  55048. * @param vertex the current index of the current particle
  55049. * @param pt the index of the current vertex in the particle shape
  55050. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55051. * @example : just set a vertex particle position
  55052. * @returns the updated vertex
  55053. */
  55054. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55055. return vertex;
  55056. };
  55057. /**
  55058. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55059. * This does nothing and may be overwritten by the user.
  55060. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55061. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55062. * @param update the boolean update value actually passed to setParticles()
  55063. */
  55064. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55065. };
  55066. /**
  55067. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55068. * This will be passed three parameters.
  55069. * This does nothing and may be overwritten by the user.
  55070. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55071. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55072. * @param update the boolean update value actually passed to setParticles()
  55073. */
  55074. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55075. };
  55076. return SolidParticleSystem;
  55077. }());
  55078. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55079. })(BABYLON || (BABYLON = {}));
  55080. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55081. "use strict";
  55082. var BABYLON;
  55083. (function (BABYLON) {
  55084. var ShaderMaterial = /** @class */ (function (_super) {
  55085. __extends(ShaderMaterial, _super);
  55086. function ShaderMaterial(name, scene, shaderPath, options) {
  55087. var _this = _super.call(this, name, scene) || this;
  55088. _this._textures = {};
  55089. _this._textureArrays = {};
  55090. _this._floats = {};
  55091. _this._ints = {};
  55092. _this._floatsArrays = {};
  55093. _this._colors3 = {};
  55094. _this._colors3Arrays = {};
  55095. _this._colors4 = {};
  55096. _this._vectors2 = {};
  55097. _this._vectors3 = {};
  55098. _this._vectors4 = {};
  55099. _this._matrices = {};
  55100. _this._matrices3x3 = {};
  55101. _this._matrices2x2 = {};
  55102. _this._vectors2Arrays = {};
  55103. _this._vectors3Arrays = {};
  55104. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55105. _this._shaderPath = shaderPath;
  55106. options.needAlphaBlending = options.needAlphaBlending || false;
  55107. options.needAlphaTesting = options.needAlphaTesting || false;
  55108. options.attributes = options.attributes || ["position", "normal", "uv"];
  55109. options.uniforms = options.uniforms || ["worldViewProjection"];
  55110. options.uniformBuffers = options.uniformBuffers || [];
  55111. options.samplers = options.samplers || [];
  55112. options.defines = options.defines || [];
  55113. _this._options = options;
  55114. return _this;
  55115. }
  55116. ShaderMaterial.prototype.getClassName = function () {
  55117. return "ShaderMaterial";
  55118. };
  55119. ShaderMaterial.prototype.needAlphaBlending = function () {
  55120. return this._options.needAlphaBlending;
  55121. };
  55122. ShaderMaterial.prototype.needAlphaTesting = function () {
  55123. return this._options.needAlphaTesting;
  55124. };
  55125. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55126. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55127. this._options.uniforms.push(uniformName);
  55128. }
  55129. };
  55130. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55131. if (this._options.samplers.indexOf(name) === -1) {
  55132. this._options.samplers.push(name);
  55133. }
  55134. this._textures[name] = texture;
  55135. return this;
  55136. };
  55137. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55138. if (this._options.samplers.indexOf(name) === -1) {
  55139. this._options.samplers.push(name);
  55140. }
  55141. this._checkUniform(name);
  55142. this._textureArrays[name] = textures;
  55143. return this;
  55144. };
  55145. ShaderMaterial.prototype.setFloat = function (name, value) {
  55146. this._checkUniform(name);
  55147. this._floats[name] = value;
  55148. return this;
  55149. };
  55150. ShaderMaterial.prototype.setInt = function (name, value) {
  55151. this._checkUniform(name);
  55152. this._ints[name] = value;
  55153. return this;
  55154. };
  55155. ShaderMaterial.prototype.setFloats = function (name, value) {
  55156. this._checkUniform(name);
  55157. this._floatsArrays[name] = value;
  55158. return this;
  55159. };
  55160. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55161. this._checkUniform(name);
  55162. this._colors3[name] = value;
  55163. return this;
  55164. };
  55165. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55166. this._checkUniform(name);
  55167. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55168. color.toArray(arr, arr.length);
  55169. return arr;
  55170. }, []);
  55171. return this;
  55172. };
  55173. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55174. this._checkUniform(name);
  55175. this._colors4[name] = value;
  55176. return this;
  55177. };
  55178. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55179. this._checkUniform(name);
  55180. this._vectors2[name] = value;
  55181. return this;
  55182. };
  55183. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55184. this._checkUniform(name);
  55185. this._vectors3[name] = value;
  55186. return this;
  55187. };
  55188. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55189. this._checkUniform(name);
  55190. this._vectors4[name] = value;
  55191. return this;
  55192. };
  55193. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55194. this._checkUniform(name);
  55195. this._matrices[name] = value;
  55196. return this;
  55197. };
  55198. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55199. this._checkUniform(name);
  55200. this._matrices3x3[name] = value;
  55201. return this;
  55202. };
  55203. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55204. this._checkUniform(name);
  55205. this._matrices2x2[name] = value;
  55206. return this;
  55207. };
  55208. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55209. this._checkUniform(name);
  55210. this._vectors2Arrays[name] = value;
  55211. return this;
  55212. };
  55213. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55214. this._checkUniform(name);
  55215. this._vectors3Arrays[name] = value;
  55216. return this;
  55217. };
  55218. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55219. if (!mesh) {
  55220. return true;
  55221. }
  55222. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55223. return false;
  55224. }
  55225. return false;
  55226. };
  55227. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55228. var scene = this.getScene();
  55229. var engine = scene.getEngine();
  55230. if (!this.checkReadyOnEveryCall) {
  55231. if (this._renderId === scene.getRenderId()) {
  55232. if (this._checkCache(scene, mesh, useInstances)) {
  55233. return true;
  55234. }
  55235. }
  55236. }
  55237. // Instances
  55238. var defines = [];
  55239. var attribs = [];
  55240. var fallbacks = new BABYLON.EffectFallbacks();
  55241. if (useInstances) {
  55242. defines.push("#define INSTANCES");
  55243. }
  55244. for (var index = 0; index < this._options.defines.length; index++) {
  55245. defines.push(this._options.defines[index]);
  55246. }
  55247. for (var index = 0; index < this._options.attributes.length; index++) {
  55248. attribs.push(this._options.attributes[index]);
  55249. }
  55250. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55251. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55252. defines.push("#define VERTEXCOLOR");
  55253. }
  55254. // Bones
  55255. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55256. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55257. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55258. if (mesh.numBoneInfluencers > 4) {
  55259. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55260. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55261. }
  55262. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55263. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55264. fallbacks.addCPUSkinningFallback(0, mesh);
  55265. if (this._options.uniforms.indexOf("mBones") === -1) {
  55266. this._options.uniforms.push("mBones");
  55267. }
  55268. }
  55269. else {
  55270. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55271. }
  55272. // Textures
  55273. for (var name in this._textures) {
  55274. if (!this._textures[name].isReady()) {
  55275. return false;
  55276. }
  55277. }
  55278. // Alpha test
  55279. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55280. defines.push("#define ALPHATEST");
  55281. }
  55282. var previousEffect = this._effect;
  55283. var join = defines.join("\n");
  55284. this._effect = engine.createEffect(this._shaderPath, {
  55285. attributes: attribs,
  55286. uniformsNames: this._options.uniforms,
  55287. uniformBuffersNames: this._options.uniformBuffers,
  55288. samplers: this._options.samplers,
  55289. defines: join,
  55290. fallbacks: fallbacks,
  55291. onCompiled: this.onCompiled,
  55292. onError: this.onError
  55293. }, engine);
  55294. if (!this._effect.isReady()) {
  55295. return false;
  55296. }
  55297. if (previousEffect !== this._effect) {
  55298. scene.resetCachedMaterial();
  55299. }
  55300. this._renderId = scene.getRenderId();
  55301. return true;
  55302. };
  55303. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55304. var scene = this.getScene();
  55305. if (!this._effect) {
  55306. return;
  55307. }
  55308. if (this._options.uniforms.indexOf("world") !== -1) {
  55309. this._effect.setMatrix("world", world);
  55310. }
  55311. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55312. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55313. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55314. }
  55315. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55316. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55317. }
  55318. };
  55319. ShaderMaterial.prototype.bind = function (world, mesh) {
  55320. // Std values
  55321. this.bindOnlyWorldMatrix(world);
  55322. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55323. if (this._options.uniforms.indexOf("view") !== -1) {
  55324. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55325. }
  55326. if (this._options.uniforms.indexOf("projection") !== -1) {
  55327. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55328. }
  55329. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55330. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55331. }
  55332. // Bones
  55333. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55334. var name;
  55335. // Texture
  55336. for (name in this._textures) {
  55337. this._effect.setTexture(name, this._textures[name]);
  55338. }
  55339. // Texture arrays
  55340. for (name in this._textureArrays) {
  55341. this._effect.setTextureArray(name, this._textureArrays[name]);
  55342. }
  55343. // Int
  55344. for (name in this._ints) {
  55345. this._effect.setInt(name, this._ints[name]);
  55346. }
  55347. // Float
  55348. for (name in this._floats) {
  55349. this._effect.setFloat(name, this._floats[name]);
  55350. }
  55351. // Floats
  55352. for (name in this._floatsArrays) {
  55353. this._effect.setArray(name, this._floatsArrays[name]);
  55354. }
  55355. // Color3
  55356. for (name in this._colors3) {
  55357. this._effect.setColor3(name, this._colors3[name]);
  55358. }
  55359. for (name in this._colors3Arrays) {
  55360. this._effect.setArray3(name, this._colors3Arrays[name]);
  55361. }
  55362. // Color4
  55363. for (name in this._colors4) {
  55364. var color = this._colors4[name];
  55365. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55366. }
  55367. // Vector2
  55368. for (name in this._vectors2) {
  55369. this._effect.setVector2(name, this._vectors2[name]);
  55370. }
  55371. // Vector3
  55372. for (name in this._vectors3) {
  55373. this._effect.setVector3(name, this._vectors3[name]);
  55374. }
  55375. // Vector4
  55376. for (name in this._vectors4) {
  55377. this._effect.setVector4(name, this._vectors4[name]);
  55378. }
  55379. // Matrix
  55380. for (name in this._matrices) {
  55381. this._effect.setMatrix(name, this._matrices[name]);
  55382. }
  55383. // Matrix 3x3
  55384. for (name in this._matrices3x3) {
  55385. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55386. }
  55387. // Matrix 2x2
  55388. for (name in this._matrices2x2) {
  55389. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55390. }
  55391. // Vector2Array
  55392. for (name in this._vectors2Arrays) {
  55393. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55394. }
  55395. // Vector3Array
  55396. for (name in this._vectors3Arrays) {
  55397. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55398. }
  55399. }
  55400. this._afterBind(mesh);
  55401. };
  55402. ShaderMaterial.prototype.getActiveTextures = function () {
  55403. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55404. for (var name in this._textures) {
  55405. activeTextures.push(this._textures[name]);
  55406. }
  55407. for (var name in this._textureArrays) {
  55408. var array = this._textureArrays[name];
  55409. for (var index = 0; index < array.length; index++) {
  55410. activeTextures.push(array[index]);
  55411. }
  55412. }
  55413. return activeTextures;
  55414. };
  55415. ShaderMaterial.prototype.hasTexture = function (texture) {
  55416. if (_super.prototype.hasTexture.call(this, texture)) {
  55417. return true;
  55418. }
  55419. for (var name in this._textures) {
  55420. if (this._textures[name] === texture) {
  55421. return true;
  55422. }
  55423. }
  55424. for (var name in this._textureArrays) {
  55425. var array = this._textureArrays[name];
  55426. for (var index = 0; index < array.length; index++) {
  55427. if (array[index] === texture) {
  55428. return true;
  55429. }
  55430. }
  55431. }
  55432. return false;
  55433. };
  55434. ShaderMaterial.prototype.clone = function (name) {
  55435. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55436. return newShaderMaterial;
  55437. };
  55438. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55439. if (forceDisposeTextures) {
  55440. var name;
  55441. for (name in this._textures) {
  55442. this._textures[name].dispose();
  55443. }
  55444. for (name in this._textureArrays) {
  55445. var array = this._textureArrays[name];
  55446. for (var index = 0; index < array.length; index++) {
  55447. array[index].dispose();
  55448. }
  55449. }
  55450. }
  55451. this._textures = {};
  55452. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55453. };
  55454. ShaderMaterial.prototype.serialize = function () {
  55455. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55456. serializationObject.customType = "BABYLON.ShaderMaterial";
  55457. serializationObject.options = this._options;
  55458. serializationObject.shaderPath = this._shaderPath;
  55459. var name;
  55460. // Texture
  55461. serializationObject.textures = {};
  55462. for (name in this._textures) {
  55463. serializationObject.textures[name] = this._textures[name].serialize();
  55464. }
  55465. // Texture arrays
  55466. serializationObject.textureArrays = {};
  55467. for (name in this._textureArrays) {
  55468. serializationObject.textureArrays[name] = [];
  55469. var array = this._textureArrays[name];
  55470. for (var index = 0; index < array.length; index++) {
  55471. serializationObject.textureArrays[name].push(array[index].serialize());
  55472. }
  55473. }
  55474. // Float
  55475. serializationObject.floats = {};
  55476. for (name in this._floats) {
  55477. serializationObject.floats[name] = this._floats[name];
  55478. }
  55479. // Float s
  55480. serializationObject.FloatArrays = {};
  55481. for (name in this._floatsArrays) {
  55482. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55483. }
  55484. // Color3
  55485. serializationObject.colors3 = {};
  55486. for (name in this._colors3) {
  55487. serializationObject.colors3[name] = this._colors3[name].asArray();
  55488. }
  55489. // Color3 array
  55490. serializationObject.colors3Arrays = {};
  55491. for (name in this._colors3Arrays) {
  55492. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55493. }
  55494. // Color4
  55495. serializationObject.colors4 = {};
  55496. for (name in this._colors4) {
  55497. serializationObject.colors4[name] = this._colors4[name].asArray();
  55498. }
  55499. // Vector2
  55500. serializationObject.vectors2 = {};
  55501. for (name in this._vectors2) {
  55502. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55503. }
  55504. // Vector3
  55505. serializationObject.vectors3 = {};
  55506. for (name in this._vectors3) {
  55507. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55508. }
  55509. // Vector4
  55510. serializationObject.vectors4 = {};
  55511. for (name in this._vectors4) {
  55512. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55513. }
  55514. // Matrix
  55515. serializationObject.matrices = {};
  55516. for (name in this._matrices) {
  55517. serializationObject.matrices[name] = this._matrices[name].asArray();
  55518. }
  55519. // Matrix 3x3
  55520. serializationObject.matrices3x3 = {};
  55521. for (name in this._matrices3x3) {
  55522. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55523. }
  55524. // Matrix 2x2
  55525. serializationObject.matrices2x2 = {};
  55526. for (name in this._matrices2x2) {
  55527. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55528. }
  55529. // Vector2Array
  55530. serializationObject.vectors2Arrays = {};
  55531. for (name in this._vectors2Arrays) {
  55532. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55533. }
  55534. // Vector3Array
  55535. serializationObject.vectors3Arrays = {};
  55536. for (name in this._vectors3Arrays) {
  55537. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55538. }
  55539. return serializationObject;
  55540. };
  55541. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55542. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55543. var name;
  55544. // Texture
  55545. for (name in source.textures) {
  55546. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55547. }
  55548. // Texture arrays
  55549. for (name in source.textureArrays) {
  55550. var array = source.textureArrays[name];
  55551. var textureArray = new Array();
  55552. for (var index = 0; index < array.length; index++) {
  55553. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55554. }
  55555. material.setTextureArray(name, textureArray);
  55556. }
  55557. // Float
  55558. for (name in source.floats) {
  55559. material.setFloat(name, source.floats[name]);
  55560. }
  55561. // Float s
  55562. for (name in source.floatsArrays) {
  55563. material.setFloats(name, source.floatsArrays[name]);
  55564. }
  55565. // Color3
  55566. for (name in source.colors3) {
  55567. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55568. }
  55569. // Color3 arrays
  55570. for (name in source.colors3Arrays) {
  55571. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55572. if (i % 3 === 0) {
  55573. arr.push([num]);
  55574. }
  55575. else {
  55576. arr[arr.length - 1].push(num);
  55577. }
  55578. return arr;
  55579. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55580. material.setColor3Array(name, colors);
  55581. }
  55582. // Color4
  55583. for (name in source.colors4) {
  55584. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55585. }
  55586. // Vector2
  55587. for (name in source.vectors2) {
  55588. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55589. }
  55590. // Vector3
  55591. for (name in source.vectors3) {
  55592. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55593. }
  55594. // Vector4
  55595. for (name in source.vectors4) {
  55596. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55597. }
  55598. // Matrix
  55599. for (name in source.matrices) {
  55600. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55601. }
  55602. // Matrix 3x3
  55603. for (name in source.matrices3x3) {
  55604. material.setMatrix3x3(name, source.matrices3x3[name]);
  55605. }
  55606. // Matrix 2x2
  55607. for (name in source.matrices2x2) {
  55608. material.setMatrix2x2(name, source.matrices2x2[name]);
  55609. }
  55610. // Vector2Array
  55611. for (name in source.vectors2Arrays) {
  55612. material.setArray2(name, source.vectors2Arrays[name]);
  55613. }
  55614. // Vector3Array
  55615. for (name in source.vectors3Arrays) {
  55616. material.setArray3(name, source.vectors3Arrays[name]);
  55617. }
  55618. return material;
  55619. };
  55620. return ShaderMaterial;
  55621. }(BABYLON.Material));
  55622. BABYLON.ShaderMaterial = ShaderMaterial;
  55623. })(BABYLON || (BABYLON = {}));
  55624. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55625. "use strict";
  55626. var BABYLON;
  55627. (function (BABYLON) {
  55628. var GroundMesh = /** @class */ (function (_super) {
  55629. __extends(GroundMesh, _super);
  55630. function GroundMesh(name, scene) {
  55631. var _this = _super.call(this, name, scene) || this;
  55632. _this.generateOctree = false;
  55633. return _this;
  55634. }
  55635. GroundMesh.prototype.getClassName = function () {
  55636. return "GroundMesh";
  55637. };
  55638. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55639. get: function () {
  55640. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55641. },
  55642. enumerable: true,
  55643. configurable: true
  55644. });
  55645. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55646. get: function () {
  55647. return this._subdivisionsX;
  55648. },
  55649. enumerable: true,
  55650. configurable: true
  55651. });
  55652. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55653. get: function () {
  55654. return this._subdivisionsY;
  55655. },
  55656. enumerable: true,
  55657. configurable: true
  55658. });
  55659. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55660. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55661. this._subdivisionsX = chunksCount;
  55662. this._subdivisionsY = chunksCount;
  55663. this.subdivide(chunksCount);
  55664. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55665. };
  55666. /**
  55667. * Returns a height (y) value in the Worl system :
  55668. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55669. * Returns the ground y position if (x, z) are outside the ground surface.
  55670. */
  55671. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55672. var world = this.getWorldMatrix();
  55673. var invMat = BABYLON.Tmp.Matrix[5];
  55674. world.invertToRef(invMat);
  55675. var tmpVect = BABYLON.Tmp.Vector3[8];
  55676. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55677. x = tmpVect.x;
  55678. z = tmpVect.z;
  55679. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55680. return this.position.y;
  55681. }
  55682. if (!this._heightQuads || this._heightQuads.length == 0) {
  55683. this._initHeightQuads();
  55684. this._computeHeightQuads();
  55685. }
  55686. var facet = this._getFacetAt(x, z);
  55687. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55688. // return y in the World system
  55689. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55690. return tmpVect.y;
  55691. };
  55692. /**
  55693. * Returns a normalized vector (Vector3) orthogonal to the ground
  55694. * at the ground coordinates (x, z) expressed in the World system.
  55695. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55696. */
  55697. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55698. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55699. this.getNormalAtCoordinatesToRef(x, z, normal);
  55700. return normal;
  55701. };
  55702. /**
  55703. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55704. * at the ground coordinates (x, z) expressed in the World system.
  55705. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55706. * Returns the GroundMesh.
  55707. */
  55708. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55709. var world = this.getWorldMatrix();
  55710. var tmpMat = BABYLON.Tmp.Matrix[5];
  55711. world.invertToRef(tmpMat);
  55712. var tmpVect = BABYLON.Tmp.Vector3[8];
  55713. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55714. x = tmpVect.x;
  55715. z = tmpVect.z;
  55716. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55717. return this;
  55718. }
  55719. if (!this._heightQuads || this._heightQuads.length == 0) {
  55720. this._initHeightQuads();
  55721. this._computeHeightQuads();
  55722. }
  55723. var facet = this._getFacetAt(x, z);
  55724. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55725. return this;
  55726. };
  55727. /**
  55728. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55729. * if the ground has been updated.
  55730. * This can be used in the render loop.
  55731. * Returns the GroundMesh.
  55732. */
  55733. GroundMesh.prototype.updateCoordinateHeights = function () {
  55734. if (!this._heightQuads || this._heightQuads.length == 0) {
  55735. this._initHeightQuads();
  55736. }
  55737. this._computeHeightQuads();
  55738. return this;
  55739. };
  55740. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55741. GroundMesh.prototype._getFacetAt = function (x, z) {
  55742. // retrieve col and row from x, z coordinates in the ground local system
  55743. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55744. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55745. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55746. var facet;
  55747. if (z < quad.slope.x * x + quad.slope.y) {
  55748. facet = quad.facet1;
  55749. }
  55750. else {
  55751. facet = quad.facet2;
  55752. }
  55753. return facet;
  55754. };
  55755. // Creates and populates the heightMap array with "facet" elements :
  55756. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55757. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55758. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55759. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55760. // Returns the GroundMesh.
  55761. GroundMesh.prototype._initHeightQuads = function () {
  55762. var subdivisionsX = this._subdivisionsX;
  55763. var subdivisionsY = this._subdivisionsY;
  55764. this._heightQuads = new Array();
  55765. for (var row = 0; row < subdivisionsY; row++) {
  55766. for (var col = 0; col < subdivisionsX; col++) {
  55767. 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) };
  55768. this._heightQuads[row * subdivisionsX + col] = quad;
  55769. }
  55770. }
  55771. return this;
  55772. };
  55773. // Compute each quad element values and update the the heightMap array :
  55774. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55775. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55776. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55777. // Returns the GroundMesh.
  55778. GroundMesh.prototype._computeHeightQuads = function () {
  55779. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55780. if (!positions) {
  55781. return this;
  55782. }
  55783. var v1 = BABYLON.Tmp.Vector3[3];
  55784. var v2 = BABYLON.Tmp.Vector3[2];
  55785. var v3 = BABYLON.Tmp.Vector3[1];
  55786. var v4 = BABYLON.Tmp.Vector3[0];
  55787. var v1v2 = BABYLON.Tmp.Vector3[4];
  55788. var v1v3 = BABYLON.Tmp.Vector3[5];
  55789. var v1v4 = BABYLON.Tmp.Vector3[6];
  55790. var norm1 = BABYLON.Tmp.Vector3[7];
  55791. var norm2 = BABYLON.Tmp.Vector3[8];
  55792. var i = 0;
  55793. var j = 0;
  55794. var k = 0;
  55795. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55796. var h = 0;
  55797. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55798. var d2 = 0;
  55799. var subdivisionsX = this._subdivisionsX;
  55800. var subdivisionsY = this._subdivisionsY;
  55801. for (var row = 0; row < subdivisionsY; row++) {
  55802. for (var col = 0; col < subdivisionsX; col++) {
  55803. i = col * 3;
  55804. j = row * (subdivisionsX + 1) * 3;
  55805. k = (row + 1) * (subdivisionsX + 1) * 3;
  55806. v1.x = positions[j + i];
  55807. v1.y = positions[j + i + 1];
  55808. v1.z = positions[j + i + 2];
  55809. v2.x = positions[j + i + 3];
  55810. v2.y = positions[j + i + 4];
  55811. v2.z = positions[j + i + 5];
  55812. v3.x = positions[k + i];
  55813. v3.y = positions[k + i + 1];
  55814. v3.z = positions[k + i + 2];
  55815. v4.x = positions[k + i + 3];
  55816. v4.y = positions[k + i + 4];
  55817. v4.z = positions[k + i + 5];
  55818. // 2D slope V1V4
  55819. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55820. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55821. // facet equations :
  55822. // we compute each facet normal vector
  55823. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55824. // we compute the value d by applying the equation to v1 which belongs to the plane
  55825. // then we store the facet equation in a Vector4
  55826. v2.subtractToRef(v1, v1v2);
  55827. v3.subtractToRef(v1, v1v3);
  55828. v4.subtractToRef(v1, v1v4);
  55829. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55830. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55831. norm1.normalize();
  55832. norm2.normalize();
  55833. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55834. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55835. var quad = this._heightQuads[row * subdivisionsX + col];
  55836. quad.slope.copyFromFloats(cd, h);
  55837. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55838. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55839. }
  55840. }
  55841. return this;
  55842. };
  55843. GroundMesh.prototype.serialize = function (serializationObject) {
  55844. _super.prototype.serialize.call(this, serializationObject);
  55845. serializationObject.subdivisionsX = this._subdivisionsX;
  55846. serializationObject.subdivisionsY = this._subdivisionsY;
  55847. serializationObject.minX = this._minX;
  55848. serializationObject.maxX = this._maxX;
  55849. serializationObject.minZ = this._minZ;
  55850. serializationObject.maxZ = this._maxZ;
  55851. serializationObject.width = this._width;
  55852. serializationObject.height = this._height;
  55853. };
  55854. GroundMesh.Parse = function (parsedMesh, scene) {
  55855. var result = new GroundMesh(parsedMesh.name, scene);
  55856. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55857. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55858. result._minX = parsedMesh.minX;
  55859. result._maxX = parsedMesh.maxX;
  55860. result._minZ = parsedMesh.minZ;
  55861. result._maxZ = parsedMesh.maxZ;
  55862. result._width = parsedMesh.width;
  55863. result._height = parsedMesh.height;
  55864. return result;
  55865. };
  55866. return GroundMesh;
  55867. }(BABYLON.Mesh));
  55868. BABYLON.GroundMesh = GroundMesh;
  55869. })(BABYLON || (BABYLON = {}));
  55870. //# sourceMappingURL=babylon.groundMesh.js.map
  55871. "use strict";
  55872. var BABYLON;
  55873. (function (BABYLON) {
  55874. /**
  55875. * Creates an instance based on a source mesh.
  55876. */
  55877. var InstancedMesh = /** @class */ (function (_super) {
  55878. __extends(InstancedMesh, _super);
  55879. function InstancedMesh(name, source) {
  55880. var _this = _super.call(this, name, source.getScene()) || this;
  55881. source.instances.push(_this);
  55882. _this._sourceMesh = source;
  55883. _this.position.copyFrom(source.position);
  55884. _this.rotation.copyFrom(source.rotation);
  55885. _this.scaling.copyFrom(source.scaling);
  55886. if (source.rotationQuaternion) {
  55887. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55888. }
  55889. _this.infiniteDistance = source.infiniteDistance;
  55890. _this.setPivotMatrix(source.getPivotMatrix());
  55891. _this.refreshBoundingInfo();
  55892. _this._syncSubMeshes();
  55893. return _this;
  55894. }
  55895. /**
  55896. * Returns the string "InstancedMesh".
  55897. */
  55898. InstancedMesh.prototype.getClassName = function () {
  55899. return "InstancedMesh";
  55900. };
  55901. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55902. // Methods
  55903. get: function () {
  55904. return this._sourceMesh.receiveShadows;
  55905. },
  55906. enumerable: true,
  55907. configurable: true
  55908. });
  55909. Object.defineProperty(InstancedMesh.prototype, "material", {
  55910. get: function () {
  55911. return this._sourceMesh.material;
  55912. },
  55913. enumerable: true,
  55914. configurable: true
  55915. });
  55916. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55917. get: function () {
  55918. return this._sourceMesh.visibility;
  55919. },
  55920. enumerable: true,
  55921. configurable: true
  55922. });
  55923. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55924. get: function () {
  55925. return this._sourceMesh.skeleton;
  55926. },
  55927. enumerable: true,
  55928. configurable: true
  55929. });
  55930. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55931. get: function () {
  55932. return this._sourceMesh.renderingGroupId;
  55933. },
  55934. set: function (value) {
  55935. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55936. return;
  55937. }
  55938. //no-op with warning
  55939. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55940. },
  55941. enumerable: true,
  55942. configurable: true
  55943. });
  55944. /**
  55945. * Returns the total number of vertices (integer).
  55946. */
  55947. InstancedMesh.prototype.getTotalVertices = function () {
  55948. return this._sourceMesh.getTotalVertices();
  55949. };
  55950. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55951. get: function () {
  55952. return this._sourceMesh;
  55953. },
  55954. enumerable: true,
  55955. configurable: true
  55956. });
  55957. /**
  55958. * Is this node ready to be used/rendered
  55959. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55960. * @return {boolean} is it ready
  55961. */
  55962. InstancedMesh.prototype.isReady = function (completeCheck) {
  55963. if (completeCheck === void 0) { completeCheck = false; }
  55964. return this._sourceMesh.isReady(completeCheck, true);
  55965. };
  55966. /**
  55967. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55968. */
  55969. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55970. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55971. };
  55972. /**
  55973. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55974. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55975. * The `data` are either a numeric array either a Float32Array.
  55976. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55977. * 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).
  55978. * Note that a new underlying VertexBuffer object is created each call.
  55979. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55980. *
  55981. * Possible `kind` values :
  55982. * - BABYLON.VertexBuffer.PositionKind
  55983. * - BABYLON.VertexBuffer.UVKind
  55984. * - BABYLON.VertexBuffer.UV2Kind
  55985. * - BABYLON.VertexBuffer.UV3Kind
  55986. * - BABYLON.VertexBuffer.UV4Kind
  55987. * - BABYLON.VertexBuffer.UV5Kind
  55988. * - BABYLON.VertexBuffer.UV6Kind
  55989. * - BABYLON.VertexBuffer.ColorKind
  55990. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55991. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55992. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55993. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55994. *
  55995. * Returns the Mesh.
  55996. */
  55997. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55998. if (this.sourceMesh) {
  55999. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  56000. }
  56001. return this.sourceMesh;
  56002. };
  56003. /**
  56004. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  56005. * If the mesh has no geometry, it is simply returned as it is.
  56006. * The `data` are either a numeric array either a Float32Array.
  56007. * No new underlying VertexBuffer object is created.
  56008. * 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.
  56009. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  56010. *
  56011. * Possible `kind` values :
  56012. * - BABYLON.VertexBuffer.PositionKind
  56013. * - BABYLON.VertexBuffer.UVKind
  56014. * - BABYLON.VertexBuffer.UV2Kind
  56015. * - BABYLON.VertexBuffer.UV3Kind
  56016. * - BABYLON.VertexBuffer.UV4Kind
  56017. * - BABYLON.VertexBuffer.UV5Kind
  56018. * - BABYLON.VertexBuffer.UV6Kind
  56019. * - BABYLON.VertexBuffer.ColorKind
  56020. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56021. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56022. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56023. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56024. *
  56025. * Returns the Mesh.
  56026. */
  56027. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56028. if (this.sourceMesh) {
  56029. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56030. }
  56031. return this.sourceMesh;
  56032. };
  56033. /**
  56034. * Sets the mesh indices.
  56035. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56036. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56037. * This method creates a new index buffer each call.
  56038. * Returns the Mesh.
  56039. */
  56040. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56041. if (totalVertices === void 0) { totalVertices = null; }
  56042. if (this.sourceMesh) {
  56043. this.sourceMesh.setIndices(indices, totalVertices);
  56044. }
  56045. return this.sourceMesh;
  56046. };
  56047. /**
  56048. * Boolean : True if the mesh owns the requested kind of data.
  56049. */
  56050. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56051. return this._sourceMesh.isVerticesDataPresent(kind);
  56052. };
  56053. /**
  56054. * Returns an array of indices (IndicesArray).
  56055. */
  56056. InstancedMesh.prototype.getIndices = function () {
  56057. return this._sourceMesh.getIndices();
  56058. };
  56059. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56060. get: function () {
  56061. return this._sourceMesh._positions;
  56062. },
  56063. enumerable: true,
  56064. configurable: true
  56065. });
  56066. /**
  56067. * Sets a new updated BoundingInfo to the mesh.
  56068. * Returns the mesh.
  56069. */
  56070. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56071. var meshBB = this._sourceMesh.getBoundingInfo();
  56072. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56073. this._updateBoundingInfo();
  56074. return this;
  56075. };
  56076. InstancedMesh.prototype._preActivate = function () {
  56077. if (this._currentLOD) {
  56078. this._currentLOD._preActivate();
  56079. }
  56080. return this;
  56081. };
  56082. InstancedMesh.prototype._activate = function (renderId) {
  56083. if (this._currentLOD) {
  56084. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56085. }
  56086. return this;
  56087. };
  56088. /**
  56089. * Returns the current associated LOD AbstractMesh.
  56090. */
  56091. InstancedMesh.prototype.getLOD = function (camera) {
  56092. if (!camera) {
  56093. return this;
  56094. }
  56095. var boundingInfo = this.getBoundingInfo();
  56096. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56097. if (this._currentLOD === this.sourceMesh) {
  56098. return this;
  56099. }
  56100. return this._currentLOD;
  56101. };
  56102. InstancedMesh.prototype._syncSubMeshes = function () {
  56103. this.releaseSubMeshes();
  56104. if (this._sourceMesh.subMeshes) {
  56105. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56106. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56107. }
  56108. }
  56109. return this;
  56110. };
  56111. InstancedMesh.prototype._generatePointsArray = function () {
  56112. return this._sourceMesh._generatePointsArray();
  56113. };
  56114. /**
  56115. * Creates a new InstancedMesh from the current mesh.
  56116. * - name (string) : the cloned mesh name
  56117. * - newParent (optional Node) : the optional Node to parent the clone to.
  56118. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56119. *
  56120. * Returns the clone.
  56121. */
  56122. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56123. var result = this._sourceMesh.createInstance(name);
  56124. // Deep copy
  56125. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56126. // Bounding info
  56127. this.refreshBoundingInfo();
  56128. // Parent
  56129. if (newParent) {
  56130. result.parent = newParent;
  56131. }
  56132. if (!doNotCloneChildren) {
  56133. // Children
  56134. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56135. var mesh = this.getScene().meshes[index];
  56136. if (mesh.parent === this) {
  56137. mesh.clone(mesh.name, result);
  56138. }
  56139. }
  56140. }
  56141. result.computeWorldMatrix(true);
  56142. return result;
  56143. };
  56144. /**
  56145. * Disposes the InstancedMesh.
  56146. * Returns nothing.
  56147. */
  56148. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56149. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56150. // Remove from mesh
  56151. var index = this._sourceMesh.instances.indexOf(this);
  56152. this._sourceMesh.instances.splice(index, 1);
  56153. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56154. };
  56155. return InstancedMesh;
  56156. }(BABYLON.AbstractMesh));
  56157. BABYLON.InstancedMesh = InstancedMesh;
  56158. })(BABYLON || (BABYLON = {}));
  56159. //# sourceMappingURL=babylon.instancedMesh.js.map
  56160. "use strict";
  56161. var BABYLON;
  56162. (function (BABYLON) {
  56163. var LinesMesh = /** @class */ (function (_super) {
  56164. __extends(LinesMesh, _super);
  56165. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56166. if (scene === void 0) { scene = null; }
  56167. if (parent === void 0) { parent = null; }
  56168. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56169. _this.useVertexColor = useVertexColor;
  56170. _this.useVertexAlpha = useVertexAlpha;
  56171. _this.color = new BABYLON.Color3(1, 1, 1);
  56172. _this.alpha = 1;
  56173. if (source) {
  56174. _this.color = source.color.clone();
  56175. _this.alpha = source.alpha;
  56176. _this.useVertexColor = source.useVertexColor;
  56177. _this.useVertexAlpha = source.useVertexAlpha;
  56178. }
  56179. _this._intersectionThreshold = 0.1;
  56180. var defines = [];
  56181. var options = {
  56182. attributes: [BABYLON.VertexBuffer.PositionKind],
  56183. uniforms: ["world", "viewProjection"],
  56184. needAlphaBlending: true,
  56185. defines: defines
  56186. };
  56187. if (useVertexAlpha === false) {
  56188. options.needAlphaBlending = false;
  56189. }
  56190. if (!useVertexColor) {
  56191. options.uniforms.push("color");
  56192. }
  56193. else {
  56194. options.defines.push("#define VERTEXCOLOR");
  56195. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56196. }
  56197. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56198. return _this;
  56199. }
  56200. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56201. /**
  56202. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56203. * This margin is expressed in world space coordinates, so its value may vary.
  56204. * Default value is 0.1
  56205. * @returns the intersection Threshold value.
  56206. */
  56207. get: function () {
  56208. return this._intersectionThreshold;
  56209. },
  56210. /**
  56211. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56212. * This margin is expressed in world space coordinates, so its value may vary.
  56213. * @param value the new threshold to apply
  56214. */
  56215. set: function (value) {
  56216. if (this._intersectionThreshold === value) {
  56217. return;
  56218. }
  56219. this._intersectionThreshold = value;
  56220. if (this.geometry) {
  56221. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56222. }
  56223. },
  56224. enumerable: true,
  56225. configurable: true
  56226. });
  56227. /**
  56228. * Returns the string "LineMesh"
  56229. */
  56230. LinesMesh.prototype.getClassName = function () {
  56231. return "LinesMesh";
  56232. };
  56233. Object.defineProperty(LinesMesh.prototype, "material", {
  56234. get: function () {
  56235. return this._colorShader;
  56236. },
  56237. set: function (value) {
  56238. // Do nothing
  56239. },
  56240. enumerable: true,
  56241. configurable: true
  56242. });
  56243. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56244. get: function () {
  56245. return false;
  56246. },
  56247. enumerable: true,
  56248. configurable: true
  56249. });
  56250. LinesMesh.prototype.createInstance = function (name) {
  56251. throw new Error("LinesMeshes do not support createInstance.");
  56252. };
  56253. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56254. if (!this._geometry) {
  56255. return this;
  56256. }
  56257. // VBOs
  56258. this._geometry._bind(this._colorShader.getEffect());
  56259. // Color
  56260. if (!this.useVertexColor) {
  56261. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56262. }
  56263. return this;
  56264. };
  56265. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56266. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56267. return this;
  56268. }
  56269. var engine = this.getScene().getEngine();
  56270. // Draw order
  56271. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56272. return this;
  56273. };
  56274. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56275. this._colorShader.dispose();
  56276. _super.prototype.dispose.call(this, doNotRecurse);
  56277. };
  56278. /**
  56279. * Returns a new LineMesh object cloned from the current one.
  56280. */
  56281. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56282. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56283. };
  56284. return LinesMesh;
  56285. }(BABYLON.Mesh));
  56286. BABYLON.LinesMesh = LinesMesh;
  56287. })(BABYLON || (BABYLON = {}));
  56288. //# sourceMappingURL=babylon.linesMesh.js.map
  56289. "use strict";
  56290. var BABYLON;
  56291. (function (BABYLON) {
  56292. var MeshBuilder = /** @class */ (function () {
  56293. function MeshBuilder() {
  56294. }
  56295. MeshBuilder.updateSideOrientation = function (orientation) {
  56296. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56297. return BABYLON.Mesh.DOUBLESIDE;
  56298. }
  56299. if (orientation === undefined || orientation === null) {
  56300. return BABYLON.Mesh.FRONTSIDE;
  56301. }
  56302. return orientation;
  56303. };
  56304. /**
  56305. * Creates a box mesh.
  56306. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56307. * The parameter `size` sets the size (float) of each box side (default 1).
  56308. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56309. * 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).
  56310. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56312. * 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).
  56313. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56315. */
  56316. MeshBuilder.CreateBox = function (name, options, scene) {
  56317. if (scene === void 0) { scene = null; }
  56318. var box = new BABYLON.Mesh(name, scene);
  56319. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56320. box._originalBuilderSideOrientation = options.sideOrientation;
  56321. var vertexData = BABYLON.VertexData.CreateBox(options);
  56322. vertexData.applyToMesh(box, options.updatable);
  56323. return box;
  56324. };
  56325. /**
  56326. * Creates a sphere mesh.
  56327. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56328. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56329. * 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`).
  56330. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56331. * 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
  56332. * 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).
  56333. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56334. * 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).
  56335. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56336. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56337. */
  56338. MeshBuilder.CreateSphere = function (name, options, scene) {
  56339. var sphere = new BABYLON.Mesh(name, scene);
  56340. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56341. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56342. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56343. vertexData.applyToMesh(sphere, options.updatable);
  56344. return sphere;
  56345. };
  56346. /**
  56347. * Creates a plane polygonal mesh. By default, this is a disc.
  56348. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56349. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56350. * 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.
  56351. * 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
  56352. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56353. * 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).
  56354. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56355. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56356. */
  56357. MeshBuilder.CreateDisc = function (name, options, scene) {
  56358. if (scene === void 0) { scene = null; }
  56359. var disc = new BABYLON.Mesh(name, scene);
  56360. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56361. disc._originalBuilderSideOrientation = options.sideOrientation;
  56362. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56363. vertexData.applyToMesh(disc, options.updatable);
  56364. return disc;
  56365. };
  56366. /**
  56367. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56368. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56369. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56370. * 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`).
  56371. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56372. * 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.
  56373. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56374. * 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).
  56375. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56376. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56377. */
  56378. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56379. var sphere = new BABYLON.Mesh(name, scene);
  56380. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56381. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56382. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56383. vertexData.applyToMesh(sphere, options.updatable);
  56384. return sphere;
  56385. };
  56386. ;
  56387. /**
  56388. * Creates a ribbon mesh.
  56389. * 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.
  56390. *
  56391. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56392. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56393. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56394. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56395. * 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.
  56396. * 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.
  56397. * 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
  56398. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56399. * 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).
  56400. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56401. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56402. * 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.
  56403. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56404. * 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
  56405. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56406. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56407. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56408. */
  56409. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56410. if (scene === void 0) { scene = null; }
  56411. var pathArray = options.pathArray;
  56412. var closeArray = options.closeArray;
  56413. var closePath = options.closePath;
  56414. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56415. var instance = options.instance;
  56416. var updatable = options.updatable;
  56417. if (instance) {
  56418. // positionFunction : ribbon case
  56419. // only pathArray and sideOrientation parameters are taken into account for positions update
  56420. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56421. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56422. var positionFunction = function (positions) {
  56423. var minlg = pathArray[0].length;
  56424. var i = 0;
  56425. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56426. for (var si = 1; si <= ns; si++) {
  56427. for (var p = 0; p < pathArray.length; p++) {
  56428. var path = pathArray[p];
  56429. var l = path.length;
  56430. minlg = (minlg < l) ? minlg : l;
  56431. var j = 0;
  56432. while (j < minlg) {
  56433. positions[i] = path[j].x;
  56434. positions[i + 1] = path[j].y;
  56435. positions[i + 2] = path[j].z;
  56436. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56437. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56438. }
  56439. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56440. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56441. }
  56442. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56443. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56444. }
  56445. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56446. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56447. }
  56448. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56449. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56450. }
  56451. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56452. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56453. }
  56454. j++;
  56455. i += 3;
  56456. }
  56457. if (instance._closePath) {
  56458. positions[i] = path[0].x;
  56459. positions[i + 1] = path[0].y;
  56460. positions[i + 2] = path[0].z;
  56461. i += 3;
  56462. }
  56463. }
  56464. }
  56465. };
  56466. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56467. positionFunction(positions);
  56468. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56469. instance._boundingInfo.update(instance._worldMatrix);
  56470. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56471. if (options.colors) {
  56472. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56473. for (var c = 0; c < options.colors.length; c++) {
  56474. colors[c * 4] = options.colors[c].r;
  56475. colors[c * 4 + 1] = options.colors[c].g;
  56476. colors[c * 4 + 2] = options.colors[c].b;
  56477. colors[c * 4 + 3] = options.colors[c].a;
  56478. }
  56479. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56480. }
  56481. if (options.uvs) {
  56482. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56483. for (var i = 0; i < options.uvs.length; i++) {
  56484. uvs[i * 2] = options.uvs[i].x;
  56485. uvs[i * 2 + 1] = options.uvs[i].y;
  56486. }
  56487. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56488. }
  56489. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56490. var indices = instance.getIndices();
  56491. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56492. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56493. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56494. if (instance._closePath) {
  56495. var indexFirst = 0;
  56496. var indexLast = 0;
  56497. for (var p = 0; p < pathArray.length; p++) {
  56498. indexFirst = instance._idx[p] * 3;
  56499. if (p + 1 < pathArray.length) {
  56500. indexLast = (instance._idx[p + 1] - 1) * 3;
  56501. }
  56502. else {
  56503. indexLast = normals.length - 3;
  56504. }
  56505. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56506. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56507. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56508. normals[indexLast] = normals[indexFirst];
  56509. normals[indexLast + 1] = normals[indexFirst + 1];
  56510. normals[indexLast + 2] = normals[indexFirst + 2];
  56511. }
  56512. }
  56513. if (!(instance.areNormalsFrozen)) {
  56514. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56515. }
  56516. }
  56517. return instance;
  56518. }
  56519. else {
  56520. var ribbon = new BABYLON.Mesh(name, scene);
  56521. ribbon._originalBuilderSideOrientation = sideOrientation;
  56522. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56523. if (closePath) {
  56524. ribbon._idx = vertexData._idx;
  56525. }
  56526. ribbon._closePath = closePath;
  56527. ribbon._closeArray = closeArray;
  56528. vertexData.applyToMesh(ribbon, updatable);
  56529. return ribbon;
  56530. }
  56531. };
  56532. /**
  56533. * Creates a cylinder or a cone mesh.
  56534. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56535. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56536. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56537. * 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.
  56538. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56539. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56540. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56541. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56542. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56543. * 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).
  56544. * 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
  56545. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56546. * 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
  56547. * 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.
  56548. * If `enclose` is false, a ring surface is one element.
  56549. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56550. * 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
  56551. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56552. * 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).
  56553. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56554. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56555. */
  56556. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56557. var cylinder = new BABYLON.Mesh(name, scene);
  56558. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56559. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56560. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56561. vertexData.applyToMesh(cylinder, options.updatable);
  56562. return cylinder;
  56563. };
  56564. /**
  56565. * Creates a torus mesh.
  56566. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56567. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56568. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56569. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56570. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56571. * 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).
  56572. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56574. */
  56575. MeshBuilder.CreateTorus = function (name, options, scene) {
  56576. var torus = new BABYLON.Mesh(name, scene);
  56577. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56578. torus._originalBuilderSideOrientation = options.sideOrientation;
  56579. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56580. vertexData.applyToMesh(torus, options.updatable);
  56581. return torus;
  56582. };
  56583. /**
  56584. * Creates a torus knot mesh.
  56585. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56586. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56587. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56588. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56589. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56590. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56591. * 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).
  56592. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56593. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56594. */
  56595. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56596. var torusKnot = new BABYLON.Mesh(name, scene);
  56597. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56598. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56599. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56600. vertexData.applyToMesh(torusKnot, options.updatable);
  56601. return torusKnot;
  56602. };
  56603. /**
  56604. * Creates a line system mesh.
  56605. * A line system is a pool of many lines gathered in a single mesh.
  56606. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56607. * 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.
  56608. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56609. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56610. * 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
  56611. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56612. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56613. * 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
  56614. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56615. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56616. */
  56617. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56618. var instance = options.instance;
  56619. var lines = options.lines;
  56620. var colors = options.colors;
  56621. if (instance) {
  56622. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56623. var vertexColor;
  56624. var lineColors;
  56625. if (colors) {
  56626. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56627. }
  56628. var i = 0;
  56629. var c = 0;
  56630. for (var l = 0; l < lines.length; l++) {
  56631. var points = lines[l];
  56632. for (var p = 0; p < points.length; p++) {
  56633. positions[i] = points[p].x;
  56634. positions[i + 1] = points[p].y;
  56635. positions[i + 2] = points[p].z;
  56636. if (colors && vertexColor) {
  56637. lineColors = colors[l];
  56638. vertexColor[c] = lineColors[p].r;
  56639. vertexColor[c + 1] = lineColors[p].g;
  56640. vertexColor[c + 2] = lineColors[p].b;
  56641. vertexColor[c + 3] = lineColors[p].a;
  56642. c += 4;
  56643. }
  56644. i += 3;
  56645. }
  56646. }
  56647. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56648. if (colors && vertexColor) {
  56649. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56650. }
  56651. return instance;
  56652. }
  56653. // line system creation
  56654. var useVertexColor = (colors) ? true : false;
  56655. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56656. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56657. vertexData.applyToMesh(lineSystem, options.updatable);
  56658. return lineSystem;
  56659. };
  56660. /**
  56661. * Creates a line mesh.
  56662. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56663. * 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.
  56664. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56665. * The parameter `points` is an array successive Vector3.
  56666. * 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
  56667. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56668. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56669. * When updating an instance, remember that only point positions can change, not the number of points.
  56670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56671. */
  56672. MeshBuilder.CreateLines = function (name, options, scene) {
  56673. if (scene === void 0) { scene = null; }
  56674. var colors = (options.colors) ? [options.colors] : null;
  56675. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56676. return lines;
  56677. };
  56678. /**
  56679. * Creates a dashed line mesh.
  56680. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56681. * 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.
  56682. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56683. * The parameter `points` is an array successive Vector3.
  56684. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56685. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56686. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56687. * 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
  56688. * When updating an instance, remember that only point positions can change, not the number of points.
  56689. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56690. */
  56691. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56692. if (scene === void 0) { scene = null; }
  56693. var points = options.points;
  56694. var instance = options.instance;
  56695. var gapSize = options.gapSize || 1;
  56696. var dashSize = options.dashSize || 3;
  56697. if (instance) {
  56698. var positionFunction = function (positions) {
  56699. var curvect = BABYLON.Vector3.Zero();
  56700. var nbSeg = positions.length / 6;
  56701. var lg = 0;
  56702. var nb = 0;
  56703. var shft = 0;
  56704. var dashshft = 0;
  56705. var curshft = 0;
  56706. var p = 0;
  56707. var i = 0;
  56708. var j = 0;
  56709. for (i = 0; i < points.length - 1; i++) {
  56710. points[i + 1].subtractToRef(points[i], curvect);
  56711. lg += curvect.length();
  56712. }
  56713. shft = lg / nbSeg;
  56714. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56715. for (i = 0; i < points.length - 1; i++) {
  56716. points[i + 1].subtractToRef(points[i], curvect);
  56717. nb = Math.floor(curvect.length() / shft);
  56718. curvect.normalize();
  56719. j = 0;
  56720. while (j < nb && p < positions.length) {
  56721. curshft = shft * j;
  56722. positions[p] = points[i].x + curshft * curvect.x;
  56723. positions[p + 1] = points[i].y + curshft * curvect.y;
  56724. positions[p + 2] = points[i].z + curshft * curvect.z;
  56725. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56726. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56727. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56728. p += 6;
  56729. j++;
  56730. }
  56731. }
  56732. while (p < positions.length) {
  56733. positions[p] = points[i].x;
  56734. positions[p + 1] = points[i].y;
  56735. positions[p + 2] = points[i].z;
  56736. p += 3;
  56737. }
  56738. };
  56739. instance.updateMeshPositions(positionFunction, false);
  56740. return instance;
  56741. }
  56742. // dashed lines creation
  56743. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56744. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56745. vertexData.applyToMesh(dashedLines, options.updatable);
  56746. dashedLines.dashSize = dashSize;
  56747. dashedLines.gapSize = gapSize;
  56748. return dashedLines;
  56749. };
  56750. /**
  56751. * Creates an extruded shape mesh.
  56752. * 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.
  56753. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56754. *
  56755. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56756. * 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
  56757. * extruded along the Z axis.
  56758. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56759. * 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.
  56760. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56761. * 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
  56762. * 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
  56763. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56764. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56765. * 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).
  56766. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56767. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56768. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56769. */
  56770. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56771. if (scene === void 0) { scene = null; }
  56772. var path = options.path;
  56773. var shape = options.shape;
  56774. var scale = options.scale || 1;
  56775. var rotation = options.rotation || 0;
  56776. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56777. var updatable = options.updatable;
  56778. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56779. var instance = options.instance || null;
  56780. var invertUV = options.invertUV || false;
  56781. 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);
  56782. };
  56783. /**
  56784. * Creates an custom extruded shape mesh.
  56785. * 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.
  56786. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56787. *
  56788. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56789. * 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
  56790. * extruded along the Z axis.
  56791. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56792. * 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
  56793. * and the distance of this point from the begining of the path :
  56794. * ```javascript
  56795. * var rotationFunction = function(i, distance) {
  56796. * // do things
  56797. * return rotationValue; }
  56798. * ```
  56799. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56800. * 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
  56801. * and the distance of this point from the begining of the path :
  56802. * ```javascript
  56803. * var scaleFunction = function(i, distance) {
  56804. * // do things
  56805. * return scaleValue;}
  56806. * ```
  56807. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56808. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56809. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56810. * 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
  56811. * 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
  56812. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56813. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56814. * 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).
  56815. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56816. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56817. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56818. */
  56819. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56820. var path = options.path;
  56821. var shape = options.shape;
  56822. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56823. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56824. var ribbonCloseArray = options.ribbonCloseArray || false;
  56825. var ribbonClosePath = options.ribbonClosePath || false;
  56826. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56827. var updatable = options.updatable;
  56828. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56829. var instance = options.instance;
  56830. var invertUV = options.invertUV || false;
  56831. 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);
  56832. };
  56833. /**
  56834. * Creates lathe mesh.
  56835. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56836. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56837. *
  56838. * 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
  56839. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56840. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56841. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56842. * 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.
  56843. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56844. * 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
  56845. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56846. * 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).
  56847. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56848. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56850. */
  56851. MeshBuilder.CreateLathe = function (name, options, scene) {
  56852. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56853. var closed = (options.closed === undefined) ? true : options.closed;
  56854. var shape = options.shape;
  56855. var radius = options.radius || 1;
  56856. var tessellation = options.tessellation || 64;
  56857. var updatable = options.updatable;
  56858. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56859. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56860. var pi2 = Math.PI * 2;
  56861. var paths = new Array();
  56862. var invertUV = options.invertUV || false;
  56863. var i = 0;
  56864. var p = 0;
  56865. var step = pi2 / tessellation * arc;
  56866. var rotated;
  56867. var path = new Array();
  56868. ;
  56869. for (i = 0; i <= tessellation; i++) {
  56870. var path = [];
  56871. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56872. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56873. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56874. }
  56875. for (p = 0; p < shape.length; p++) {
  56876. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56877. path.push(rotated);
  56878. }
  56879. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56880. 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));
  56881. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56882. }
  56883. paths.push(path);
  56884. }
  56885. // lathe ribbon
  56886. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56887. return lathe;
  56888. };
  56889. /**
  56890. * Creates a plane mesh.
  56891. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56892. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56893. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56894. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56895. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56896. * 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).
  56897. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56898. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56899. */
  56900. MeshBuilder.CreatePlane = function (name, options, scene) {
  56901. var plane = new BABYLON.Mesh(name, scene);
  56902. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56903. plane._originalBuilderSideOrientation = options.sideOrientation;
  56904. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56905. vertexData.applyToMesh(plane, options.updatable);
  56906. if (options.sourcePlane) {
  56907. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56908. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56909. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56910. plane.rotate(vectorProduct, product);
  56911. }
  56912. return plane;
  56913. };
  56914. /**
  56915. * Creates a ground mesh.
  56916. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56917. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56918. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56920. */
  56921. MeshBuilder.CreateGround = function (name, options, scene) {
  56922. var ground = new BABYLON.GroundMesh(name, scene);
  56923. ground._setReady(false);
  56924. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56925. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56926. ground._width = options.width || 1;
  56927. ground._height = options.height || 1;
  56928. ground._maxX = ground._width / 2;
  56929. ground._maxZ = ground._height / 2;
  56930. ground._minX = -ground._maxX;
  56931. ground._minZ = -ground._maxZ;
  56932. var vertexData = BABYLON.VertexData.CreateGround(options);
  56933. vertexData.applyToMesh(ground, options.updatable);
  56934. ground._setReady(true);
  56935. return ground;
  56936. };
  56937. /**
  56938. * Creates a tiled ground mesh.
  56939. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56940. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56941. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56942. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56943. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56944. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56945. * numbers of subdivisions on the ground width and height of each tile.
  56946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56947. */
  56948. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56949. var tiledGround = new BABYLON.Mesh(name, scene);
  56950. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56951. vertexData.applyToMesh(tiledGround, options.updatable);
  56952. return tiledGround;
  56953. };
  56954. /**
  56955. * Creates a ground mesh from a height map.
  56956. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56957. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56958. * The parameter `url` sets the URL of the height map image resource.
  56959. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56960. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56961. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56962. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56963. * 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.
  56964. * 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).
  56965. * This function is passed the newly built mesh :
  56966. * ```javascript
  56967. * function(mesh) { // do things
  56968. * return; }
  56969. * ```
  56970. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56971. */
  56972. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56973. var width = options.width || 10.0;
  56974. var height = options.height || 10.0;
  56975. var subdivisions = options.subdivisions || 1 | 0;
  56976. var minHeight = options.minHeight || 0.0;
  56977. var maxHeight = options.maxHeight || 1.0;
  56978. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56979. var updatable = options.updatable;
  56980. var onReady = options.onReady;
  56981. var ground = new BABYLON.GroundMesh(name, scene);
  56982. ground._subdivisionsX = subdivisions;
  56983. ground._subdivisionsY = subdivisions;
  56984. ground._width = width;
  56985. ground._height = height;
  56986. ground._maxX = ground._width / 2.0;
  56987. ground._maxZ = ground._height / 2.0;
  56988. ground._minX = -ground._maxX;
  56989. ground._minZ = -ground._maxZ;
  56990. ground._setReady(false);
  56991. var onload = function (img) {
  56992. // Getting height map data
  56993. var canvas = document.createElement("canvas");
  56994. var context = canvas.getContext("2d");
  56995. if (!context) {
  56996. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56997. }
  56998. if (scene.isDisposed) {
  56999. return;
  57000. }
  57001. var bufferWidth = img.width;
  57002. var bufferHeight = img.height;
  57003. canvas.width = bufferWidth;
  57004. canvas.height = bufferHeight;
  57005. context.drawImage(img, 0, 0);
  57006. // Create VertexData from map data
  57007. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  57008. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  57009. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  57010. width: width, height: height,
  57011. subdivisions: subdivisions,
  57012. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57013. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57014. });
  57015. vertexData.applyToMesh(ground, updatable);
  57016. //execute ready callback, if set
  57017. if (onReady) {
  57018. onReady(ground);
  57019. }
  57020. ground._setReady(true);
  57021. };
  57022. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57023. return ground;
  57024. };
  57025. /**
  57026. * Creates a polygon mesh.
  57027. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57028. * 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.
  57029. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57031. * 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).
  57032. * Remember you can only change the shape positions, not their number when updating a polygon.
  57033. */
  57034. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57035. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57036. var shape = options.shape;
  57037. var holes = options.holes || [];
  57038. var depth = options.depth || 0;
  57039. var contours = [];
  57040. var hole = [];
  57041. for (var i = 0; i < shape.length; i++) {
  57042. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57043. }
  57044. var epsilon = 0.00000001;
  57045. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57046. contours.pop();
  57047. }
  57048. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57049. for (var hNb = 0; hNb < holes.length; hNb++) {
  57050. hole = [];
  57051. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57052. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57053. }
  57054. polygonTriangulation.addHole(hole);
  57055. }
  57056. var polygon = polygonTriangulation.build(options.updatable, depth);
  57057. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57058. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57059. vertexData.applyToMesh(polygon, options.updatable);
  57060. return polygon;
  57061. };
  57062. ;
  57063. /**
  57064. * Creates an extruded polygon mesh, with depth in the Y direction.
  57065. * 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).
  57066. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57067. */
  57068. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57069. return MeshBuilder.CreatePolygon(name, options, scene);
  57070. };
  57071. ;
  57072. /**
  57073. * Creates a tube mesh.
  57074. * 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.
  57075. *
  57076. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57077. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57078. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57079. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57080. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57081. * 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.
  57082. * It must return a radius value (positive float) :
  57083. * ```javascript
  57084. * var radiusFunction = function(i, distance) {
  57085. * // do things
  57086. * return radius; }
  57087. * ```
  57088. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57089. * 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
  57090. * 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
  57091. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57092. * 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).
  57093. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57094. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57095. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57096. */
  57097. MeshBuilder.CreateTube = function (name, options, scene) {
  57098. var path = options.path;
  57099. var instance = options.instance;
  57100. var radius = 1.0;
  57101. if (instance) {
  57102. radius = instance.radius;
  57103. }
  57104. if (options.radius !== undefined) {
  57105. radius = options.radius;
  57106. }
  57107. ;
  57108. var tessellation = options.tessellation || 64 | 0;
  57109. var radiusFunction = options.radiusFunction || null;
  57110. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57111. var invertUV = options.invertUV || false;
  57112. var updatable = options.updatable;
  57113. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57114. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57115. // tube geometry
  57116. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57117. var tangents = path3D.getTangents();
  57118. var normals = path3D.getNormals();
  57119. var distances = path3D.getDistances();
  57120. var pi2 = Math.PI * 2;
  57121. var step = pi2 / tessellation * arc;
  57122. var returnRadius = function () { return radius; };
  57123. var radiusFunctionFinal = radiusFunction || returnRadius;
  57124. var circlePath;
  57125. var rad;
  57126. var normal;
  57127. var rotated;
  57128. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57129. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57130. for (var i = 0; i < path.length; i++) {
  57131. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57132. circlePath = Array(); // current circle array
  57133. normal = normals[i]; // current normal
  57134. for (var t = 0; t < tessellation; t++) {
  57135. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57136. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57137. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57138. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57139. circlePath[t] = rotated;
  57140. }
  57141. circlePaths[index] = circlePath;
  57142. index++;
  57143. }
  57144. // cap
  57145. var capPath = function (nbPoints, pathIndex) {
  57146. var pointCap = Array();
  57147. for (var i = 0; i < nbPoints; i++) {
  57148. pointCap.push(path[pathIndex]);
  57149. }
  57150. return pointCap;
  57151. };
  57152. switch (cap) {
  57153. case BABYLON.Mesh.NO_CAP:
  57154. break;
  57155. case BABYLON.Mesh.CAP_START:
  57156. circlePaths[0] = capPath(tessellation, 0);
  57157. circlePaths[1] = circlePaths[2].slice(0);
  57158. break;
  57159. case BABYLON.Mesh.CAP_END:
  57160. circlePaths[index] = circlePaths[index - 1].slice(0);
  57161. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57162. break;
  57163. case BABYLON.Mesh.CAP_ALL:
  57164. circlePaths[0] = capPath(tessellation, 0);
  57165. circlePaths[1] = circlePaths[2].slice(0);
  57166. circlePaths[index] = circlePaths[index - 1].slice(0);
  57167. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57168. break;
  57169. default:
  57170. break;
  57171. }
  57172. return circlePaths;
  57173. };
  57174. var path3D;
  57175. var pathArray;
  57176. if (instance) {
  57177. var arc = options.arc || instance.arc;
  57178. path3D = (instance.path3D).update(path);
  57179. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57180. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57181. instance.path3D = path3D;
  57182. instance.pathArray = pathArray;
  57183. instance.arc = arc;
  57184. instance.radius = radius;
  57185. return instance;
  57186. }
  57187. // tube creation
  57188. path3D = new BABYLON.Path3D(path);
  57189. var newPathArray = new Array();
  57190. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57191. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57192. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57193. tube.pathArray = pathArray;
  57194. tube.path3D = path3D;
  57195. tube.tessellation = tessellation;
  57196. tube.cap = cap;
  57197. tube.arc = options.arc;
  57198. tube.radius = radius;
  57199. return tube;
  57200. };
  57201. /**
  57202. * Creates a polyhedron mesh.
  57203. *
  57204. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57205. * 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
  57206. * to choose the wanted type.
  57207. * The parameter `size` (positive float, default 1) sets the polygon size.
  57208. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57209. * 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`.
  57210. * 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
  57211. * 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)`).
  57212. * 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
  57213. * 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.
  57214. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57215. * 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).
  57216. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57217. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57218. */
  57219. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57220. var polyhedron = new BABYLON.Mesh(name, scene);
  57221. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57222. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57223. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57224. vertexData.applyToMesh(polyhedron, options.updatable);
  57225. return polyhedron;
  57226. };
  57227. /**
  57228. * Creates a decal mesh.
  57229. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57230. * 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.
  57231. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57232. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57233. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57234. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57235. */
  57236. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57237. var indices = sourceMesh.getIndices();
  57238. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57239. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57240. var position = options.position || BABYLON.Vector3.Zero();
  57241. var normal = options.normal || BABYLON.Vector3.Up();
  57242. var size = options.size || BABYLON.Vector3.One();
  57243. var angle = options.angle || 0;
  57244. // Getting correct rotation
  57245. if (!normal) {
  57246. var target = new BABYLON.Vector3(0, 0, 1);
  57247. var camera = sourceMesh.getScene().activeCamera;
  57248. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57249. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57250. }
  57251. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57252. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57253. var pitch = Math.atan2(normal.y, len);
  57254. // Matrix
  57255. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57256. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57257. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57258. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57259. var vertexData = new BABYLON.VertexData();
  57260. vertexData.indices = [];
  57261. vertexData.positions = [];
  57262. vertexData.normals = [];
  57263. vertexData.uvs = [];
  57264. var currentVertexDataIndex = 0;
  57265. var extractDecalVector3 = function (indexId) {
  57266. var result = new BABYLON.PositionNormalVertex();
  57267. if (!indices || !positions || !normals) {
  57268. return result;
  57269. }
  57270. var vertexId = indices[indexId];
  57271. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57272. // Send vector to decal local world
  57273. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57274. // Get normal
  57275. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57276. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57277. return result;
  57278. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57279. var clip = function (vertices, axis) {
  57280. if (vertices.length === 0) {
  57281. return vertices;
  57282. }
  57283. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57284. var clipVertices = function (v0, v1) {
  57285. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57286. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57287. };
  57288. var result = new Array();
  57289. for (var index = 0; index < vertices.length; index += 3) {
  57290. var v1Out;
  57291. var v2Out;
  57292. var v3Out;
  57293. var total = 0;
  57294. var nV1 = null;
  57295. var nV2 = null;
  57296. var nV3 = null;
  57297. var nV4 = null;
  57298. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57299. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57300. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57301. v1Out = d1 > 0;
  57302. v2Out = d2 > 0;
  57303. v3Out = d3 > 0;
  57304. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57305. switch (total) {
  57306. case 0:
  57307. result.push(vertices[index]);
  57308. result.push(vertices[index + 1]);
  57309. result.push(vertices[index + 2]);
  57310. break;
  57311. case 1:
  57312. if (v1Out) {
  57313. nV1 = vertices[index + 1];
  57314. nV2 = vertices[index + 2];
  57315. nV3 = clipVertices(vertices[index], nV1);
  57316. nV4 = clipVertices(vertices[index], nV2);
  57317. }
  57318. if (v2Out) {
  57319. nV1 = vertices[index];
  57320. nV2 = vertices[index + 2];
  57321. nV3 = clipVertices(vertices[index + 1], nV1);
  57322. nV4 = clipVertices(vertices[index + 1], nV2);
  57323. result.push(nV3);
  57324. result.push(nV2.clone());
  57325. result.push(nV1.clone());
  57326. result.push(nV2.clone());
  57327. result.push(nV3.clone());
  57328. result.push(nV4);
  57329. break;
  57330. }
  57331. if (v3Out) {
  57332. nV1 = vertices[index];
  57333. nV2 = vertices[index + 1];
  57334. nV3 = clipVertices(vertices[index + 2], nV1);
  57335. nV4 = clipVertices(vertices[index + 2], nV2);
  57336. }
  57337. if (nV1 && nV2 && nV3 && nV4) {
  57338. result.push(nV1.clone());
  57339. result.push(nV2.clone());
  57340. result.push(nV3);
  57341. result.push(nV4);
  57342. result.push(nV3.clone());
  57343. result.push(nV2.clone());
  57344. }
  57345. break;
  57346. case 2:
  57347. if (!v1Out) {
  57348. nV1 = vertices[index].clone();
  57349. nV2 = clipVertices(nV1, vertices[index + 1]);
  57350. nV3 = clipVertices(nV1, vertices[index + 2]);
  57351. result.push(nV1);
  57352. result.push(nV2);
  57353. result.push(nV3);
  57354. }
  57355. if (!v2Out) {
  57356. nV1 = vertices[index + 1].clone();
  57357. nV2 = clipVertices(nV1, vertices[index + 2]);
  57358. nV3 = clipVertices(nV1, vertices[index]);
  57359. result.push(nV1);
  57360. result.push(nV2);
  57361. result.push(nV3);
  57362. }
  57363. if (!v3Out) {
  57364. nV1 = vertices[index + 2].clone();
  57365. nV2 = clipVertices(nV1, vertices[index]);
  57366. nV3 = clipVertices(nV1, vertices[index + 1]);
  57367. result.push(nV1);
  57368. result.push(nV2);
  57369. result.push(nV3);
  57370. }
  57371. break;
  57372. case 3:
  57373. break;
  57374. }
  57375. }
  57376. return result;
  57377. };
  57378. for (var index = 0; index < indices.length; index += 3) {
  57379. var faceVertices = new Array();
  57380. faceVertices.push(extractDecalVector3(index));
  57381. faceVertices.push(extractDecalVector3(index + 1));
  57382. faceVertices.push(extractDecalVector3(index + 2));
  57383. // Clip
  57384. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57385. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57386. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57387. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57388. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57389. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57390. if (faceVertices.length === 0) {
  57391. continue;
  57392. }
  57393. // Add UVs and get back to world
  57394. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57395. var vertex = faceVertices[vIndex];
  57396. //TODO check for Int32Array | Uint32Array | Uint16Array
  57397. vertexData.indices.push(currentVertexDataIndex);
  57398. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57399. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57400. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57401. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57402. currentVertexDataIndex++;
  57403. }
  57404. }
  57405. // Return mesh
  57406. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57407. vertexData.applyToMesh(decal);
  57408. decal.position = position.clone();
  57409. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57410. return decal;
  57411. };
  57412. // Privates
  57413. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57414. // extrusion geometry
  57415. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57416. var tangents = path3D.getTangents();
  57417. var normals = path3D.getNormals();
  57418. var binormals = path3D.getBinormals();
  57419. var distances = path3D.getDistances();
  57420. var angle = 0;
  57421. var returnScale = function () { return scale !== null ? scale : 1; };
  57422. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57423. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57424. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57425. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57426. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57427. for (var i = 0; i < curve.length; i++) {
  57428. var shapePath = new Array();
  57429. var angleStep = rotate(i, distances[i]);
  57430. var scaleRatio = scl(i, distances[i]);
  57431. for (var p = 0; p < shape.length; p++) {
  57432. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57433. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57434. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57435. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57436. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57437. shapePath[p] = rotated;
  57438. }
  57439. shapePaths[index] = shapePath;
  57440. angle += angleStep;
  57441. index++;
  57442. }
  57443. // cap
  57444. var capPath = function (shapePath) {
  57445. var pointCap = Array();
  57446. var barycenter = BABYLON.Vector3.Zero();
  57447. var i;
  57448. for (i = 0; i < shapePath.length; i++) {
  57449. barycenter.addInPlace(shapePath[i]);
  57450. }
  57451. barycenter.scaleInPlace(1.0 / shapePath.length);
  57452. for (i = 0; i < shapePath.length; i++) {
  57453. pointCap.push(barycenter);
  57454. }
  57455. return pointCap;
  57456. };
  57457. switch (cap) {
  57458. case BABYLON.Mesh.NO_CAP:
  57459. break;
  57460. case BABYLON.Mesh.CAP_START:
  57461. shapePaths[0] = capPath(shapePaths[2]);
  57462. shapePaths[1] = shapePaths[2];
  57463. break;
  57464. case BABYLON.Mesh.CAP_END:
  57465. shapePaths[index] = shapePaths[index - 1];
  57466. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57467. break;
  57468. case BABYLON.Mesh.CAP_ALL:
  57469. shapePaths[0] = capPath(shapePaths[2]);
  57470. shapePaths[1] = shapePaths[2];
  57471. shapePaths[index] = shapePaths[index - 1];
  57472. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57473. break;
  57474. default:
  57475. break;
  57476. }
  57477. return shapePaths;
  57478. };
  57479. var path3D;
  57480. var pathArray;
  57481. if (instance) {
  57482. path3D = (instance.path3D).update(curve);
  57483. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57484. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57485. return instance;
  57486. }
  57487. // extruded shape creation
  57488. path3D = new BABYLON.Path3D(curve);
  57489. var newShapePaths = new Array();
  57490. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57491. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57492. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57493. extrudedGeneric.pathArray = pathArray;
  57494. extrudedGeneric.path3D = path3D;
  57495. extrudedGeneric.cap = cap;
  57496. return extrudedGeneric;
  57497. };
  57498. return MeshBuilder;
  57499. }());
  57500. BABYLON.MeshBuilder = MeshBuilder;
  57501. })(BABYLON || (BABYLON = {}));
  57502. //# sourceMappingURL=babylon.meshBuilder.js.map
  57503. "use strict";
  57504. var BABYLON;
  57505. (function (BABYLON) {
  57506. /**
  57507. * Draco compression (https://google.github.io/draco/)
  57508. */
  57509. var DracoCompression = /** @class */ (function () {
  57510. /**
  57511. * Constructor
  57512. * @param numWorkers The number of workers for async operations
  57513. */
  57514. function DracoCompression(numWorkers) {
  57515. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57516. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57517. if (!workerBlobUrl || !Worker) {
  57518. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57519. return;
  57520. }
  57521. var workers = new Array(numWorkers);
  57522. for (var i = 0; i < workers.length; i++) {
  57523. var worker = new Worker(workerBlobUrl);
  57524. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57525. workers[i] = worker;
  57526. }
  57527. this._workerPool = new BABYLON.WorkerPool(workers);
  57528. }
  57529. /**
  57530. * Stop all async operations and release resources.
  57531. */
  57532. DracoCompression.prototype.dispose = function () {
  57533. this._workerPool.dispose();
  57534. delete this._workerPool;
  57535. };
  57536. /**
  57537. * Decode Draco compressed mesh data to vertex data.
  57538. * @param data The array buffer view for the Draco compression data
  57539. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57540. * @returns A promise that resolves with the decoded vertex data
  57541. */
  57542. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57543. var _this = this;
  57544. return new Promise(function (resolve, reject) {
  57545. _this._workerPool.push(function (worker, onComplete) {
  57546. var vertexData = new BABYLON.VertexData();
  57547. var onError = function (error) {
  57548. worker.removeEventListener("error", onError);
  57549. worker.removeEventListener("message", onMessage);
  57550. reject(error);
  57551. onComplete();
  57552. };
  57553. var onMessage = function (message) {
  57554. if (message.data === "done") {
  57555. worker.removeEventListener("error", onError);
  57556. worker.removeEventListener("message", onMessage);
  57557. resolve(vertexData);
  57558. onComplete();
  57559. }
  57560. else if (message.data.id === "indices") {
  57561. vertexData.indices = message.data.value;
  57562. }
  57563. else {
  57564. vertexData.set(message.data.value, message.data.id);
  57565. }
  57566. };
  57567. worker.addEventListener("error", onError);
  57568. worker.addEventListener("message", onMessage);
  57569. var dataCopy = new Uint8Array(data.byteLength);
  57570. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57571. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57572. });
  57573. });
  57574. };
  57575. /**
  57576. * The worker function that gets converted to a blob url to pass into a worker.
  57577. */
  57578. DracoCompression._Worker = function () {
  57579. // self is actually a DedicatedWorkerGlobalScope
  57580. var _self = self;
  57581. var decodeMesh = function (data, attributes) {
  57582. var dracoModule = new DracoDecoderModule();
  57583. var buffer = new dracoModule.DecoderBuffer();
  57584. buffer.Init(data, data.byteLength);
  57585. var decoder = new dracoModule.Decoder();
  57586. var geometry;
  57587. var status;
  57588. try {
  57589. var type = decoder.GetEncodedGeometryType(buffer);
  57590. switch (type) {
  57591. case dracoModule.TRIANGULAR_MESH:
  57592. geometry = new dracoModule.Mesh();
  57593. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57594. break;
  57595. case dracoModule.POINT_CLOUD:
  57596. geometry = new dracoModule.PointCloud();
  57597. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57598. break;
  57599. default:
  57600. throw new Error("Invalid geometry type " + type);
  57601. }
  57602. if (!status.ok() || !geometry.ptr) {
  57603. throw new Error(status.error_msg());
  57604. }
  57605. var numPoints = geometry.num_points();
  57606. if (type === dracoModule.TRIANGULAR_MESH) {
  57607. var numFaces = geometry.num_faces();
  57608. var faceIndices = new dracoModule.DracoInt32Array();
  57609. try {
  57610. var indices = new Uint32Array(numFaces * 3);
  57611. for (var i = 0; i < numFaces; i++) {
  57612. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57613. var offset = i * 3;
  57614. indices[offset + 0] = faceIndices.GetValue(0);
  57615. indices[offset + 1] = faceIndices.GetValue(1);
  57616. indices[offset + 2] = faceIndices.GetValue(2);
  57617. }
  57618. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57619. }
  57620. finally {
  57621. dracoModule.destroy(faceIndices);
  57622. }
  57623. }
  57624. for (var kind in attributes) {
  57625. var uniqueId = attributes[kind];
  57626. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57627. var dracoData = new dracoModule.DracoFloat32Array();
  57628. try {
  57629. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57630. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57631. for (var i = 0; i < babylonData.length; i++) {
  57632. babylonData[i] = dracoData.GetValue(i);
  57633. }
  57634. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57635. }
  57636. finally {
  57637. dracoModule.destroy(dracoData);
  57638. }
  57639. }
  57640. }
  57641. finally {
  57642. if (geometry) {
  57643. dracoModule.destroy(geometry);
  57644. }
  57645. dracoModule.destroy(decoder);
  57646. dracoModule.destroy(buffer);
  57647. }
  57648. _self.postMessage("done");
  57649. };
  57650. _self.onmessage = function (event) {
  57651. switch (event.data.id) {
  57652. case "initDecoder": {
  57653. importScripts(event.data.url);
  57654. break;
  57655. }
  57656. case "decodeMesh": {
  57657. decodeMesh(event.data.data, event.data.attributes);
  57658. break;
  57659. }
  57660. }
  57661. };
  57662. };
  57663. DracoCompression._GetDefaultDecoderUrl = function () {
  57664. if (!BABYLON.Tools.IsWindowObjectExist) {
  57665. return null;
  57666. }
  57667. for (var i = 0; i < document.scripts.length; i++) {
  57668. if (document.scripts[i].type === "text/x-draco-decoder") {
  57669. return document.scripts[i].src;
  57670. }
  57671. }
  57672. return null;
  57673. };
  57674. /**
  57675. * Gets the url to the draco decoder if available.
  57676. */
  57677. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57678. return DracoCompression;
  57679. }());
  57680. BABYLON.DracoCompression = DracoCompression;
  57681. })(BABYLON || (BABYLON = {}));
  57682. //# sourceMappingURL=babylon.dracoCompression.js.map
  57683. "use strict";
  57684. var BABYLON;
  57685. (function (BABYLON) {
  57686. var AudioEngine = /** @class */ (function () {
  57687. function AudioEngine() {
  57688. this._audioContext = null;
  57689. this._audioContextInitialized = false;
  57690. this.canUseWebAudio = false;
  57691. this.WarnedWebAudioUnsupported = false;
  57692. this.unlocked = false;
  57693. this.isMP3supported = false;
  57694. this.isOGGsupported = false;
  57695. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57696. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57697. this.canUseWebAudio = true;
  57698. }
  57699. var audioElem = document.createElement('audio');
  57700. try {
  57701. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57702. this.isMP3supported = true;
  57703. }
  57704. }
  57705. catch (e) {
  57706. // protect error during capability check.
  57707. }
  57708. try {
  57709. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57710. this.isOGGsupported = true;
  57711. }
  57712. }
  57713. catch (e) {
  57714. // protect error during capability check.
  57715. }
  57716. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57717. this._unlockiOSaudio();
  57718. }
  57719. else {
  57720. this.unlocked = true;
  57721. }
  57722. }
  57723. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57724. get: function () {
  57725. if (!this._audioContextInitialized) {
  57726. this._initializeAudioContext();
  57727. }
  57728. return this._audioContext;
  57729. },
  57730. enumerable: true,
  57731. configurable: true
  57732. });
  57733. AudioEngine.prototype._unlockiOSaudio = function () {
  57734. var _this = this;
  57735. var unlockaudio = function () {
  57736. if (!_this.audioContext) {
  57737. return;
  57738. }
  57739. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57740. var source = _this.audioContext.createBufferSource();
  57741. source.buffer = buffer;
  57742. source.connect(_this.audioContext.destination);
  57743. source.start(0);
  57744. setTimeout(function () {
  57745. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57746. _this.unlocked = true;
  57747. window.removeEventListener('touchend', unlockaudio, false);
  57748. if (_this.onAudioUnlocked) {
  57749. _this.onAudioUnlocked();
  57750. }
  57751. }
  57752. }, 0);
  57753. };
  57754. window.addEventListener('touchend', unlockaudio, false);
  57755. };
  57756. AudioEngine.prototype._initializeAudioContext = function () {
  57757. try {
  57758. if (this.canUseWebAudio) {
  57759. this._audioContext = new AudioContext();
  57760. // create a global volume gain node
  57761. this.masterGain = this._audioContext.createGain();
  57762. this.masterGain.gain.value = 1;
  57763. this.masterGain.connect(this._audioContext.destination);
  57764. this._audioContextInitialized = true;
  57765. }
  57766. }
  57767. catch (e) {
  57768. this.canUseWebAudio = false;
  57769. BABYLON.Tools.Error("Web Audio: " + e.message);
  57770. }
  57771. };
  57772. AudioEngine.prototype.dispose = function () {
  57773. if (this.canUseWebAudio && this._audioContextInitialized) {
  57774. if (this._connectedAnalyser && this._audioContext) {
  57775. this._connectedAnalyser.stopDebugCanvas();
  57776. this._connectedAnalyser.dispose();
  57777. this.masterGain.disconnect();
  57778. this.masterGain.connect(this._audioContext.destination);
  57779. this._connectedAnalyser = null;
  57780. }
  57781. this.masterGain.gain.value = 1;
  57782. }
  57783. this.WarnedWebAudioUnsupported = false;
  57784. };
  57785. AudioEngine.prototype.getGlobalVolume = function () {
  57786. if (this.canUseWebAudio && this._audioContextInitialized) {
  57787. return this.masterGain.gain.value;
  57788. }
  57789. else {
  57790. return -1;
  57791. }
  57792. };
  57793. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57794. if (this.canUseWebAudio && this._audioContextInitialized) {
  57795. this.masterGain.gain.value = newVolume;
  57796. }
  57797. };
  57798. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57799. if (this._connectedAnalyser) {
  57800. this._connectedAnalyser.stopDebugCanvas();
  57801. }
  57802. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57803. this._connectedAnalyser = analyser;
  57804. this.masterGain.disconnect();
  57805. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57806. }
  57807. };
  57808. return AudioEngine;
  57809. }());
  57810. BABYLON.AudioEngine = AudioEngine;
  57811. })(BABYLON || (BABYLON = {}));
  57812. //# sourceMappingURL=babylon.audioEngine.js.map
  57813. "use strict";
  57814. var BABYLON;
  57815. (function (BABYLON) {
  57816. var Sound = /** @class */ (function () {
  57817. /**
  57818. * Create a sound and attach it to a scene
  57819. * @param name Name of your sound
  57820. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57821. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57822. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57823. */
  57824. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57825. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57826. var _this = this;
  57827. this.autoplay = false;
  57828. this.loop = false;
  57829. this.useCustomAttenuation = false;
  57830. this.spatialSound = false;
  57831. this.refDistance = 1;
  57832. this.rolloffFactor = 1;
  57833. this.maxDistance = 100;
  57834. this.distanceModel = "linear";
  57835. this._panningModel = "equalpower";
  57836. this._playbackRate = 1;
  57837. this._streaming = false;
  57838. this._startTime = 0;
  57839. this._startOffset = 0;
  57840. this._position = BABYLON.Vector3.Zero();
  57841. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57842. this._volume = 1;
  57843. this._isReadyToPlay = false;
  57844. this.isPlaying = false;
  57845. this.isPaused = false;
  57846. this._isDirectional = false;
  57847. // Used if you'd like to create a directional sound.
  57848. // If not set, the sound will be omnidirectional
  57849. this._coneInnerAngle = 360;
  57850. this._coneOuterAngle = 360;
  57851. this._coneOuterGain = 0;
  57852. this._isOutputConnected = false;
  57853. this._urlType = "Unknown";
  57854. this.name = name;
  57855. this._scene = scene;
  57856. this._readyToPlayCallback = readyToPlayCallback;
  57857. // Default custom attenuation function is a linear attenuation
  57858. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57859. if (currentDistance < maxDistance) {
  57860. return currentVolume * (1 - currentDistance / maxDistance);
  57861. }
  57862. else {
  57863. return 0;
  57864. }
  57865. };
  57866. if (options) {
  57867. this.autoplay = options.autoplay || false;
  57868. this.loop = options.loop || false;
  57869. // if volume === 0, we need another way to check this option
  57870. if (options.volume !== undefined) {
  57871. this._volume = options.volume;
  57872. }
  57873. this.spatialSound = options.spatialSound || false;
  57874. this.maxDistance = options.maxDistance || 100;
  57875. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57876. this.rolloffFactor = options.rolloffFactor || 1;
  57877. this.refDistance = options.refDistance || 1;
  57878. this.distanceModel = options.distanceModel || "linear";
  57879. this._playbackRate = options.playbackRate || 1;
  57880. this._streaming = options.streaming || false;
  57881. }
  57882. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57883. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57884. this._soundGain.gain.value = this._volume;
  57885. this._inputAudioNode = this._soundGain;
  57886. this._ouputAudioNode = this._soundGain;
  57887. if (this.spatialSound) {
  57888. this._createSpatialParameters();
  57889. }
  57890. this._scene.mainSoundTrack.AddSound(this);
  57891. var validParameter = true;
  57892. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57893. if (urlOrArrayBuffer) {
  57894. if (typeof (urlOrArrayBuffer) === "string")
  57895. this._urlType = "String";
  57896. if (Array.isArray(urlOrArrayBuffer))
  57897. this._urlType = "Array";
  57898. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57899. this._urlType = "ArrayBuffer";
  57900. var urls = [];
  57901. var codecSupportedFound = false;
  57902. switch (this._urlType) {
  57903. case "ArrayBuffer":
  57904. if (urlOrArrayBuffer.byteLength > 0) {
  57905. codecSupportedFound = true;
  57906. this._soundLoaded(urlOrArrayBuffer);
  57907. }
  57908. break;
  57909. case "String":
  57910. urls.push(urlOrArrayBuffer);
  57911. case "Array":
  57912. if (urls.length === 0)
  57913. urls = urlOrArrayBuffer;
  57914. // If we found a supported format, we load it immediately and stop the loop
  57915. for (var i = 0; i < urls.length; i++) {
  57916. var url = urls[i];
  57917. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57918. codecSupportedFound = true;
  57919. }
  57920. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57921. codecSupportedFound = true;
  57922. }
  57923. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57924. codecSupportedFound = true;
  57925. }
  57926. if (url.indexOf("blob:") !== -1) {
  57927. codecSupportedFound = true;
  57928. }
  57929. if (codecSupportedFound) {
  57930. // Loading sound using XHR2
  57931. if (!this._streaming) {
  57932. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57933. }
  57934. else {
  57935. this._htmlAudioElement = new Audio(url);
  57936. this._htmlAudioElement.controls = false;
  57937. this._htmlAudioElement.loop = this.loop;
  57938. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57939. this._htmlAudioElement.preload = "auto";
  57940. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57941. _this._isReadyToPlay = true;
  57942. if (_this.autoplay) {
  57943. _this.play();
  57944. }
  57945. if (_this._readyToPlayCallback) {
  57946. _this._readyToPlayCallback();
  57947. }
  57948. });
  57949. document.body.appendChild(this._htmlAudioElement);
  57950. }
  57951. break;
  57952. }
  57953. }
  57954. break;
  57955. default:
  57956. validParameter = false;
  57957. break;
  57958. }
  57959. if (!validParameter) {
  57960. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57961. }
  57962. else {
  57963. if (!codecSupportedFound) {
  57964. this._isReadyToPlay = true;
  57965. // Simulating a ready to play event to avoid breaking code path
  57966. if (this._readyToPlayCallback) {
  57967. window.setTimeout(function () {
  57968. if (_this._readyToPlayCallback) {
  57969. _this._readyToPlayCallback();
  57970. }
  57971. }, 1000);
  57972. }
  57973. }
  57974. }
  57975. }
  57976. }
  57977. else {
  57978. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57979. this._scene.mainSoundTrack.AddSound(this);
  57980. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57981. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57982. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57983. }
  57984. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57985. if (this._readyToPlayCallback) {
  57986. window.setTimeout(function () {
  57987. if (_this._readyToPlayCallback) {
  57988. _this._readyToPlayCallback();
  57989. }
  57990. }, 1000);
  57991. }
  57992. }
  57993. }
  57994. Sound.prototype.dispose = function () {
  57995. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57996. if (this.isPlaying) {
  57997. this.stop();
  57998. }
  57999. this._isReadyToPlay = false;
  58000. if (this.soundTrackId === -1) {
  58001. this._scene.mainSoundTrack.RemoveSound(this);
  58002. }
  58003. else {
  58004. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58005. }
  58006. if (this._soundGain) {
  58007. this._soundGain.disconnect();
  58008. this._soundGain = null;
  58009. }
  58010. if (this._soundPanner) {
  58011. this._soundPanner.disconnect();
  58012. this._soundPanner = null;
  58013. }
  58014. if (this._soundSource) {
  58015. this._soundSource.disconnect();
  58016. this._soundSource = null;
  58017. }
  58018. this._audioBuffer = null;
  58019. if (this._htmlAudioElement) {
  58020. this._htmlAudioElement.pause();
  58021. this._htmlAudioElement.src = "";
  58022. document.body.removeChild(this._htmlAudioElement);
  58023. }
  58024. if (this._connectedMesh && this._registerFunc) {
  58025. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58026. this._connectedMesh = null;
  58027. }
  58028. }
  58029. };
  58030. Sound.prototype.isReady = function () {
  58031. return this._isReadyToPlay;
  58032. };
  58033. Sound.prototype._soundLoaded = function (audioData) {
  58034. var _this = this;
  58035. if (!BABYLON.Engine.audioEngine.audioContext) {
  58036. return;
  58037. }
  58038. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58039. _this._audioBuffer = buffer;
  58040. _this._isReadyToPlay = true;
  58041. if (_this.autoplay) {
  58042. _this.play();
  58043. }
  58044. if (_this._readyToPlayCallback) {
  58045. _this._readyToPlayCallback();
  58046. }
  58047. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58048. };
  58049. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58050. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58051. this._audioBuffer = audioBuffer;
  58052. this._isReadyToPlay = true;
  58053. }
  58054. };
  58055. Sound.prototype.updateOptions = function (options) {
  58056. if (options) {
  58057. this.loop = options.loop || this.loop;
  58058. this.maxDistance = options.maxDistance || this.maxDistance;
  58059. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58060. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58061. this.refDistance = options.refDistance || this.refDistance;
  58062. this.distanceModel = options.distanceModel || this.distanceModel;
  58063. this._playbackRate = options.playbackRate || this._playbackRate;
  58064. this._updateSpatialParameters();
  58065. if (this.isPlaying) {
  58066. if (this._streaming) {
  58067. this._htmlAudioElement.playbackRate = this._playbackRate;
  58068. }
  58069. else {
  58070. if (this._soundSource) {
  58071. this._soundSource.playbackRate.value = this._playbackRate;
  58072. }
  58073. }
  58074. }
  58075. }
  58076. };
  58077. Sound.prototype._createSpatialParameters = function () {
  58078. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58079. if (this._scene.headphone) {
  58080. this._panningModel = "HRTF";
  58081. }
  58082. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58083. this._updateSpatialParameters();
  58084. this._soundPanner.connect(this._ouputAudioNode);
  58085. this._inputAudioNode = this._soundPanner;
  58086. }
  58087. };
  58088. Sound.prototype._updateSpatialParameters = function () {
  58089. if (this.spatialSound && this._soundPanner) {
  58090. if (this.useCustomAttenuation) {
  58091. // Tricks to disable in a way embedded Web Audio attenuation
  58092. this._soundPanner.distanceModel = "linear";
  58093. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58094. this._soundPanner.refDistance = 1;
  58095. this._soundPanner.rolloffFactor = 1;
  58096. this._soundPanner.panningModel = this._panningModel;
  58097. }
  58098. else {
  58099. this._soundPanner.distanceModel = this.distanceModel;
  58100. this._soundPanner.maxDistance = this.maxDistance;
  58101. this._soundPanner.refDistance = this.refDistance;
  58102. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58103. this._soundPanner.panningModel = this._panningModel;
  58104. }
  58105. }
  58106. };
  58107. Sound.prototype.switchPanningModelToHRTF = function () {
  58108. this._panningModel = "HRTF";
  58109. this._switchPanningModel();
  58110. };
  58111. Sound.prototype.switchPanningModelToEqualPower = function () {
  58112. this._panningModel = "equalpower";
  58113. this._switchPanningModel();
  58114. };
  58115. Sound.prototype._switchPanningModel = function () {
  58116. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58117. this._soundPanner.panningModel = this._panningModel;
  58118. }
  58119. };
  58120. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58121. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58122. if (this._isOutputConnected) {
  58123. this._ouputAudioNode.disconnect();
  58124. }
  58125. this._ouputAudioNode.connect(soundTrackAudioNode);
  58126. this._isOutputConnected = true;
  58127. }
  58128. };
  58129. /**
  58130. * Transform this sound into a directional source
  58131. * @param coneInnerAngle Size of the inner cone in degree
  58132. * @param coneOuterAngle Size of the outer cone in degree
  58133. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58134. */
  58135. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58136. if (coneOuterAngle < coneInnerAngle) {
  58137. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58138. return;
  58139. }
  58140. this._coneInnerAngle = coneInnerAngle;
  58141. this._coneOuterAngle = coneOuterAngle;
  58142. this._coneOuterGain = coneOuterGain;
  58143. this._isDirectional = true;
  58144. if (this.isPlaying && this.loop) {
  58145. this.stop();
  58146. this.play();
  58147. }
  58148. };
  58149. Sound.prototype.setPosition = function (newPosition) {
  58150. this._position = newPosition;
  58151. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58152. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58153. }
  58154. };
  58155. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58156. this._localDirection = newLocalDirection;
  58157. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58158. this._updateDirection();
  58159. }
  58160. };
  58161. Sound.prototype._updateDirection = function () {
  58162. if (!this._connectedMesh || !this._soundPanner) {
  58163. return;
  58164. }
  58165. var mat = this._connectedMesh.getWorldMatrix();
  58166. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58167. direction.normalize();
  58168. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58169. };
  58170. Sound.prototype.updateDistanceFromListener = function () {
  58171. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58172. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58173. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58174. }
  58175. };
  58176. Sound.prototype.setAttenuationFunction = function (callback) {
  58177. this._customAttenuationFunction = callback;
  58178. };
  58179. /**
  58180. * Play the sound
  58181. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58182. * @param offset (optional) Start the sound setting it at a specific time
  58183. */
  58184. Sound.prototype.play = function (time, offset) {
  58185. var _this = this;
  58186. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58187. try {
  58188. if (this._startOffset < 0) {
  58189. time = -this._startOffset;
  58190. this._startOffset = 0;
  58191. }
  58192. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58193. if (!this._soundSource || !this._streamingSource) {
  58194. if (this.spatialSound && this._soundPanner) {
  58195. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58196. if (this._isDirectional) {
  58197. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58198. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58199. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58200. if (this._connectedMesh) {
  58201. this._updateDirection();
  58202. }
  58203. else {
  58204. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58205. }
  58206. }
  58207. }
  58208. }
  58209. if (this._streaming) {
  58210. if (!this._streamingSource) {
  58211. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58212. this._htmlAudioElement.onended = function () { _this._onended(); };
  58213. this._htmlAudioElement.playbackRate = this._playbackRate;
  58214. }
  58215. this._streamingSource.disconnect();
  58216. this._streamingSource.connect(this._inputAudioNode);
  58217. this._htmlAudioElement.play();
  58218. }
  58219. else {
  58220. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58221. this._soundSource.buffer = this._audioBuffer;
  58222. this._soundSource.connect(this._inputAudioNode);
  58223. this._soundSource.loop = this.loop;
  58224. this._soundSource.playbackRate.value = this._playbackRate;
  58225. this._soundSource.onended = function () { _this._onended(); };
  58226. if (this._soundSource.buffer) {
  58227. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58228. }
  58229. }
  58230. this._startTime = startTime;
  58231. this.isPlaying = true;
  58232. this.isPaused = false;
  58233. }
  58234. catch (ex) {
  58235. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58236. }
  58237. }
  58238. };
  58239. Sound.prototype._onended = function () {
  58240. this.isPlaying = false;
  58241. if (this.onended) {
  58242. this.onended();
  58243. }
  58244. };
  58245. /**
  58246. * Stop the sound
  58247. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58248. */
  58249. Sound.prototype.stop = function (time) {
  58250. if (this.isPlaying) {
  58251. if (this._streaming) {
  58252. this._htmlAudioElement.pause();
  58253. // Test needed for Firefox or it will generate an Invalid State Error
  58254. if (this._htmlAudioElement.currentTime > 0) {
  58255. this._htmlAudioElement.currentTime = 0;
  58256. }
  58257. }
  58258. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58259. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58260. this._soundSource.stop(stopTime);
  58261. this._soundSource.onended = function () { };
  58262. if (!this.isPaused) {
  58263. this._startOffset = 0;
  58264. }
  58265. }
  58266. this.isPlaying = false;
  58267. }
  58268. };
  58269. Sound.prototype.pause = function () {
  58270. if (this.isPlaying) {
  58271. this.isPaused = true;
  58272. if (this._streaming) {
  58273. this._htmlAudioElement.pause();
  58274. }
  58275. else if (BABYLON.Engine.audioEngine.audioContext) {
  58276. this.stop(0);
  58277. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58278. }
  58279. }
  58280. };
  58281. Sound.prototype.setVolume = function (newVolume, time) {
  58282. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58283. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58284. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58285. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58286. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58287. }
  58288. else {
  58289. this._soundGain.gain.value = newVolume;
  58290. }
  58291. }
  58292. this._volume = newVolume;
  58293. };
  58294. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58295. this._playbackRate = newPlaybackRate;
  58296. if (this.isPlaying) {
  58297. if (this._streaming) {
  58298. this._htmlAudioElement.playbackRate = this._playbackRate;
  58299. }
  58300. else if (this._soundSource) {
  58301. this._soundSource.playbackRate.value = this._playbackRate;
  58302. }
  58303. }
  58304. };
  58305. Sound.prototype.getVolume = function () {
  58306. return this._volume;
  58307. };
  58308. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58309. var _this = this;
  58310. if (this._connectedMesh && this._registerFunc) {
  58311. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58312. this._registerFunc = null;
  58313. }
  58314. this._connectedMesh = meshToConnectTo;
  58315. if (!this.spatialSound) {
  58316. this.spatialSound = true;
  58317. this._createSpatialParameters();
  58318. if (this.isPlaying && this.loop) {
  58319. this.stop();
  58320. this.play();
  58321. }
  58322. }
  58323. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58324. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58325. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58326. };
  58327. Sound.prototype.detachFromMesh = function () {
  58328. if (this._connectedMesh && this._registerFunc) {
  58329. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58330. this._registerFunc = null;
  58331. this._connectedMesh = null;
  58332. }
  58333. };
  58334. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58335. if (!node.getBoundingInfo) {
  58336. return;
  58337. }
  58338. var mesh = node;
  58339. var boundingInfo = mesh.getBoundingInfo();
  58340. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58341. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58342. this._updateDirection();
  58343. }
  58344. };
  58345. Sound.prototype.clone = function () {
  58346. var _this = this;
  58347. if (!this._streaming) {
  58348. var setBufferAndRun = function () {
  58349. if (_this._isReadyToPlay) {
  58350. clonedSound._audioBuffer = _this.getAudioBuffer();
  58351. clonedSound._isReadyToPlay = true;
  58352. if (clonedSound.autoplay) {
  58353. clonedSound.play();
  58354. }
  58355. }
  58356. else {
  58357. window.setTimeout(setBufferAndRun, 300);
  58358. }
  58359. };
  58360. var currentOptions = {
  58361. autoplay: this.autoplay, loop: this.loop,
  58362. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58363. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58364. refDistance: this.refDistance, distanceModel: this.distanceModel
  58365. };
  58366. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58367. if (this.useCustomAttenuation) {
  58368. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58369. }
  58370. clonedSound.setPosition(this._position);
  58371. clonedSound.setPlaybackRate(this._playbackRate);
  58372. setBufferAndRun();
  58373. return clonedSound;
  58374. }
  58375. else {
  58376. return null;
  58377. }
  58378. };
  58379. Sound.prototype.getAudioBuffer = function () {
  58380. return this._audioBuffer;
  58381. };
  58382. Sound.prototype.serialize = function () {
  58383. var serializationObject = {
  58384. name: this.name,
  58385. url: this.name,
  58386. autoplay: this.autoplay,
  58387. loop: this.loop,
  58388. volume: this._volume,
  58389. spatialSound: this.spatialSound,
  58390. maxDistance: this.maxDistance,
  58391. rolloffFactor: this.rolloffFactor,
  58392. refDistance: this.refDistance,
  58393. distanceModel: this.distanceModel,
  58394. playbackRate: this._playbackRate,
  58395. panningModel: this._panningModel,
  58396. soundTrackId: this.soundTrackId
  58397. };
  58398. if (this.spatialSound) {
  58399. if (this._connectedMesh)
  58400. serializationObject.connectedMeshId = this._connectedMesh.id;
  58401. serializationObject.position = this._position.asArray();
  58402. serializationObject.refDistance = this.refDistance;
  58403. serializationObject.distanceModel = this.distanceModel;
  58404. serializationObject.isDirectional = this._isDirectional;
  58405. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58406. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58407. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58408. serializationObject.coneOuterGain = this._coneOuterGain;
  58409. }
  58410. return serializationObject;
  58411. };
  58412. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58413. var soundName = parsedSound.name;
  58414. var soundUrl;
  58415. if (parsedSound.url) {
  58416. soundUrl = rootUrl + parsedSound.url;
  58417. }
  58418. else {
  58419. soundUrl = rootUrl + soundName;
  58420. }
  58421. var options = {
  58422. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58423. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58424. rolloffFactor: parsedSound.rolloffFactor,
  58425. refDistance: parsedSound.refDistance,
  58426. distanceModel: parsedSound.distanceModel,
  58427. playbackRate: parsedSound.playbackRate
  58428. };
  58429. var newSound;
  58430. if (!sourceSound) {
  58431. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58432. scene._addPendingData(newSound);
  58433. }
  58434. else {
  58435. var setBufferAndRun = function () {
  58436. if (sourceSound._isReadyToPlay) {
  58437. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58438. newSound._isReadyToPlay = true;
  58439. if (newSound.autoplay) {
  58440. newSound.play();
  58441. }
  58442. }
  58443. else {
  58444. window.setTimeout(setBufferAndRun, 300);
  58445. }
  58446. };
  58447. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58448. setBufferAndRun();
  58449. }
  58450. if (parsedSound.position) {
  58451. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58452. newSound.setPosition(soundPosition);
  58453. }
  58454. if (parsedSound.isDirectional) {
  58455. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58456. if (parsedSound.localDirectionToMesh) {
  58457. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58458. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58459. }
  58460. }
  58461. if (parsedSound.connectedMeshId) {
  58462. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58463. if (connectedMesh) {
  58464. newSound.attachToMesh(connectedMesh);
  58465. }
  58466. }
  58467. return newSound;
  58468. };
  58469. return Sound;
  58470. }());
  58471. BABYLON.Sound = Sound;
  58472. })(BABYLON || (BABYLON = {}));
  58473. //# sourceMappingURL=babylon.sound.js.map
  58474. "use strict";
  58475. var BABYLON;
  58476. (function (BABYLON) {
  58477. var SoundTrack = /** @class */ (function () {
  58478. function SoundTrack(scene, options) {
  58479. this.id = -1;
  58480. this._isMainTrack = false;
  58481. this._isInitialized = false;
  58482. this._scene = scene;
  58483. this.soundCollection = new Array();
  58484. this._options = options;
  58485. if (!this._isMainTrack) {
  58486. this._scene.soundTracks.push(this);
  58487. this.id = this._scene.soundTracks.length - 1;
  58488. }
  58489. }
  58490. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58491. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58492. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58493. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58494. if (this._options) {
  58495. if (this._options.volume) {
  58496. this._outputAudioNode.gain.value = this._options.volume;
  58497. }
  58498. if (this._options.mainTrack) {
  58499. this._isMainTrack = this._options.mainTrack;
  58500. }
  58501. }
  58502. this._isInitialized = true;
  58503. }
  58504. };
  58505. SoundTrack.prototype.dispose = function () {
  58506. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58507. if (this._connectedAnalyser) {
  58508. this._connectedAnalyser.stopDebugCanvas();
  58509. }
  58510. while (this.soundCollection.length) {
  58511. this.soundCollection[0].dispose();
  58512. }
  58513. if (this._outputAudioNode) {
  58514. this._outputAudioNode.disconnect();
  58515. }
  58516. this._outputAudioNode = null;
  58517. }
  58518. };
  58519. SoundTrack.prototype.AddSound = function (sound) {
  58520. if (!this._isInitialized) {
  58521. this._initializeSoundTrackAudioGraph();
  58522. }
  58523. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58524. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58525. }
  58526. if (sound.soundTrackId) {
  58527. if (sound.soundTrackId === -1) {
  58528. this._scene.mainSoundTrack.RemoveSound(sound);
  58529. }
  58530. else {
  58531. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58532. }
  58533. }
  58534. this.soundCollection.push(sound);
  58535. sound.soundTrackId = this.id;
  58536. };
  58537. SoundTrack.prototype.RemoveSound = function (sound) {
  58538. var index = this.soundCollection.indexOf(sound);
  58539. if (index !== -1) {
  58540. this.soundCollection.splice(index, 1);
  58541. }
  58542. };
  58543. SoundTrack.prototype.setVolume = function (newVolume) {
  58544. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58545. this._outputAudioNode.gain.value = newVolume;
  58546. }
  58547. };
  58548. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58549. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58550. for (var i = 0; i < this.soundCollection.length; i++) {
  58551. this.soundCollection[i].switchPanningModelToHRTF();
  58552. }
  58553. }
  58554. };
  58555. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58556. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58557. for (var i = 0; i < this.soundCollection.length; i++) {
  58558. this.soundCollection[i].switchPanningModelToEqualPower();
  58559. }
  58560. }
  58561. };
  58562. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58563. if (this._connectedAnalyser) {
  58564. this._connectedAnalyser.stopDebugCanvas();
  58565. }
  58566. this._connectedAnalyser = analyser;
  58567. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58568. this._outputAudioNode.disconnect();
  58569. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58570. }
  58571. };
  58572. return SoundTrack;
  58573. }());
  58574. BABYLON.SoundTrack = SoundTrack;
  58575. })(BABYLON || (BABYLON = {}));
  58576. //# sourceMappingURL=babylon.soundtrack.js.map
  58577. "use strict";
  58578. var BABYLON;
  58579. (function (BABYLON) {
  58580. var Analyser = /** @class */ (function () {
  58581. function Analyser(scene) {
  58582. this.SMOOTHING = 0.75;
  58583. this.FFT_SIZE = 512;
  58584. this.BARGRAPHAMPLITUDE = 256;
  58585. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58586. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58587. this._scene = scene;
  58588. this._audioEngine = BABYLON.Engine.audioEngine;
  58589. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58590. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58591. this._webAudioAnalyser.minDecibels = -140;
  58592. this._webAudioAnalyser.maxDecibels = 0;
  58593. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58594. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58595. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58596. }
  58597. }
  58598. Analyser.prototype.getFrequencyBinCount = function () {
  58599. if (this._audioEngine.canUseWebAudio) {
  58600. return this._webAudioAnalyser.frequencyBinCount;
  58601. }
  58602. else {
  58603. return 0;
  58604. }
  58605. };
  58606. Analyser.prototype.getByteFrequencyData = function () {
  58607. if (this._audioEngine.canUseWebAudio) {
  58608. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58609. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58610. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58611. }
  58612. return this._byteFreqs;
  58613. };
  58614. Analyser.prototype.getByteTimeDomainData = function () {
  58615. if (this._audioEngine.canUseWebAudio) {
  58616. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58617. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58618. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58619. }
  58620. return this._byteTime;
  58621. };
  58622. Analyser.prototype.getFloatFrequencyData = function () {
  58623. if (this._audioEngine.canUseWebAudio) {
  58624. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58625. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58626. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58627. }
  58628. return this._floatFreqs;
  58629. };
  58630. Analyser.prototype.drawDebugCanvas = function () {
  58631. var _this = this;
  58632. if (this._audioEngine.canUseWebAudio) {
  58633. if (!this._debugCanvas) {
  58634. this._debugCanvas = document.createElement("canvas");
  58635. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58636. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58637. this._debugCanvas.style.position = "absolute";
  58638. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58639. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58640. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58641. document.body.appendChild(this._debugCanvas);
  58642. this._registerFunc = function () {
  58643. _this.drawDebugCanvas();
  58644. };
  58645. this._scene.registerBeforeRender(this._registerFunc);
  58646. }
  58647. if (this._registerFunc && this._debugCanvasContext) {
  58648. var workingArray = this.getByteFrequencyData();
  58649. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58650. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58651. // Draw the frequency domain chart.
  58652. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58653. var value = workingArray[i];
  58654. var percent = value / this.BARGRAPHAMPLITUDE;
  58655. var height = this.DEBUGCANVASSIZE.height * percent;
  58656. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58657. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58658. var hue = i / this.getFrequencyBinCount() * 360;
  58659. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58660. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58661. }
  58662. }
  58663. }
  58664. };
  58665. Analyser.prototype.stopDebugCanvas = function () {
  58666. if (this._debugCanvas) {
  58667. if (this._registerFunc) {
  58668. this._scene.unregisterBeforeRender(this._registerFunc);
  58669. this._registerFunc = null;
  58670. }
  58671. document.body.removeChild(this._debugCanvas);
  58672. this._debugCanvas = null;
  58673. this._debugCanvasContext = null;
  58674. }
  58675. };
  58676. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58677. if (this._audioEngine.canUseWebAudio) {
  58678. inputAudioNode.connect(this._webAudioAnalyser);
  58679. this._webAudioAnalyser.connect(outputAudioNode);
  58680. }
  58681. };
  58682. Analyser.prototype.dispose = function () {
  58683. if (this._audioEngine.canUseWebAudio) {
  58684. this._webAudioAnalyser.disconnect();
  58685. }
  58686. };
  58687. return Analyser;
  58688. }());
  58689. BABYLON.Analyser = Analyser;
  58690. })(BABYLON || (BABYLON = {}));
  58691. //# sourceMappingURL=babylon.analyser.js.map
  58692. "use strict";
  58693. var BABYLON;
  58694. (function (BABYLON) {
  58695. var CubeTexture = /** @class */ (function (_super) {
  58696. __extends(CubeTexture, _super);
  58697. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58698. if (extensions === void 0) { extensions = null; }
  58699. if (noMipmap === void 0) { noMipmap = false; }
  58700. if (files === void 0) { files = null; }
  58701. if (onLoad === void 0) { onLoad = null; }
  58702. if (onError === void 0) { onError = null; }
  58703. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58704. if (prefiltered === void 0) { prefiltered = false; }
  58705. if (forcedExtension === void 0) { forcedExtension = null; }
  58706. var _this = _super.call(this, scene) || this;
  58707. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58708. /**
  58709. * Gets or sets the center of the bounding box associated with the cube texture
  58710. * It must define where the camera used to render the texture was set
  58711. */
  58712. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58713. _this.name = rootUrl;
  58714. _this.url = rootUrl;
  58715. _this._noMipmap = noMipmap;
  58716. _this.hasAlpha = false;
  58717. _this._format = format;
  58718. _this._prefiltered = prefiltered;
  58719. _this.isCube = true;
  58720. _this._textureMatrix = BABYLON.Matrix.Identity();
  58721. if (prefiltered) {
  58722. _this.gammaSpace = false;
  58723. }
  58724. if (!rootUrl && !files) {
  58725. return _this;
  58726. }
  58727. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58728. var lastDot = rootUrl.lastIndexOf(".");
  58729. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58730. var isDDS = (extension === ".dds");
  58731. if (!files) {
  58732. if (!isDDS && !extensions) {
  58733. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58734. }
  58735. files = [];
  58736. if (extensions) {
  58737. for (var index = 0; index < extensions.length; index++) {
  58738. files.push(rootUrl + extensions[index]);
  58739. }
  58740. }
  58741. }
  58742. _this._files = files;
  58743. if (!_this._texture) {
  58744. if (!scene.useDelayedTextureLoading) {
  58745. if (prefiltered) {
  58746. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58747. }
  58748. else {
  58749. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58750. }
  58751. }
  58752. else {
  58753. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58754. }
  58755. }
  58756. else if (onLoad) {
  58757. if (_this._texture.isReady) {
  58758. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58759. }
  58760. else {
  58761. _this._texture.onLoadedObservable.add(onLoad);
  58762. }
  58763. }
  58764. return _this;
  58765. }
  58766. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58767. get: function () {
  58768. return this._boundingBoxSize;
  58769. },
  58770. /**
  58771. * Gets or sets the size of the bounding box associated with the cube texture
  58772. * When defined, the cubemap will switch to local mode
  58773. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58774. * @example https://www.babylonjs-playground.com/#RNASML
  58775. */
  58776. set: function (value) {
  58777. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58778. return;
  58779. }
  58780. this._boundingBoxSize = value;
  58781. var scene = this.getScene();
  58782. if (scene) {
  58783. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58784. }
  58785. },
  58786. enumerable: true,
  58787. configurable: true
  58788. });
  58789. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58790. var rootUrlKey = "";
  58791. files.forEach(function (url) { return rootUrlKey += url; });
  58792. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58793. };
  58794. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58795. if (forcedExtension === void 0) { forcedExtension = null; }
  58796. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58797. };
  58798. // Methods
  58799. CubeTexture.prototype.delayLoad = function () {
  58800. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58801. return;
  58802. }
  58803. var scene = this.getScene();
  58804. if (!scene) {
  58805. return;
  58806. }
  58807. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58808. this._texture = this._getFromCache(this.url, this._noMipmap);
  58809. if (!this._texture) {
  58810. if (this._prefiltered) {
  58811. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58812. }
  58813. else {
  58814. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58815. }
  58816. }
  58817. };
  58818. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58819. return this._textureMatrix;
  58820. };
  58821. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58822. this._textureMatrix = value;
  58823. };
  58824. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58825. var texture = BABYLON.SerializationHelper.Parse(function () {
  58826. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58827. }, parsedTexture, scene);
  58828. // Local Cubemaps
  58829. if (parsedTexture.boundingBoxPosition) {
  58830. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58831. }
  58832. if (parsedTexture.boundingBoxSize) {
  58833. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58834. }
  58835. // Animations
  58836. if (parsedTexture.animations) {
  58837. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58838. var parsedAnimation = parsedTexture.animations[animationIndex];
  58839. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58840. }
  58841. }
  58842. return texture;
  58843. };
  58844. CubeTexture.prototype.clone = function () {
  58845. var _this = this;
  58846. return BABYLON.SerializationHelper.Clone(function () {
  58847. var scene = _this.getScene();
  58848. if (!scene) {
  58849. return _this;
  58850. }
  58851. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58852. }, this);
  58853. };
  58854. return CubeTexture;
  58855. }(BABYLON.BaseTexture));
  58856. BABYLON.CubeTexture = CubeTexture;
  58857. })(BABYLON || (BABYLON = {}));
  58858. //# sourceMappingURL=babylon.cubeTexture.js.map
  58859. "use strict";
  58860. var BABYLON;
  58861. (function (BABYLON) {
  58862. var RenderTargetTexture = /** @class */ (function (_super) {
  58863. __extends(RenderTargetTexture, _super);
  58864. /**
  58865. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58866. * or used a shadow, depth texture...
  58867. * @param name The friendly name of the texture
  58868. * @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)
  58869. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58870. * @param generateMipMaps True if mip maps need to be generated after render.
  58871. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58872. * @param type The type of the buffer in the RTT (int, half float, float...)
  58873. * @param isCube True if a cube texture needs to be created
  58874. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58875. * @param generateDepthBuffer True to generate a depth buffer
  58876. * @param generateStencilBuffer True to generate a stencil buffer
  58877. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58878. */
  58879. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58880. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58881. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58882. if (isCube === void 0) { isCube = false; }
  58883. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58884. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58885. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58886. if (isMulti === void 0) { isMulti = false; }
  58887. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58888. _this.isCube = isCube;
  58889. /**
  58890. * Use this list to define the list of mesh you want to render.
  58891. */
  58892. _this.renderList = new Array();
  58893. _this.renderParticles = true;
  58894. _this.renderSprites = false;
  58895. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58896. _this.ignoreCameraViewport = false;
  58897. // Events
  58898. /**
  58899. * An event triggered when the texture is unbind.
  58900. * @type {BABYLON.Observable}
  58901. */
  58902. _this.onBeforeBindObservable = new BABYLON.Observable();
  58903. /**
  58904. * An event triggered when the texture is unbind.
  58905. * @type {BABYLON.Observable}
  58906. */
  58907. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58908. /**
  58909. * An event triggered before rendering the texture
  58910. * @type {BABYLON.Observable}
  58911. */
  58912. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58913. /**
  58914. * An event triggered after rendering the texture
  58915. * @type {BABYLON.Observable}
  58916. */
  58917. _this.onAfterRenderObservable = new BABYLON.Observable();
  58918. /**
  58919. * An event triggered after the texture clear
  58920. * @type {BABYLON.Observable}
  58921. */
  58922. _this.onClearObservable = new BABYLON.Observable();
  58923. _this._currentRefreshId = -1;
  58924. _this._refreshRate = 1;
  58925. _this._samples = 1;
  58926. /**
  58927. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58928. * It must define where the camera used to render the texture is set
  58929. */
  58930. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58931. scene = _this.getScene();
  58932. if (!scene) {
  58933. return _this;
  58934. }
  58935. _this._engine = scene.getEngine();
  58936. _this.name = name;
  58937. _this.isRenderTarget = true;
  58938. _this._initialSizeParameter = size;
  58939. _this._processSizeParameter(size);
  58940. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58941. });
  58942. _this._generateMipMaps = generateMipMaps ? true : false;
  58943. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58944. // Rendering groups
  58945. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58946. if (isMulti) {
  58947. return _this;
  58948. }
  58949. _this._renderTargetOptions = {
  58950. generateMipMaps: generateMipMaps,
  58951. type: type,
  58952. samplingMode: samplingMode,
  58953. generateDepthBuffer: generateDepthBuffer,
  58954. generateStencilBuffer: generateStencilBuffer
  58955. };
  58956. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58957. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58958. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58959. }
  58960. if (isCube) {
  58961. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58962. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58963. _this._textureMatrix = BABYLON.Matrix.Identity();
  58964. }
  58965. else {
  58966. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58967. }
  58968. return _this;
  58969. }
  58970. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58971. get: function () {
  58972. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58973. },
  58974. enumerable: true,
  58975. configurable: true
  58976. });
  58977. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58978. get: function () {
  58979. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58980. },
  58981. enumerable: true,
  58982. configurable: true
  58983. });
  58984. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58985. get: function () {
  58986. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58987. },
  58988. enumerable: true,
  58989. configurable: true
  58990. });
  58991. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58992. set: function (callback) {
  58993. if (this._onAfterUnbindObserver) {
  58994. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58995. }
  58996. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58997. },
  58998. enumerable: true,
  58999. configurable: true
  59000. });
  59001. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59002. set: function (callback) {
  59003. if (this._onBeforeRenderObserver) {
  59004. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59005. }
  59006. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59007. },
  59008. enumerable: true,
  59009. configurable: true
  59010. });
  59011. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59012. set: function (callback) {
  59013. if (this._onAfterRenderObserver) {
  59014. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59015. }
  59016. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59017. },
  59018. enumerable: true,
  59019. configurable: true
  59020. });
  59021. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59022. set: function (callback) {
  59023. if (this._onClearObserver) {
  59024. this.onClearObservable.remove(this._onClearObserver);
  59025. }
  59026. this._onClearObserver = this.onClearObservable.add(callback);
  59027. },
  59028. enumerable: true,
  59029. configurable: true
  59030. });
  59031. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59032. get: function () {
  59033. return this._renderTargetOptions;
  59034. },
  59035. enumerable: true,
  59036. configurable: true
  59037. });
  59038. RenderTargetTexture.prototype._onRatioRescale = function () {
  59039. if (this._sizeRatio) {
  59040. this.resize(this._initialSizeParameter);
  59041. }
  59042. };
  59043. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59044. get: function () {
  59045. return this._boundingBoxSize;
  59046. },
  59047. /**
  59048. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59049. * When defined, the cubemap will switch to local mode
  59050. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59051. * @example https://www.babylonjs-playground.com/#RNASML
  59052. */
  59053. set: function (value) {
  59054. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59055. return;
  59056. }
  59057. this._boundingBoxSize = value;
  59058. var scene = this.getScene();
  59059. if (scene) {
  59060. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59061. }
  59062. },
  59063. enumerable: true,
  59064. configurable: true
  59065. });
  59066. /**
  59067. * Creates a depth stencil texture.
  59068. * This is only available in WebGL 2 or with the depth texture extension available.
  59069. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59070. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59071. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59072. */
  59073. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59074. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59075. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59076. if (generateStencil === void 0) { generateStencil = false; }
  59077. if (!this.getScene()) {
  59078. return;
  59079. }
  59080. var engine = this.getScene().getEngine();
  59081. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59082. bilinearFiltering: bilinearFiltering,
  59083. comparisonFunction: comparisonFunction,
  59084. generateStencil: generateStencil,
  59085. isCube: this.isCube
  59086. });
  59087. engine.setFrameBufferDepthStencilTexture(this);
  59088. };
  59089. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59090. if (size.ratio) {
  59091. this._sizeRatio = size.ratio;
  59092. this._size = {
  59093. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59094. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59095. };
  59096. }
  59097. else {
  59098. this._size = size;
  59099. }
  59100. };
  59101. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59102. get: function () {
  59103. return this._samples;
  59104. },
  59105. set: function (value) {
  59106. if (this._samples === value) {
  59107. return;
  59108. }
  59109. var scene = this.getScene();
  59110. if (!scene) {
  59111. return;
  59112. }
  59113. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59114. },
  59115. enumerable: true,
  59116. configurable: true
  59117. });
  59118. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59119. this._currentRefreshId = -1;
  59120. };
  59121. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59122. get: function () {
  59123. return this._refreshRate;
  59124. },
  59125. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59126. set: function (value) {
  59127. this._refreshRate = value;
  59128. this.resetRefreshCounter();
  59129. },
  59130. enumerable: true,
  59131. configurable: true
  59132. });
  59133. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59134. if (!this._postProcessManager) {
  59135. var scene = this.getScene();
  59136. if (!scene) {
  59137. return;
  59138. }
  59139. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59140. this._postProcesses = new Array();
  59141. }
  59142. this._postProcesses.push(postProcess);
  59143. this._postProcesses[0].autoClear = false;
  59144. };
  59145. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59146. if (!this._postProcesses) {
  59147. return;
  59148. }
  59149. if (dispose) {
  59150. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59151. var postProcess = _a[_i];
  59152. postProcess.dispose();
  59153. }
  59154. }
  59155. this._postProcesses = [];
  59156. };
  59157. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59158. if (!this._postProcesses) {
  59159. return;
  59160. }
  59161. var index = this._postProcesses.indexOf(postProcess);
  59162. if (index === -1) {
  59163. return;
  59164. }
  59165. this._postProcesses.splice(index, 1);
  59166. if (this._postProcesses.length > 0) {
  59167. this._postProcesses[0].autoClear = false;
  59168. }
  59169. };
  59170. RenderTargetTexture.prototype._shouldRender = function () {
  59171. if (this._currentRefreshId === -1) {
  59172. this._currentRefreshId = 1;
  59173. return true;
  59174. }
  59175. if (this.refreshRate === this._currentRefreshId) {
  59176. this._currentRefreshId = 1;
  59177. return true;
  59178. }
  59179. this._currentRefreshId++;
  59180. return false;
  59181. };
  59182. RenderTargetTexture.prototype.getRenderSize = function () {
  59183. if (this._size.width) {
  59184. return this._size.width;
  59185. }
  59186. return this._size;
  59187. };
  59188. RenderTargetTexture.prototype.getRenderWidth = function () {
  59189. if (this._size.width) {
  59190. return this._size.width;
  59191. }
  59192. return this._size;
  59193. };
  59194. RenderTargetTexture.prototype.getRenderHeight = function () {
  59195. if (this._size.width) {
  59196. return this._size.height;
  59197. }
  59198. return this._size;
  59199. };
  59200. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59201. get: function () {
  59202. return true;
  59203. },
  59204. enumerable: true,
  59205. configurable: true
  59206. });
  59207. RenderTargetTexture.prototype.scale = function (ratio) {
  59208. var newSize = this.getRenderSize() * ratio;
  59209. this.resize(newSize);
  59210. };
  59211. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59212. if (this.isCube) {
  59213. return this._textureMatrix;
  59214. }
  59215. return _super.prototype.getReflectionTextureMatrix.call(this);
  59216. };
  59217. RenderTargetTexture.prototype.resize = function (size) {
  59218. this.releaseInternalTexture();
  59219. var scene = this.getScene();
  59220. if (!scene) {
  59221. return;
  59222. }
  59223. this._processSizeParameter(size);
  59224. if (this.isCube) {
  59225. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59226. }
  59227. else {
  59228. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59229. }
  59230. };
  59231. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59232. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59233. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59234. var scene = this.getScene();
  59235. if (!scene) {
  59236. return;
  59237. }
  59238. var engine = scene.getEngine();
  59239. if (this.useCameraPostProcesses !== undefined) {
  59240. useCameraPostProcess = this.useCameraPostProcesses;
  59241. }
  59242. if (this._waitingRenderList) {
  59243. this.renderList = [];
  59244. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59245. var id = this._waitingRenderList[index];
  59246. var mesh_1 = scene.getMeshByID(id);
  59247. if (mesh_1) {
  59248. this.renderList.push(mesh_1);
  59249. }
  59250. }
  59251. delete this._waitingRenderList;
  59252. }
  59253. // Is predicate defined?
  59254. if (this.renderListPredicate) {
  59255. if (this.renderList) {
  59256. this.renderList.splice(0); // Clear previous renderList
  59257. }
  59258. else {
  59259. this.renderList = [];
  59260. }
  59261. var scene = this.getScene();
  59262. if (!scene) {
  59263. return;
  59264. }
  59265. var sceneMeshes = scene.meshes;
  59266. for (var index = 0; index < sceneMeshes.length; index++) {
  59267. var mesh = sceneMeshes[index];
  59268. if (this.renderListPredicate(mesh)) {
  59269. this.renderList.push(mesh);
  59270. }
  59271. }
  59272. }
  59273. this.onBeforeBindObservable.notifyObservers(this);
  59274. // Set custom projection.
  59275. // Needs to be before binding to prevent changing the aspect ratio.
  59276. var camera;
  59277. if (this.activeCamera) {
  59278. camera = this.activeCamera;
  59279. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59280. if (this.activeCamera !== scene.activeCamera) {
  59281. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59282. }
  59283. }
  59284. else {
  59285. camera = scene.activeCamera;
  59286. if (camera) {
  59287. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59288. }
  59289. }
  59290. // Prepare renderingManager
  59291. this._renderingManager.reset();
  59292. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59293. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59294. var sceneRenderId = scene.getRenderId();
  59295. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59296. var mesh = currentRenderList[meshIndex];
  59297. if (mesh) {
  59298. if (!mesh.isReady(this.refreshRate === 0)) {
  59299. this.resetRefreshCounter();
  59300. continue;
  59301. }
  59302. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59303. var isMasked = void 0;
  59304. if (!this.renderList && camera) {
  59305. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59306. }
  59307. else {
  59308. isMasked = false;
  59309. }
  59310. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59311. mesh._activate(sceneRenderId);
  59312. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59313. var subMesh = mesh.subMeshes[subIndex];
  59314. scene._activeIndices.addCount(subMesh.indexCount, false);
  59315. this._renderingManager.dispatch(subMesh, mesh);
  59316. }
  59317. }
  59318. }
  59319. }
  59320. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59321. var particleSystem = scene.particleSystems[particleIndex];
  59322. var emitter = particleSystem.emitter;
  59323. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59324. continue;
  59325. }
  59326. if (currentRenderList.indexOf(emitter) >= 0) {
  59327. this._renderingManager.dispatchParticles(particleSystem);
  59328. }
  59329. }
  59330. if (this.isCube) {
  59331. for (var face = 0; face < 6; face++) {
  59332. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59333. scene.incrementRenderId();
  59334. scene.resetCachedMaterial();
  59335. }
  59336. }
  59337. else {
  59338. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59339. }
  59340. this.onAfterUnbindObservable.notifyObservers(this);
  59341. if (scene.activeCamera) {
  59342. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59343. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59344. }
  59345. engine.setViewport(scene.activeCamera.viewport);
  59346. }
  59347. scene.resetCachedMaterial();
  59348. };
  59349. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59350. var minimum = 128;
  59351. var x = renderDimension * scale;
  59352. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59353. // Ensure we don't exceed the render dimension (while staying POT)
  59354. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59355. };
  59356. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59357. var _this = this;
  59358. if (!this._texture) {
  59359. return;
  59360. }
  59361. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59362. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59363. });
  59364. };
  59365. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59366. var scene = this.getScene();
  59367. if (!scene) {
  59368. return;
  59369. }
  59370. var engine = scene.getEngine();
  59371. if (!this._texture) {
  59372. return;
  59373. }
  59374. // Bind
  59375. if (this._postProcessManager) {
  59376. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59377. }
  59378. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59379. if (this._texture) {
  59380. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59381. }
  59382. }
  59383. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59384. // Clear
  59385. if (this.onClearObservable.hasObservers()) {
  59386. this.onClearObservable.notifyObservers(engine);
  59387. }
  59388. else {
  59389. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59390. }
  59391. if (!this._doNotChangeAspectRatio) {
  59392. scene.updateTransformMatrix(true);
  59393. }
  59394. // Render
  59395. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59396. if (this._postProcessManager) {
  59397. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59398. }
  59399. else if (useCameraPostProcess) {
  59400. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59401. }
  59402. if (!this._doNotChangeAspectRatio) {
  59403. scene.updateTransformMatrix(true);
  59404. }
  59405. // Dump ?
  59406. if (dumpForDebug) {
  59407. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59408. }
  59409. // Unbind
  59410. if (!this.isCube || faceIndex === 5) {
  59411. if (this.isCube) {
  59412. if (faceIndex === 5) {
  59413. engine.generateMipMapsForCubemap(this._texture);
  59414. }
  59415. }
  59416. this.unbindFrameBuffer(engine, faceIndex);
  59417. }
  59418. else {
  59419. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59420. }
  59421. };
  59422. /**
  59423. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59424. * This allowed control for front to back rendering or reversly depending of the special needs.
  59425. *
  59426. * @param renderingGroupId The rendering group id corresponding to its index
  59427. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59428. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59429. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59430. */
  59431. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59432. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59433. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59434. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59435. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59436. };
  59437. /**
  59438. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59439. *
  59440. * @param renderingGroupId The rendering group id corresponding to its index
  59441. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59442. */
  59443. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59444. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59445. };
  59446. RenderTargetTexture.prototype.clone = function () {
  59447. var textureSize = this.getSize();
  59448. 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);
  59449. // Base texture
  59450. newTexture.hasAlpha = this.hasAlpha;
  59451. newTexture.level = this.level;
  59452. // RenderTarget Texture
  59453. newTexture.coordinatesMode = this.coordinatesMode;
  59454. if (this.renderList) {
  59455. newTexture.renderList = this.renderList.slice(0);
  59456. }
  59457. return newTexture;
  59458. };
  59459. RenderTargetTexture.prototype.serialize = function () {
  59460. if (!this.name) {
  59461. return null;
  59462. }
  59463. var serializationObject = _super.prototype.serialize.call(this);
  59464. serializationObject.renderTargetSize = this.getRenderSize();
  59465. serializationObject.renderList = [];
  59466. if (this.renderList) {
  59467. for (var index = 0; index < this.renderList.length; index++) {
  59468. serializationObject.renderList.push(this.renderList[index].id);
  59469. }
  59470. }
  59471. return serializationObject;
  59472. };
  59473. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59474. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59475. var objBuffer = this.getInternalTexture();
  59476. var scene = this.getScene();
  59477. if (objBuffer && scene) {
  59478. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59479. }
  59480. };
  59481. RenderTargetTexture.prototype.dispose = function () {
  59482. if (this._postProcessManager) {
  59483. this._postProcessManager.dispose();
  59484. this._postProcessManager = null;
  59485. }
  59486. this.clearPostProcesses(true);
  59487. if (this._resizeObserver) {
  59488. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59489. this._resizeObserver = null;
  59490. }
  59491. this.renderList = null;
  59492. // Remove from custom render targets
  59493. var scene = this.getScene();
  59494. if (!scene) {
  59495. return;
  59496. }
  59497. var index = scene.customRenderTargets.indexOf(this);
  59498. if (index >= 0) {
  59499. scene.customRenderTargets.splice(index, 1);
  59500. }
  59501. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59502. var camera = _a[_i];
  59503. index = camera.customRenderTargets.indexOf(this);
  59504. if (index >= 0) {
  59505. camera.customRenderTargets.splice(index, 1);
  59506. }
  59507. }
  59508. _super.prototype.dispose.call(this);
  59509. };
  59510. RenderTargetTexture.prototype._rebuild = function () {
  59511. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59512. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59513. }
  59514. if (this._postProcessManager) {
  59515. this._postProcessManager._rebuild();
  59516. }
  59517. };
  59518. /**
  59519. * Clear the info related to rendering groups preventing retention point in material dispose.
  59520. */
  59521. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59522. if (this._renderingManager) {
  59523. this._renderingManager.freeRenderingGroups();
  59524. }
  59525. };
  59526. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59527. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59528. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59529. return RenderTargetTexture;
  59530. }(BABYLON.Texture));
  59531. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59532. })(BABYLON || (BABYLON = {}));
  59533. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59534. "use strict";
  59535. var BABYLON;
  59536. (function (BABYLON) {
  59537. ;
  59538. var MultiRenderTarget = /** @class */ (function (_super) {
  59539. __extends(MultiRenderTarget, _super);
  59540. function MultiRenderTarget(name, size, count, scene, options) {
  59541. var _this = this;
  59542. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59543. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59544. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59545. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59546. _this._engine = scene.getEngine();
  59547. if (!_this.isSupported) {
  59548. _this.dispose();
  59549. return;
  59550. }
  59551. var types = [];
  59552. var samplingModes = [];
  59553. for (var i = 0; i < count; i++) {
  59554. if (options && options.types && options.types[i] !== undefined) {
  59555. types.push(options.types[i]);
  59556. }
  59557. else {
  59558. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59559. }
  59560. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59561. samplingModes.push(options.samplingModes[i]);
  59562. }
  59563. else {
  59564. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59565. }
  59566. }
  59567. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59568. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59569. _this._size = size;
  59570. _this._multiRenderTargetOptions = {
  59571. samplingModes: samplingModes,
  59572. generateMipMaps: generateMipMaps,
  59573. generateDepthBuffer: generateDepthBuffer,
  59574. generateStencilBuffer: generateStencilBuffer,
  59575. generateDepthTexture: generateDepthTexture,
  59576. types: types,
  59577. textureCount: count
  59578. };
  59579. _this._createInternalTextures();
  59580. _this._createTextures();
  59581. return _this;
  59582. }
  59583. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59584. get: function () {
  59585. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59586. },
  59587. enumerable: true,
  59588. configurable: true
  59589. });
  59590. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59591. get: function () {
  59592. return this._textures;
  59593. },
  59594. enumerable: true,
  59595. configurable: true
  59596. });
  59597. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59598. get: function () {
  59599. return this._textures[this._textures.length - 1];
  59600. },
  59601. enumerable: true,
  59602. configurable: true
  59603. });
  59604. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59605. set: function (wrap) {
  59606. if (this._textures) {
  59607. for (var i = 0; i < this._textures.length; i++) {
  59608. this._textures[i].wrapU = wrap;
  59609. }
  59610. }
  59611. },
  59612. enumerable: true,
  59613. configurable: true
  59614. });
  59615. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59616. set: function (wrap) {
  59617. if (this._textures) {
  59618. for (var i = 0; i < this._textures.length; i++) {
  59619. this._textures[i].wrapV = wrap;
  59620. }
  59621. }
  59622. },
  59623. enumerable: true,
  59624. configurable: true
  59625. });
  59626. MultiRenderTarget.prototype._rebuild = function () {
  59627. this.releaseInternalTextures();
  59628. this._createInternalTextures();
  59629. for (var i = 0; i < this._internalTextures.length; i++) {
  59630. var texture = this._textures[i];
  59631. texture._texture = this._internalTextures[i];
  59632. }
  59633. // Keeps references to frame buffer and stencil/depth buffer
  59634. this._texture = this._internalTextures[0];
  59635. };
  59636. MultiRenderTarget.prototype._createInternalTextures = function () {
  59637. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59638. };
  59639. MultiRenderTarget.prototype._createTextures = function () {
  59640. this._textures = [];
  59641. for (var i = 0; i < this._internalTextures.length; i++) {
  59642. var texture = new BABYLON.Texture(null, this.getScene());
  59643. texture._texture = this._internalTextures[i];
  59644. this._textures.push(texture);
  59645. }
  59646. // Keeps references to frame buffer and stencil/depth buffer
  59647. this._texture = this._internalTextures[0];
  59648. };
  59649. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59650. get: function () {
  59651. return this._samples;
  59652. },
  59653. set: function (value) {
  59654. if (this._samples === value) {
  59655. return;
  59656. }
  59657. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59658. },
  59659. enumerable: true,
  59660. configurable: true
  59661. });
  59662. MultiRenderTarget.prototype.resize = function (size) {
  59663. this.releaseInternalTextures();
  59664. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59665. this._createInternalTextures();
  59666. };
  59667. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59668. var _this = this;
  59669. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59670. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59671. });
  59672. };
  59673. MultiRenderTarget.prototype.dispose = function () {
  59674. this.releaseInternalTextures();
  59675. _super.prototype.dispose.call(this);
  59676. };
  59677. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59678. if (!this._internalTextures) {
  59679. return;
  59680. }
  59681. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59682. if (this._internalTextures[i] !== undefined) {
  59683. this._internalTextures[i].dispose();
  59684. this._internalTextures.splice(i, 1);
  59685. }
  59686. }
  59687. };
  59688. return MultiRenderTarget;
  59689. }(BABYLON.RenderTargetTexture));
  59690. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59691. })(BABYLON || (BABYLON = {}));
  59692. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59693. "use strict";
  59694. var BABYLON;
  59695. (function (BABYLON) {
  59696. var MirrorTexture = /** @class */ (function (_super) {
  59697. __extends(MirrorTexture, _super);
  59698. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59699. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59700. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59701. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59702. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59703. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59704. _this._transformMatrix = BABYLON.Matrix.Zero();
  59705. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59706. _this._adaptiveBlurKernel = 0;
  59707. _this._blurKernelX = 0;
  59708. _this._blurKernelY = 0;
  59709. _this._blurRatio = 1.0;
  59710. _this.ignoreCameraViewport = true;
  59711. _this.onBeforeRenderObservable.add(function () {
  59712. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59713. _this._savedViewMatrix = scene.getViewMatrix();
  59714. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59715. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59716. scene.clipPlane = _this.mirrorPlane;
  59717. scene.getEngine().cullBackFaces = false;
  59718. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59719. });
  59720. _this.onAfterRenderObservable.add(function () {
  59721. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59722. scene.getEngine().cullBackFaces = true;
  59723. scene._mirroredCameraPosition = null;
  59724. delete scene.clipPlane;
  59725. });
  59726. return _this;
  59727. }
  59728. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59729. get: function () {
  59730. return this._blurRatio;
  59731. },
  59732. set: function (value) {
  59733. if (this._blurRatio === value) {
  59734. return;
  59735. }
  59736. this._blurRatio = value;
  59737. this._preparePostProcesses();
  59738. },
  59739. enumerable: true,
  59740. configurable: true
  59741. });
  59742. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59743. set: function (value) {
  59744. this._adaptiveBlurKernel = value;
  59745. this._autoComputeBlurKernel();
  59746. },
  59747. enumerable: true,
  59748. configurable: true
  59749. });
  59750. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59751. set: function (value) {
  59752. this.blurKernelX = value;
  59753. this.blurKernelY = value;
  59754. },
  59755. enumerable: true,
  59756. configurable: true
  59757. });
  59758. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59759. get: function () {
  59760. return this._blurKernelX;
  59761. },
  59762. set: function (value) {
  59763. if (this._blurKernelX === value) {
  59764. return;
  59765. }
  59766. this._blurKernelX = value;
  59767. this._preparePostProcesses();
  59768. },
  59769. enumerable: true,
  59770. configurable: true
  59771. });
  59772. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59773. get: function () {
  59774. return this._blurKernelY;
  59775. },
  59776. set: function (value) {
  59777. if (this._blurKernelY === value) {
  59778. return;
  59779. }
  59780. this._blurKernelY = value;
  59781. this._preparePostProcesses();
  59782. },
  59783. enumerable: true,
  59784. configurable: true
  59785. });
  59786. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59787. var engine = this.getScene().getEngine();
  59788. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59789. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59790. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59791. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59792. };
  59793. MirrorTexture.prototype._onRatioRescale = function () {
  59794. if (this._sizeRatio) {
  59795. this.resize(this._initialSizeParameter);
  59796. if (!this._adaptiveBlurKernel) {
  59797. this._preparePostProcesses();
  59798. }
  59799. }
  59800. if (this._adaptiveBlurKernel) {
  59801. this._autoComputeBlurKernel();
  59802. }
  59803. };
  59804. MirrorTexture.prototype._preparePostProcesses = function () {
  59805. this.clearPostProcesses(true);
  59806. if (this._blurKernelX && this._blurKernelY) {
  59807. var engine = this.getScene().getEngine();
  59808. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59809. 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);
  59810. this._blurX.autoClear = false;
  59811. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59812. this._blurX.inputTexture = this._texture;
  59813. }
  59814. else {
  59815. this._blurX.alwaysForcePOT = true;
  59816. }
  59817. 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);
  59818. this._blurY.autoClear = false;
  59819. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59820. this.addPostProcess(this._blurX);
  59821. this.addPostProcess(this._blurY);
  59822. }
  59823. else {
  59824. if (this._blurY) {
  59825. this.removePostProcess(this._blurY);
  59826. this._blurY.dispose();
  59827. this._blurY = null;
  59828. }
  59829. if (this._blurX) {
  59830. this.removePostProcess(this._blurX);
  59831. this._blurX.dispose();
  59832. this._blurX = null;
  59833. }
  59834. }
  59835. };
  59836. MirrorTexture.prototype.clone = function () {
  59837. var scene = this.getScene();
  59838. if (!scene) {
  59839. return this;
  59840. }
  59841. var textureSize = this.getSize();
  59842. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59843. // Base texture
  59844. newTexture.hasAlpha = this.hasAlpha;
  59845. newTexture.level = this.level;
  59846. // Mirror Texture
  59847. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59848. if (this.renderList) {
  59849. newTexture.renderList = this.renderList.slice(0);
  59850. }
  59851. return newTexture;
  59852. };
  59853. MirrorTexture.prototype.serialize = function () {
  59854. if (!this.name) {
  59855. return null;
  59856. }
  59857. var serializationObject = _super.prototype.serialize.call(this);
  59858. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59859. return serializationObject;
  59860. };
  59861. return MirrorTexture;
  59862. }(BABYLON.RenderTargetTexture));
  59863. BABYLON.MirrorTexture = MirrorTexture;
  59864. })(BABYLON || (BABYLON = {}));
  59865. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59866. "use strict";
  59867. var BABYLON;
  59868. (function (BABYLON) {
  59869. /**
  59870. * Creates a refraction texture used by refraction channel of the standard material.
  59871. * @param name the texture name
  59872. * @param size size of the underlying texture
  59873. * @param scene root scene
  59874. */
  59875. var RefractionTexture = /** @class */ (function (_super) {
  59876. __extends(RefractionTexture, _super);
  59877. function RefractionTexture(name, size, scene, generateMipMaps) {
  59878. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59879. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59880. _this.depth = 2.0;
  59881. _this.onBeforeRenderObservable.add(function () {
  59882. scene.clipPlane = _this.refractionPlane;
  59883. });
  59884. _this.onAfterRenderObservable.add(function () {
  59885. delete scene.clipPlane;
  59886. });
  59887. return _this;
  59888. }
  59889. RefractionTexture.prototype.clone = function () {
  59890. var scene = this.getScene();
  59891. if (!scene) {
  59892. return this;
  59893. }
  59894. var textureSize = this.getSize();
  59895. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59896. // Base texture
  59897. newTexture.hasAlpha = this.hasAlpha;
  59898. newTexture.level = this.level;
  59899. // Refraction Texture
  59900. newTexture.refractionPlane = this.refractionPlane.clone();
  59901. if (this.renderList) {
  59902. newTexture.renderList = this.renderList.slice(0);
  59903. }
  59904. newTexture.depth = this.depth;
  59905. return newTexture;
  59906. };
  59907. RefractionTexture.prototype.serialize = function () {
  59908. if (!this.name) {
  59909. return null;
  59910. }
  59911. var serializationObject = _super.prototype.serialize.call(this);
  59912. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59913. serializationObject.depth = this.depth;
  59914. return serializationObject;
  59915. };
  59916. return RefractionTexture;
  59917. }(BABYLON.RenderTargetTexture));
  59918. BABYLON.RefractionTexture = RefractionTexture;
  59919. })(BABYLON || (BABYLON = {}));
  59920. //# sourceMappingURL=babylon.refractionTexture.js.map
  59921. "use strict";
  59922. var BABYLON;
  59923. (function (BABYLON) {
  59924. var DynamicTexture = /** @class */ (function (_super) {
  59925. __extends(DynamicTexture, _super);
  59926. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59927. if (scene === void 0) { scene = null; }
  59928. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59929. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59930. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59931. _this.name = name;
  59932. _this._engine = _this.getScene().getEngine();
  59933. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59934. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59935. _this._generateMipMaps = generateMipMaps;
  59936. if (options.getContext) {
  59937. _this._canvas = options;
  59938. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59939. }
  59940. else {
  59941. _this._canvas = document.createElement("canvas");
  59942. if (options.width) {
  59943. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59944. }
  59945. else {
  59946. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59947. }
  59948. }
  59949. var textureSize = _this.getSize();
  59950. _this._canvas.width = textureSize.width;
  59951. _this._canvas.height = textureSize.height;
  59952. _this._context = _this._canvas.getContext("2d");
  59953. return _this;
  59954. }
  59955. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59956. get: function () {
  59957. return true;
  59958. },
  59959. enumerable: true,
  59960. configurable: true
  59961. });
  59962. DynamicTexture.prototype._recreate = function (textureSize) {
  59963. this._canvas.width = textureSize.width;
  59964. this._canvas.height = textureSize.height;
  59965. this.releaseInternalTexture();
  59966. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59967. };
  59968. DynamicTexture.prototype.scale = function (ratio) {
  59969. var textureSize = this.getSize();
  59970. textureSize.width *= ratio;
  59971. textureSize.height *= ratio;
  59972. this._recreate(textureSize);
  59973. };
  59974. DynamicTexture.prototype.scaleTo = function (width, height) {
  59975. var textureSize = this.getSize();
  59976. textureSize.width = width;
  59977. textureSize.height = height;
  59978. this._recreate(textureSize);
  59979. };
  59980. DynamicTexture.prototype.getContext = function () {
  59981. return this._context;
  59982. };
  59983. DynamicTexture.prototype.clear = function () {
  59984. var size = this.getSize();
  59985. this._context.fillRect(0, 0, size.width, size.height);
  59986. };
  59987. DynamicTexture.prototype.update = function (invertY) {
  59988. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59989. };
  59990. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59991. if (update === void 0) { update = true; }
  59992. var size = this.getSize();
  59993. if (clearColor) {
  59994. this._context.fillStyle = clearColor;
  59995. this._context.fillRect(0, 0, size.width, size.height);
  59996. }
  59997. this._context.font = font;
  59998. if (x === null || x === undefined) {
  59999. var textSize = this._context.measureText(text);
  60000. x = (size.width - textSize.width) / 2;
  60001. }
  60002. if (y === null || y === undefined) {
  60003. var fontSize = parseInt((font.replace(/\D/g, '')));
  60004. ;
  60005. y = (size.height / 2) + (fontSize / 3.65);
  60006. }
  60007. this._context.fillStyle = color;
  60008. this._context.fillText(text, x, y);
  60009. if (update) {
  60010. this.update(invertY);
  60011. }
  60012. };
  60013. DynamicTexture.prototype.clone = function () {
  60014. var scene = this.getScene();
  60015. if (!scene) {
  60016. return this;
  60017. }
  60018. var textureSize = this.getSize();
  60019. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  60020. // Base texture
  60021. newTexture.hasAlpha = this.hasAlpha;
  60022. newTexture.level = this.level;
  60023. // Dynamic Texture
  60024. newTexture.wrapU = this.wrapU;
  60025. newTexture.wrapV = this.wrapV;
  60026. return newTexture;
  60027. };
  60028. DynamicTexture.prototype._rebuild = function () {
  60029. this.update();
  60030. };
  60031. return DynamicTexture;
  60032. }(BABYLON.Texture));
  60033. BABYLON.DynamicTexture = DynamicTexture;
  60034. })(BABYLON || (BABYLON = {}));
  60035. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60036. "use strict";
  60037. var BABYLON;
  60038. (function (BABYLON) {
  60039. var VideoTexture = /** @class */ (function (_super) {
  60040. __extends(VideoTexture, _super);
  60041. /**
  60042. * Creates a video texture.
  60043. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60044. * @param {string | null} name optional name, will detect from video source, if not defined
  60045. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60046. * @param {BABYLON.Scene} scene is obviously the current scene.
  60047. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60048. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60049. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60050. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60051. */
  60052. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60053. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60054. if (invertY === void 0) { invertY = false; }
  60055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60056. if (settings === void 0) { settings = {
  60057. autoPlay: true,
  60058. loop: true,
  60059. autoUpdateTexture: true,
  60060. }; }
  60061. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60062. _this._createInternalTexture = function () {
  60063. if (_this._texture != null) {
  60064. return;
  60065. }
  60066. if (!_this._engine.needPOTTextures ||
  60067. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60068. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60069. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60070. }
  60071. else {
  60072. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60073. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60074. _this._generateMipMaps = false;
  60075. }
  60076. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60077. _this._texture.isReady = true;
  60078. _this._updateInternalTexture();
  60079. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60080. _this.onLoadObservable.notifyObservers(_this);
  60081. }
  60082. };
  60083. _this.reset = function () {
  60084. if (_this._texture == null) {
  60085. return;
  60086. }
  60087. _this._texture.dispose();
  60088. _this._texture = null;
  60089. };
  60090. _this._updateInternalTexture = function (e) {
  60091. if (_this._texture == null || !_this._texture.isReady) {
  60092. return;
  60093. }
  60094. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60095. return;
  60096. }
  60097. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60098. };
  60099. _this._engine = _this.getScene().getEngine();
  60100. _this._generateMipMaps = generateMipMaps;
  60101. _this._samplingMode = samplingMode;
  60102. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60103. _this.name = name || _this._getName(src);
  60104. _this.video = _this._getVideo(src);
  60105. if (settings.autoPlay !== undefined) {
  60106. _this.video.autoplay = settings.autoPlay;
  60107. }
  60108. if (settings.loop !== undefined) {
  60109. _this.video.loop = settings.loop;
  60110. }
  60111. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60112. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60113. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60114. _this.video.addEventListener("emptied", _this.reset);
  60115. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60116. _this._createInternalTexture();
  60117. }
  60118. return _this;
  60119. }
  60120. VideoTexture.prototype._getName = function (src) {
  60121. if (src instanceof HTMLVideoElement) {
  60122. return src.currentSrc;
  60123. }
  60124. if (typeof src === "object") {
  60125. return src.toString();
  60126. }
  60127. return src;
  60128. };
  60129. ;
  60130. VideoTexture.prototype._getVideo = function (src) {
  60131. if (src instanceof HTMLVideoElement) {
  60132. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60133. return src;
  60134. }
  60135. var video = document.createElement("video");
  60136. if (typeof src === "string") {
  60137. BABYLON.Tools.SetCorsBehavior(src, video);
  60138. video.src = src;
  60139. }
  60140. else {
  60141. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60142. src.forEach(function (url) {
  60143. var source = document.createElement("source");
  60144. source.src = url;
  60145. video.appendChild(source);
  60146. });
  60147. }
  60148. return video;
  60149. };
  60150. ;
  60151. /**
  60152. * Internal method to initiate `update`.
  60153. */
  60154. VideoTexture.prototype._rebuild = function () {
  60155. this.update();
  60156. };
  60157. /**
  60158. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60159. */
  60160. VideoTexture.prototype.update = function () {
  60161. if (!this.autoUpdateTexture) {
  60162. // Expecting user to call `updateTexture` manually
  60163. return;
  60164. }
  60165. this.updateTexture(true);
  60166. };
  60167. /**
  60168. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60169. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60170. */
  60171. VideoTexture.prototype.updateTexture = function (isVisible) {
  60172. if (!isVisible) {
  60173. return;
  60174. }
  60175. if (this.video.paused) {
  60176. return;
  60177. }
  60178. this._updateInternalTexture();
  60179. };
  60180. /**
  60181. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60182. * @param url New url.
  60183. */
  60184. VideoTexture.prototype.updateURL = function (url) {
  60185. this.video.src = url;
  60186. };
  60187. VideoTexture.prototype.dispose = function () {
  60188. _super.prototype.dispose.call(this);
  60189. this.video.removeEventListener("canplay", this._createInternalTexture);
  60190. this.video.removeEventListener("paused", this._updateInternalTexture);
  60191. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60192. this.video.removeEventListener("emptied", this.reset);
  60193. this.video.pause();
  60194. };
  60195. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60196. var video = document.createElement("video");
  60197. var constraintsDeviceId;
  60198. if (constraints && constraints.deviceId) {
  60199. constraintsDeviceId = {
  60200. exact: constraints.deviceId,
  60201. };
  60202. }
  60203. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60204. if (navigator.mediaDevices) {
  60205. navigator.mediaDevices.getUserMedia({ video: constraints })
  60206. .then(function (stream) {
  60207. if (video.mozSrcObject !== undefined) {
  60208. // hack for Firefox < 19
  60209. video.mozSrcObject = stream;
  60210. }
  60211. else {
  60212. video.srcObject = stream;
  60213. }
  60214. var onPlaying = function () {
  60215. if (onReady) {
  60216. onReady(new VideoTexture("video", video, scene, true, true));
  60217. }
  60218. video.removeEventListener("playing", onPlaying);
  60219. };
  60220. video.addEventListener("playing", onPlaying);
  60221. video.play();
  60222. })
  60223. .catch(function (err) {
  60224. BABYLON.Tools.Error(err.name);
  60225. });
  60226. }
  60227. else {
  60228. navigator.getUserMedia =
  60229. navigator.getUserMedia ||
  60230. navigator.webkitGetUserMedia ||
  60231. navigator.mozGetUserMedia ||
  60232. navigator.msGetUserMedia;
  60233. if (navigator.getUserMedia) {
  60234. navigator.getUserMedia({
  60235. video: {
  60236. deviceId: constraintsDeviceId,
  60237. width: {
  60238. min: (constraints && constraints.minWidth) || 256,
  60239. max: (constraints && constraints.maxWidth) || 640,
  60240. },
  60241. height: {
  60242. min: (constraints && constraints.minHeight) || 256,
  60243. max: (constraints && constraints.maxHeight) || 480,
  60244. },
  60245. },
  60246. }, function (stream) {
  60247. if (video.mozSrcObject !== undefined) {
  60248. // hack for Firefox < 19
  60249. video.mozSrcObject = stream;
  60250. }
  60251. else {
  60252. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60253. }
  60254. video.play();
  60255. if (onReady) {
  60256. onReady(new VideoTexture("video", video, scene, true, true));
  60257. }
  60258. }, function (e) {
  60259. BABYLON.Tools.Error(e.name);
  60260. });
  60261. }
  60262. }
  60263. };
  60264. return VideoTexture;
  60265. }(BABYLON.Texture));
  60266. BABYLON.VideoTexture = VideoTexture;
  60267. })(BABYLON || (BABYLON = {}));
  60268. //# sourceMappingURL=babylon.videoTexture.js.map
  60269. "use strict";
  60270. var BABYLON;
  60271. (function (BABYLON) {
  60272. var RawTexture = /** @class */ (function (_super) {
  60273. __extends(RawTexture, _super);
  60274. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60275. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60276. if (invertY === void 0) { invertY = false; }
  60277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60278. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60279. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60280. _this.format = format;
  60281. _this._engine = scene.getEngine();
  60282. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60283. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60284. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60285. return _this;
  60286. }
  60287. RawTexture.prototype.update = function (data) {
  60288. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60289. };
  60290. // Statics
  60291. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60292. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60293. if (invertY === void 0) { invertY = false; }
  60294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60295. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60296. };
  60297. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60298. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60299. if (invertY === void 0) { invertY = false; }
  60300. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60301. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60302. };
  60303. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60304. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60305. if (invertY === void 0) { invertY = false; }
  60306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60307. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60308. };
  60309. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60310. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60311. if (invertY === void 0) { invertY = false; }
  60312. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60313. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60314. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60315. };
  60316. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60317. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60318. if (invertY === void 0) { invertY = false; }
  60319. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60320. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60321. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60322. };
  60323. return RawTexture;
  60324. }(BABYLON.Texture));
  60325. BABYLON.RawTexture = RawTexture;
  60326. })(BABYLON || (BABYLON = {}));
  60327. //# sourceMappingURL=babylon.rawTexture.js.map
  60328. "use strict";
  60329. var BABYLON;
  60330. (function (BABYLON) {
  60331. /**
  60332. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60333. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60334. */
  60335. var PostProcess = /** @class */ (function () {
  60336. /**
  60337. * Creates a new instance of @see PostProcess
  60338. * @param name The name of the PostProcess.
  60339. * @param fragmentUrl The url of the fragment shader to be used.
  60340. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60341. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60342. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60343. * @param camera The camera to apply the render pass to.
  60344. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60345. * @param engine The engine which the post process will be applied. (default: current engine)
  60346. * @param reusable If the post process can be reused on the same frame. (default: false)
  60347. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60348. * @param textureType Type of textures used when performing the post process. (default: 0)
  60349. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60350. * @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
  60351. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60352. */
  60353. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60355. if (defines === void 0) { defines = null; }
  60356. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60357. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60358. if (blockCompilation === void 0) { blockCompilation = false; }
  60359. this.name = name;
  60360. /**
  60361. * Width of the texture to apply the post process on
  60362. */
  60363. this.width = -1;
  60364. /**
  60365. * Height of the texture to apply the post process on
  60366. */
  60367. this.height = -1;
  60368. /**
  60369. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60370. */
  60371. this._outputTexture = null;
  60372. /**
  60373. * If the buffer needs to be cleared before applying the post process. (default: true)
  60374. * Should be set to false if shader will overwrite all previous pixels.
  60375. */
  60376. this.autoClear = true;
  60377. /**
  60378. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60379. */
  60380. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60381. /**
  60382. * Animations to be used for the post processing
  60383. */
  60384. this.animations = new Array();
  60385. /**
  60386. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60387. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60388. */
  60389. this.enablePixelPerfectMode = false;
  60390. /**
  60391. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60392. */
  60393. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60394. /**
  60395. * Force textures to be a power of two (default: false)
  60396. */
  60397. this.alwaysForcePOT = false;
  60398. /**
  60399. * Number of sample textures (default: 1)
  60400. */
  60401. this.samples = 1;
  60402. /**
  60403. * Modify the scale of the post process to be the same as the viewport (default: false)
  60404. */
  60405. this.adaptScaleToCurrentViewport = false;
  60406. this._reusable = false;
  60407. /**
  60408. * Smart array of input and output textures for the post process.
  60409. */
  60410. this._textures = new BABYLON.SmartArray(2);
  60411. /**
  60412. * The index in _textures that corresponds to the output texture.
  60413. */
  60414. this._currentRenderTextureInd = 0;
  60415. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60416. this._texelSize = BABYLON.Vector2.Zero();
  60417. // Events
  60418. /**
  60419. * An event triggered when the postprocess is activated.
  60420. * @type {BABYLON.Observable}
  60421. */
  60422. this.onActivateObservable = new BABYLON.Observable();
  60423. /**
  60424. * An event triggered when the postprocess changes its size.
  60425. * @type {BABYLON.Observable}
  60426. */
  60427. this.onSizeChangedObservable = new BABYLON.Observable();
  60428. /**
  60429. * An event triggered when the postprocess applies its effect.
  60430. * @type {BABYLON.Observable}
  60431. */
  60432. this.onApplyObservable = new BABYLON.Observable();
  60433. /**
  60434. * An event triggered before rendering the postprocess
  60435. * @type {BABYLON.Observable}
  60436. */
  60437. this.onBeforeRenderObservable = new BABYLON.Observable();
  60438. /**
  60439. * An event triggered after rendering the postprocess
  60440. * @type {BABYLON.Observable}
  60441. */
  60442. this.onAfterRenderObservable = new BABYLON.Observable();
  60443. if (camera != null) {
  60444. this._camera = camera;
  60445. this._scene = camera.getScene();
  60446. camera.attachPostProcess(this);
  60447. this._engine = this._scene.getEngine();
  60448. this._scene.postProcesses.push(this);
  60449. }
  60450. else if (engine) {
  60451. this._engine = engine;
  60452. this._engine.postProcesses.push(this);
  60453. }
  60454. this._options = options;
  60455. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60456. this._reusable = reusable || false;
  60457. this._textureType = textureType;
  60458. this._samplers = samplers || [];
  60459. this._samplers.push("textureSampler");
  60460. this._fragmentUrl = fragmentUrl;
  60461. this._vertexUrl = vertexUrl;
  60462. this._parameters = parameters || [];
  60463. this._parameters.push("scale");
  60464. this._indexParameters = indexParameters;
  60465. if (!blockCompilation) {
  60466. this.updateEffect(defines);
  60467. }
  60468. }
  60469. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60470. /**
  60471. * A function that is added to the onActivateObservable
  60472. */
  60473. set: function (callback) {
  60474. if (this._onActivateObserver) {
  60475. this.onActivateObservable.remove(this._onActivateObserver);
  60476. }
  60477. if (callback) {
  60478. this._onActivateObserver = this.onActivateObservable.add(callback);
  60479. }
  60480. },
  60481. enumerable: true,
  60482. configurable: true
  60483. });
  60484. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60485. /**
  60486. * A function that is added to the onSizeChangedObservable
  60487. */
  60488. set: function (callback) {
  60489. if (this._onSizeChangedObserver) {
  60490. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60491. }
  60492. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60493. },
  60494. enumerable: true,
  60495. configurable: true
  60496. });
  60497. Object.defineProperty(PostProcess.prototype, "onApply", {
  60498. /**
  60499. * A function that is added to the onApplyObservable
  60500. */
  60501. set: function (callback) {
  60502. if (this._onApplyObserver) {
  60503. this.onApplyObservable.remove(this._onApplyObserver);
  60504. }
  60505. this._onApplyObserver = this.onApplyObservable.add(callback);
  60506. },
  60507. enumerable: true,
  60508. configurable: true
  60509. });
  60510. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60511. /**
  60512. * A function that is added to the onBeforeRenderObservable
  60513. */
  60514. set: function (callback) {
  60515. if (this._onBeforeRenderObserver) {
  60516. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60517. }
  60518. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60519. },
  60520. enumerable: true,
  60521. configurable: true
  60522. });
  60523. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60524. /**
  60525. * A function that is added to the onAfterRenderObservable
  60526. */
  60527. set: function (callback) {
  60528. if (this._onAfterRenderObserver) {
  60529. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60530. }
  60531. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60532. },
  60533. enumerable: true,
  60534. configurable: true
  60535. });
  60536. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60537. /**
  60538. * 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
  60539. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60540. */
  60541. get: function () {
  60542. return this._textures.data[this._currentRenderTextureInd];
  60543. },
  60544. set: function (value) {
  60545. this._forcedOutputTexture = value;
  60546. },
  60547. enumerable: true,
  60548. configurable: true
  60549. });
  60550. /**
  60551. * Gets the camera which post process is applied to.
  60552. * @returns The camera the post process is applied to.
  60553. */
  60554. PostProcess.prototype.getCamera = function () {
  60555. return this._camera;
  60556. };
  60557. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60558. /**
  60559. * Gets the texel size of the postprocess.
  60560. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60561. */
  60562. get: function () {
  60563. if (this._shareOutputWithPostProcess) {
  60564. return this._shareOutputWithPostProcess.texelSize;
  60565. }
  60566. if (this._forcedOutputTexture) {
  60567. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60568. }
  60569. return this._texelSize;
  60570. },
  60571. enumerable: true,
  60572. configurable: true
  60573. });
  60574. /**
  60575. * Gets the engine which this post process belongs to.
  60576. * @returns The engine the post process was enabled with.
  60577. */
  60578. PostProcess.prototype.getEngine = function () {
  60579. return this._engine;
  60580. };
  60581. /**
  60582. * The effect that is created when initializing the post process.
  60583. * @returns The created effect corrisponding the the postprocess.
  60584. */
  60585. PostProcess.prototype.getEffect = function () {
  60586. return this._effect;
  60587. };
  60588. /**
  60589. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60590. * @param postProcess The post process to share the output with.
  60591. * @returns This post process.
  60592. */
  60593. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60594. this._disposeTextures();
  60595. this._shareOutputWithPostProcess = postProcess;
  60596. return this;
  60597. };
  60598. /**
  60599. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60600. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60601. */
  60602. PostProcess.prototype.useOwnOutput = function () {
  60603. if (this._textures.length == 0) {
  60604. this._textures = new BABYLON.SmartArray(2);
  60605. }
  60606. this._shareOutputWithPostProcess = null;
  60607. };
  60608. /**
  60609. * Updates the effect with the current post process compile time values and recompiles the shader.
  60610. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60611. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60612. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60613. * @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
  60614. * @param onCompiled Called when the shader has been compiled.
  60615. * @param onError Called if there is an error when compiling a shader.
  60616. */
  60617. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60618. if (defines === void 0) { defines = null; }
  60619. if (uniforms === void 0) { uniforms = null; }
  60620. if (samplers === void 0) { samplers = null; }
  60621. 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);
  60622. };
  60623. /**
  60624. * The post process is reusable if it can be used multiple times within one frame.
  60625. * @returns If the post process is reusable
  60626. */
  60627. PostProcess.prototype.isReusable = function () {
  60628. return this._reusable;
  60629. };
  60630. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60631. PostProcess.prototype.markTextureDirty = function () {
  60632. this.width = -1;
  60633. };
  60634. /**
  60635. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60636. * 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.
  60637. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60638. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60639. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60640. * @returns The target texture that was bound to be written to.
  60641. */
  60642. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60643. var _this = this;
  60644. if (sourceTexture === void 0) { sourceTexture = null; }
  60645. camera = camera || this._camera;
  60646. var scene = camera.getScene();
  60647. var engine = scene.getEngine();
  60648. var maxSize = engine.getCaps().maxTextureSize;
  60649. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60650. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60651. // 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
  60652. var webVRCamera = camera.parent;
  60653. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60654. requiredWidth /= 2;
  60655. }
  60656. var desiredWidth = (this._options.width || requiredWidth);
  60657. var desiredHeight = this._options.height || requiredHeight;
  60658. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60659. if (this.adaptScaleToCurrentViewport) {
  60660. var currentViewport = engine.currentViewport;
  60661. if (currentViewport) {
  60662. desiredWidth *= currentViewport.width;
  60663. desiredHeight *= currentViewport.height;
  60664. }
  60665. }
  60666. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60667. if (!this._options.width) {
  60668. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60669. }
  60670. if (!this._options.height) {
  60671. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60672. }
  60673. }
  60674. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60675. if (this._textures.length > 0) {
  60676. for (var i = 0; i < this._textures.length; i++) {
  60677. this._engine._releaseTexture(this._textures.data[i]);
  60678. }
  60679. this._textures.reset();
  60680. }
  60681. this.width = desiredWidth;
  60682. this.height = desiredHeight;
  60683. var textureSize = { width: this.width, height: this.height };
  60684. var textureOptions = {
  60685. generateMipMaps: false,
  60686. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60687. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60688. samplingMode: this.renderTargetSamplingMode,
  60689. type: this._textureType
  60690. };
  60691. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60692. if (this._reusable) {
  60693. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60694. }
  60695. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60696. this.onSizeChangedObservable.notifyObservers(this);
  60697. }
  60698. this._textures.forEach(function (texture) {
  60699. if (texture.samples !== _this.samples) {
  60700. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60701. }
  60702. });
  60703. }
  60704. var target;
  60705. if (this._shareOutputWithPostProcess) {
  60706. target = this._shareOutputWithPostProcess.inputTexture;
  60707. }
  60708. else if (this._forcedOutputTexture) {
  60709. target = this._forcedOutputTexture;
  60710. this.width = this._forcedOutputTexture.width;
  60711. this.height = this._forcedOutputTexture.height;
  60712. }
  60713. else {
  60714. target = this.inputTexture;
  60715. }
  60716. // Bind the input of this post process to be used as the output of the previous post process.
  60717. if (this.enablePixelPerfectMode) {
  60718. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60719. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60720. }
  60721. else {
  60722. this._scaleRatio.copyFromFloats(1, 1);
  60723. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60724. }
  60725. this.onActivateObservable.notifyObservers(camera);
  60726. // Clear
  60727. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60728. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60729. }
  60730. if (this._reusable) {
  60731. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60732. }
  60733. return target;
  60734. };
  60735. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60736. /**
  60737. * If the post process is supported.
  60738. */
  60739. get: function () {
  60740. return this._effect.isSupported;
  60741. },
  60742. enumerable: true,
  60743. configurable: true
  60744. });
  60745. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60746. /**
  60747. * The aspect ratio of the output texture.
  60748. */
  60749. get: function () {
  60750. if (this._shareOutputWithPostProcess) {
  60751. return this._shareOutputWithPostProcess.aspectRatio;
  60752. }
  60753. if (this._forcedOutputTexture) {
  60754. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60755. }
  60756. return this.width / this.height;
  60757. },
  60758. enumerable: true,
  60759. configurable: true
  60760. });
  60761. /**
  60762. * Get a value indicating if the post-process is ready to be used
  60763. * @returns true if the post-process is ready (shader is compiled)
  60764. */
  60765. PostProcess.prototype.isReady = function () {
  60766. return this._effect && this._effect.isReady();
  60767. };
  60768. /**
  60769. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60770. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60771. */
  60772. PostProcess.prototype.apply = function () {
  60773. // Check
  60774. if (!this._effect || !this._effect.isReady())
  60775. return null;
  60776. // States
  60777. this._engine.enableEffect(this._effect);
  60778. this._engine.setState(false);
  60779. this._engine.setDepthBuffer(false);
  60780. this._engine.setDepthWrite(false);
  60781. // Alpha
  60782. this._engine.setAlphaMode(this.alphaMode);
  60783. if (this.alphaConstants) {
  60784. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60785. }
  60786. // Bind the output texture of the preivous post process as the input to this post process.
  60787. var source;
  60788. if (this._shareOutputWithPostProcess) {
  60789. source = this._shareOutputWithPostProcess.inputTexture;
  60790. }
  60791. else if (this._forcedOutputTexture) {
  60792. source = this._forcedOutputTexture;
  60793. }
  60794. else {
  60795. source = this.inputTexture;
  60796. }
  60797. this._effect._bindTexture("textureSampler", source);
  60798. // Parameters
  60799. this._effect.setVector2("scale", this._scaleRatio);
  60800. this.onApplyObservable.notifyObservers(this._effect);
  60801. return this._effect;
  60802. };
  60803. PostProcess.prototype._disposeTextures = function () {
  60804. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60805. return;
  60806. }
  60807. if (this._textures.length > 0) {
  60808. for (var i = 0; i < this._textures.length; i++) {
  60809. this._engine._releaseTexture(this._textures.data[i]);
  60810. }
  60811. }
  60812. this._textures.dispose();
  60813. };
  60814. /**
  60815. * Disposes the post process.
  60816. * @param camera The camera to dispose the post process on.
  60817. */
  60818. PostProcess.prototype.dispose = function (camera) {
  60819. camera = camera || this._camera;
  60820. this._disposeTextures();
  60821. if (this._scene) {
  60822. var index_1 = this._scene.postProcesses.indexOf(this);
  60823. if (index_1 !== -1) {
  60824. this._scene.postProcesses.splice(index_1, 1);
  60825. }
  60826. }
  60827. else {
  60828. var index_2 = this._engine.postProcesses.indexOf(this);
  60829. if (index_2 !== -1) {
  60830. this._engine.postProcesses.splice(index_2, 1);
  60831. }
  60832. }
  60833. if (!camera) {
  60834. return;
  60835. }
  60836. camera.detachPostProcess(this);
  60837. var index = camera._postProcesses.indexOf(this);
  60838. if (index === 0 && camera._postProcesses.length > 0) {
  60839. var firstPostProcess = this._camera._getFirstPostProcess();
  60840. if (firstPostProcess) {
  60841. firstPostProcess.markTextureDirty();
  60842. }
  60843. }
  60844. this.onActivateObservable.clear();
  60845. this.onAfterRenderObservable.clear();
  60846. this.onApplyObservable.clear();
  60847. this.onBeforeRenderObservable.clear();
  60848. this.onSizeChangedObservable.clear();
  60849. };
  60850. return PostProcess;
  60851. }());
  60852. BABYLON.PostProcess = PostProcess;
  60853. })(BABYLON || (BABYLON = {}));
  60854. //# sourceMappingURL=babylon.postProcess.js.map
  60855. "use strict";
  60856. var BABYLON;
  60857. (function (BABYLON) {
  60858. var PassPostProcess = /** @class */ (function (_super) {
  60859. __extends(PassPostProcess, _super);
  60860. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60861. if (camera === void 0) { camera = null; }
  60862. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60863. if (blockCompilation === void 0) { blockCompilation = false; }
  60864. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60865. }
  60866. return PassPostProcess;
  60867. }(BABYLON.PostProcess));
  60868. BABYLON.PassPostProcess = PassPostProcess;
  60869. })(BABYLON || (BABYLON = {}));
  60870. //# sourceMappingURL=babylon.passPostProcess.js.map
  60871. "use strict";
  60872. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60873. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60874. s = arguments[i];
  60875. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60876. t[p] = s[p];
  60877. }
  60878. return t;
  60879. };
  60880. var BABYLON;
  60881. (function (BABYLON) {
  60882. /**
  60883. * Default implementation of @see IShadowGenerator.
  60884. * This is the main object responsible of generating shadows in the framework.
  60885. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60886. */
  60887. var ShadowGenerator = /** @class */ (function () {
  60888. /**
  60889. * Creates a ShadowGenerator object.
  60890. * A ShadowGenerator is the required tool to use the shadows.
  60891. * Each light casting shadows needs to use its own ShadowGenerator.
  60892. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60893. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60894. * @param light The light object generating the shadows.
  60895. * @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.
  60896. */
  60897. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60898. this._bias = 0.00005;
  60899. this._normalBias = 0;
  60900. this._blurBoxOffset = 1;
  60901. this._blurScale = 2;
  60902. this._blurKernel = 1;
  60903. this._useKernelBlur = false;
  60904. this._filter = ShadowGenerator.FILTER_NONE;
  60905. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  60906. this._contactHardeningLightSizeUVRatio = 0.1;
  60907. this._darkness = 0;
  60908. this._transparencyShadow = false;
  60909. /**
  60910. * Controls the extent to which the shadows fade out at the edge of the frustum
  60911. * Used only by directionals and spots
  60912. */
  60913. this.frustumEdgeFalloff = 0;
  60914. /**
  60915. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60916. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60917. * It might on the other hand introduce peter panning.
  60918. */
  60919. this.forceBackFacesOnly = false;
  60920. this._lightDirection = BABYLON.Vector3.Zero();
  60921. this._viewMatrix = BABYLON.Matrix.Zero();
  60922. this._projectionMatrix = BABYLON.Matrix.Zero();
  60923. this._transformMatrix = BABYLON.Matrix.Zero();
  60924. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60925. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60926. this._currentFaceIndex = 0;
  60927. this._currentFaceIndexCache = 0;
  60928. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60929. this._mapSize = mapSize;
  60930. this._light = light;
  60931. this._scene = light.getScene();
  60932. light._shadowGenerator = this;
  60933. // Texture type fallback from float to int if not supported.
  60934. var caps = this._scene.getEngine().getCaps();
  60935. if (!useFullFloatFirst) {
  60936. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60937. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60938. }
  60939. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60940. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60941. }
  60942. else {
  60943. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60944. }
  60945. }
  60946. else {
  60947. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60948. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60949. }
  60950. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60951. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60952. }
  60953. else {
  60954. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60955. }
  60956. }
  60957. this._initializeGenerator();
  60958. this._applyFilterValues();
  60959. }
  60960. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60961. /**
  60962. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  60963. */
  60964. get: function () {
  60965. return this._bias;
  60966. },
  60967. /**
  60968. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  60969. */
  60970. set: function (bias) {
  60971. this._bias = bias;
  60972. },
  60973. enumerable: true,
  60974. configurable: true
  60975. });
  60976. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  60977. /**
  60978. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60979. */
  60980. get: function () {
  60981. return this._normalBias;
  60982. },
  60983. /**
  60984. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60985. */
  60986. set: function (normalBias) {
  60987. this._normalBias = normalBias;
  60988. },
  60989. enumerable: true,
  60990. configurable: true
  60991. });
  60992. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60993. /**
  60994. * Gets the blur box offset: offset applied during the blur pass.
  60995. * Only usefull if useKernelBlur = false
  60996. */
  60997. get: function () {
  60998. return this._blurBoxOffset;
  60999. },
  61000. /**
  61001. * Sets the blur box offset: offset applied during the blur pass.
  61002. * Only usefull if useKernelBlur = false
  61003. */
  61004. set: function (value) {
  61005. if (this._blurBoxOffset === value) {
  61006. return;
  61007. }
  61008. this._blurBoxOffset = value;
  61009. this._disposeBlurPostProcesses();
  61010. },
  61011. enumerable: true,
  61012. configurable: true
  61013. });
  61014. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  61015. /**
  61016. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  61017. * 2 means half of the size.
  61018. */
  61019. get: function () {
  61020. return this._blurScale;
  61021. },
  61022. /**
  61023. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  61024. * 2 means half of the size.
  61025. */
  61026. set: function (value) {
  61027. if (this._blurScale === value) {
  61028. return;
  61029. }
  61030. this._blurScale = value;
  61031. this._disposeBlurPostProcesses();
  61032. },
  61033. enumerable: true,
  61034. configurable: true
  61035. });
  61036. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61037. /**
  61038. * Gets the blur kernel: kernel size of the blur pass.
  61039. * Only usefull if useKernelBlur = true
  61040. */
  61041. get: function () {
  61042. return this._blurKernel;
  61043. },
  61044. /**
  61045. * Sets the blur kernel: kernel size of the blur pass.
  61046. * Only usefull if useKernelBlur = true
  61047. */
  61048. set: function (value) {
  61049. if (this._blurKernel === value) {
  61050. return;
  61051. }
  61052. this._blurKernel = value;
  61053. this._disposeBlurPostProcesses();
  61054. },
  61055. enumerable: true,
  61056. configurable: true
  61057. });
  61058. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61059. /**
  61060. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61061. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61062. */
  61063. get: function () {
  61064. return this._useKernelBlur;
  61065. },
  61066. /**
  61067. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61068. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61069. */
  61070. set: function (value) {
  61071. if (this._useKernelBlur === value) {
  61072. return;
  61073. }
  61074. this._useKernelBlur = value;
  61075. this._disposeBlurPostProcesses();
  61076. },
  61077. enumerable: true,
  61078. configurable: true
  61079. });
  61080. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61081. /**
  61082. * Gets the depth scale used in ESM mode.
  61083. */
  61084. get: function () {
  61085. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61086. },
  61087. /**
  61088. * Sets the depth scale used in ESM mode.
  61089. * This can override the scale stored on the light.
  61090. */
  61091. set: function (value) {
  61092. this._depthScale = value;
  61093. },
  61094. enumerable: true,
  61095. configurable: true
  61096. });
  61097. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61098. /**
  61099. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61100. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61101. */
  61102. get: function () {
  61103. return this._filter;
  61104. },
  61105. /**
  61106. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61107. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61108. */
  61109. set: function (value) {
  61110. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61111. if (this._light.needCube()) {
  61112. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61113. this.useExponentialShadowMap = true;
  61114. return;
  61115. }
  61116. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61117. this.useCloseExponentialShadowMap = true;
  61118. return;
  61119. }
  61120. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61121. this.usePoissonSampling = true;
  61122. return;
  61123. }
  61124. }
  61125. // Weblg1 fallback for PCF.
  61126. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61127. if (this._scene.getEngine().webGLVersion === 1) {
  61128. this.usePoissonSampling = true;
  61129. return;
  61130. }
  61131. }
  61132. if (this._filter === value) {
  61133. return;
  61134. }
  61135. this._filter = value;
  61136. this._disposeBlurPostProcesses();
  61137. this._applyFilterValues();
  61138. this._light._markMeshesAsLightDirty();
  61139. },
  61140. enumerable: true,
  61141. configurable: true
  61142. });
  61143. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61144. /**
  61145. * Gets if the current filter is set to Poisson Sampling.
  61146. */
  61147. get: function () {
  61148. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61149. },
  61150. /**
  61151. * Sets the current filter to Poisson Sampling.
  61152. */
  61153. set: function (value) {
  61154. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61155. return;
  61156. }
  61157. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61158. },
  61159. enumerable: true,
  61160. configurable: true
  61161. });
  61162. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61163. /**
  61164. * Gets if the current filter is set to VSM.
  61165. * DEPRECATED. Should use useExponentialShadowMap instead.
  61166. */
  61167. get: function () {
  61168. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61169. return this.useExponentialShadowMap;
  61170. },
  61171. /**
  61172. * Sets the current filter is to VSM.
  61173. * DEPRECATED. Should use useExponentialShadowMap instead.
  61174. */
  61175. set: function (value) {
  61176. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61177. this.useExponentialShadowMap = value;
  61178. },
  61179. enumerable: true,
  61180. configurable: true
  61181. });
  61182. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61183. /**
  61184. * Gets if the current filter is set to blurred VSM.
  61185. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61186. */
  61187. get: function () {
  61188. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61189. return this.useBlurExponentialShadowMap;
  61190. },
  61191. /**
  61192. * Sets the current filter is to blurred VSM.
  61193. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61194. */
  61195. set: function (value) {
  61196. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61197. this.useBlurExponentialShadowMap = value;
  61198. },
  61199. enumerable: true,
  61200. configurable: true
  61201. });
  61202. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61203. /**
  61204. * Gets if the current filter is set to ESM.
  61205. */
  61206. get: function () {
  61207. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61208. },
  61209. /**
  61210. * Sets the current filter is to ESM.
  61211. */
  61212. set: function (value) {
  61213. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61214. return;
  61215. }
  61216. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61217. },
  61218. enumerable: true,
  61219. configurable: true
  61220. });
  61221. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61222. /**
  61223. * Gets if the current filter is set to filtered ESM.
  61224. */
  61225. get: function () {
  61226. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61227. },
  61228. /**
  61229. * Gets if the current filter is set to filtered ESM.
  61230. */
  61231. set: function (value) {
  61232. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61233. return;
  61234. }
  61235. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61236. },
  61237. enumerable: true,
  61238. configurable: true
  61239. });
  61240. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61241. /**
  61242. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61243. * exponential to prevent steep falloff artifacts).
  61244. */
  61245. get: function () {
  61246. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61247. },
  61248. /**
  61249. * Sets the current filter to "close ESM" (using the inverse of the
  61250. * exponential to prevent steep falloff artifacts).
  61251. */
  61252. set: function (value) {
  61253. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61254. return;
  61255. }
  61256. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61257. },
  61258. enumerable: true,
  61259. configurable: true
  61260. });
  61261. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61262. /**
  61263. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61264. * exponential to prevent steep falloff artifacts).
  61265. */
  61266. get: function () {
  61267. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61268. },
  61269. /**
  61270. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61271. * exponential to prevent steep falloff artifacts).
  61272. */
  61273. set: function (value) {
  61274. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61275. return;
  61276. }
  61277. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61278. },
  61279. enumerable: true,
  61280. configurable: true
  61281. });
  61282. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61283. /**
  61284. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61285. */
  61286. get: function () {
  61287. return this.filter === ShadowGenerator.FILTER_PCF;
  61288. },
  61289. /**
  61290. * Sets the current filter to "PCF" (percentage closer filtering).
  61291. */
  61292. set: function (value) {
  61293. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61294. return;
  61295. }
  61296. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61297. },
  61298. enumerable: true,
  61299. configurable: true
  61300. });
  61301. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61302. /**
  61303. * Gets the PCF or PCSS Quality.
  61304. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61305. */
  61306. get: function () {
  61307. return this._filteringQuality;
  61308. },
  61309. /**
  61310. * Sets the PCF or PCSS Quality.
  61311. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61312. */
  61313. set: function (filteringQuality) {
  61314. this._filteringQuality = filteringQuality;
  61315. },
  61316. enumerable: true,
  61317. configurable: true
  61318. });
  61319. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61320. /**
  61321. * Gets if the current filter is set to "PCSS" (contact hardening).
  61322. */
  61323. get: function () {
  61324. return this.filter === ShadowGenerator.FILTER_PCSS;
  61325. },
  61326. /**
  61327. * Sets the current filter to "PCSS" (contact hardening).
  61328. */
  61329. set: function (value) {
  61330. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61331. return;
  61332. }
  61333. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61334. },
  61335. enumerable: true,
  61336. configurable: true
  61337. });
  61338. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61339. /**
  61340. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61341. * Using a ratio helps keeping shape stability independently of the map size.
  61342. *
  61343. * It does not account for the light projection as it was having too much
  61344. * instability during the light setup or during light position changes.
  61345. *
  61346. * Only valid if useContactHardeningShadow is true.
  61347. */
  61348. get: function () {
  61349. return this._contactHardeningLightSizeUVRatio;
  61350. },
  61351. /**
  61352. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61353. * Using a ratio helps keeping shape stability independently of the map size.
  61354. *
  61355. * It does not account for the light projection as it was having too much
  61356. * instability during the light setup or during light position changes.
  61357. *
  61358. * Only valid if useContactHardeningShadow is true.
  61359. */
  61360. set: function (contactHardeningLightSizeUVRatio) {
  61361. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61362. },
  61363. enumerable: true,
  61364. configurable: true
  61365. });
  61366. /**
  61367. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61368. * 0 means strongest and 1 would means no shadow.
  61369. * @returns the darkness.
  61370. */
  61371. ShadowGenerator.prototype.getDarkness = function () {
  61372. return this._darkness;
  61373. };
  61374. /**
  61375. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61376. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61377. * @returns the shadow generator allowing fluent coding.
  61378. */
  61379. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61380. if (darkness >= 1.0)
  61381. this._darkness = 1.0;
  61382. else if (darkness <= 0.0)
  61383. this._darkness = 0.0;
  61384. else
  61385. this._darkness = darkness;
  61386. return this;
  61387. };
  61388. /**
  61389. * Sets the ability to have transparent shadow (boolean).
  61390. * @param transparent True if transparent else False
  61391. * @returns the shadow generator allowing fluent coding
  61392. */
  61393. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61394. this._transparencyShadow = transparent;
  61395. return this;
  61396. };
  61397. /**
  61398. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61399. * @returns The render target texture if present otherwise, null
  61400. */
  61401. ShadowGenerator.prototype.getShadowMap = function () {
  61402. return this._shadowMap;
  61403. };
  61404. /**
  61405. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61406. * @returns The render target texture if the shadow map is present otherwise, null
  61407. */
  61408. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61409. if (this._shadowMap2) {
  61410. return this._shadowMap2;
  61411. }
  61412. return this._shadowMap;
  61413. };
  61414. /**
  61415. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61416. * @param mesh Mesh to add
  61417. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61418. * @returns the Shadow Generator itself
  61419. */
  61420. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61421. if (includeDescendants === void 0) { includeDescendants = true; }
  61422. if (!this._shadowMap) {
  61423. return this;
  61424. }
  61425. if (!this._shadowMap.renderList) {
  61426. this._shadowMap.renderList = [];
  61427. }
  61428. this._shadowMap.renderList.push(mesh);
  61429. if (includeDescendants) {
  61430. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61431. }
  61432. return this;
  61433. var _a;
  61434. };
  61435. /**
  61436. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61437. * @param mesh Mesh to remove
  61438. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61439. * @returns the Shadow Generator itself
  61440. */
  61441. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61442. if (includeDescendants === void 0) { includeDescendants = true; }
  61443. if (!this._shadowMap || !this._shadowMap.renderList) {
  61444. return this;
  61445. }
  61446. var index = this._shadowMap.renderList.indexOf(mesh);
  61447. if (index !== -1) {
  61448. this._shadowMap.renderList.splice(index, 1);
  61449. }
  61450. if (includeDescendants) {
  61451. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61452. var child = _a[_i];
  61453. this.removeShadowCaster(child);
  61454. }
  61455. }
  61456. return this;
  61457. };
  61458. /**
  61459. * Returns the associated light object.
  61460. * @returns the light generating the shadow
  61461. */
  61462. ShadowGenerator.prototype.getLight = function () {
  61463. return this._light;
  61464. };
  61465. ShadowGenerator.prototype._initializeGenerator = function () {
  61466. this._light._markMeshesAsLightDirty();
  61467. this._initializeShadowMap();
  61468. };
  61469. ShadowGenerator.prototype._initializeShadowMap = function () {
  61470. var _this = this;
  61471. // Render target
  61472. var engine = this._scene.getEngine();
  61473. if (engine.webGLVersion > 1) {
  61474. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61475. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61476. }
  61477. else {
  61478. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61479. }
  61480. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61481. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61482. this._shadowMap.anisotropicFilteringLevel = 1;
  61483. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61484. this._shadowMap.renderParticles = false;
  61485. this._shadowMap.ignoreCameraViewport = true;
  61486. // Record Face Index before render.
  61487. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61488. _this._currentFaceIndex = faceIndex;
  61489. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61490. engine.setColorWrite(false);
  61491. }
  61492. });
  61493. // Custom render function.
  61494. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61495. // Blur if required afer render.
  61496. this._shadowMap.onAfterUnbindObservable.add(function () {
  61497. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61498. engine.setColorWrite(true);
  61499. }
  61500. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61501. return;
  61502. }
  61503. var shadowMap = _this.getShadowMapForRendering();
  61504. if (shadowMap) {
  61505. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61506. }
  61507. });
  61508. // Clear according to the chosen filter.
  61509. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61510. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61511. this._shadowMap.onClearObservable.add(function (engine) {
  61512. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61513. engine.clear(clearOne, false, true, false);
  61514. }
  61515. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61516. engine.clear(clearZero, true, true, false);
  61517. }
  61518. else {
  61519. engine.clear(clearOne, true, true, false);
  61520. }
  61521. });
  61522. };
  61523. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61524. var _this = this;
  61525. var engine = this._scene.getEngine();
  61526. var targetSize = this._mapSize / this.blurScale;
  61527. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61528. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61529. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61530. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61531. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61532. }
  61533. if (this.useKernelBlur) {
  61534. 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);
  61535. this._kernelBlurXPostprocess.width = targetSize;
  61536. this._kernelBlurXPostprocess.height = targetSize;
  61537. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61538. effect.setTexture("textureSampler", _this._shadowMap);
  61539. });
  61540. 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);
  61541. this._kernelBlurXPostprocess.autoClear = false;
  61542. this._kernelBlurYPostprocess.autoClear = false;
  61543. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61544. this._kernelBlurXPostprocess.packedFloat = true;
  61545. this._kernelBlurYPostprocess.packedFloat = true;
  61546. }
  61547. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61548. }
  61549. else {
  61550. 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);
  61551. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61552. effect.setFloat2("screenSize", targetSize, targetSize);
  61553. effect.setTexture("textureSampler", _this._shadowMap);
  61554. });
  61555. this._boxBlurPostprocess.autoClear = false;
  61556. this._blurPostProcesses = [this._boxBlurPostprocess];
  61557. }
  61558. };
  61559. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61560. var index;
  61561. var engine = this._scene.getEngine();
  61562. if (depthOnlySubMeshes.length) {
  61563. engine.setColorWrite(false);
  61564. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61565. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61566. }
  61567. engine.setColorWrite(true);
  61568. }
  61569. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61570. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61571. }
  61572. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61573. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61574. }
  61575. if (this._transparencyShadow) {
  61576. for (index = 0; index < transparentSubMeshes.length; index++) {
  61577. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61578. }
  61579. }
  61580. };
  61581. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61582. var _this = this;
  61583. var mesh = subMesh.getRenderingMesh();
  61584. var scene = this._scene;
  61585. var engine = scene.getEngine();
  61586. var material = subMesh.getMaterial();
  61587. if (!material) {
  61588. return;
  61589. }
  61590. // Culling
  61591. engine.setState(material.backFaceCulling);
  61592. // Managing instances
  61593. var batch = mesh._getInstancesRenderList(subMesh._id);
  61594. if (batch.mustReturn) {
  61595. return;
  61596. }
  61597. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61598. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61599. engine.enableEffect(this._effect);
  61600. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61601. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61602. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61603. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61604. this._effect.setVector3("lightData", this._cachedDirection);
  61605. }
  61606. else {
  61607. this._effect.setVector3("lightData", this._cachedPosition);
  61608. }
  61609. if (scene.activeCamera) {
  61610. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61611. }
  61612. // Alpha test
  61613. if (material && material.needAlphaTesting()) {
  61614. var alphaTexture = material.getAlphaTestTexture();
  61615. if (alphaTexture) {
  61616. this._effect.setTexture("diffuseSampler", alphaTexture);
  61617. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61618. }
  61619. }
  61620. // Bones
  61621. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61622. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61623. }
  61624. if (this.forceBackFacesOnly) {
  61625. engine.setState(true, 0, false, true);
  61626. }
  61627. // Draw
  61628. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61629. if (this.forceBackFacesOnly) {
  61630. engine.setState(true, 0, false, false);
  61631. }
  61632. }
  61633. else {
  61634. // Need to reset refresh rate of the shadowMap
  61635. if (this._shadowMap) {
  61636. this._shadowMap.resetRefreshCounter();
  61637. }
  61638. }
  61639. };
  61640. ShadowGenerator.prototype._applyFilterValues = function () {
  61641. if (!this._shadowMap) {
  61642. return;
  61643. }
  61644. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61645. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61646. }
  61647. else {
  61648. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61649. }
  61650. };
  61651. /**
  61652. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61653. * @param onCompiled Callback triggered at the and of the effects compilation
  61654. * @param options Sets of optional options forcing the compilation with different modes
  61655. */
  61656. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61657. var _this = this;
  61658. var localOptions = __assign({ useInstances: false }, options);
  61659. var shadowMap = this.getShadowMap();
  61660. if (!shadowMap) {
  61661. if (onCompiled) {
  61662. onCompiled(this);
  61663. }
  61664. return;
  61665. }
  61666. var renderList = shadowMap.renderList;
  61667. if (!renderList) {
  61668. if (onCompiled) {
  61669. onCompiled(this);
  61670. }
  61671. return;
  61672. }
  61673. var subMeshes = new Array();
  61674. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61675. var mesh = renderList_1[_i];
  61676. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61677. }
  61678. if (subMeshes.length === 0) {
  61679. if (onCompiled) {
  61680. onCompiled(this);
  61681. }
  61682. return;
  61683. }
  61684. var currentIndex = 0;
  61685. var checkReady = function () {
  61686. if (!_this._scene || !_this._scene.getEngine()) {
  61687. return;
  61688. }
  61689. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61690. currentIndex++;
  61691. if (currentIndex >= subMeshes.length) {
  61692. if (onCompiled) {
  61693. onCompiled(_this);
  61694. }
  61695. return;
  61696. }
  61697. }
  61698. setTimeout(checkReady, 16);
  61699. };
  61700. checkReady();
  61701. };
  61702. /**
  61703. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61704. * @param options Sets of optional options forcing the compilation with different modes
  61705. * @returns A promise that resolves when the compilation completes
  61706. */
  61707. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61708. var _this = this;
  61709. return new Promise(function (resolve) {
  61710. _this.forceCompilation(function () {
  61711. resolve();
  61712. }, options);
  61713. });
  61714. };
  61715. /**
  61716. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61717. * @param subMesh The submesh we want to render in the shadow map
  61718. * @param useInstances Defines wether will draw in the map using instances
  61719. * @returns true if ready otherwise, false
  61720. */
  61721. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61722. var defines = [];
  61723. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61724. defines.push("#define FLOAT");
  61725. }
  61726. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61727. defines.push("#define ESM");
  61728. }
  61729. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61730. defines.push("#define DEPTHTEXTURE");
  61731. }
  61732. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61733. var mesh = subMesh.getMesh();
  61734. var material = subMesh.getMaterial();
  61735. // Normal bias.
  61736. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61737. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61738. defines.push("#define NORMAL");
  61739. if (mesh.nonUniformScaling) {
  61740. defines.push("#define NONUNIFORMSCALING");
  61741. }
  61742. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61743. defines.push("#define DIRECTIONINLIGHTDATA");
  61744. }
  61745. }
  61746. // Alpha test
  61747. if (material && material.needAlphaTesting()) {
  61748. var alphaTexture = material.getAlphaTestTexture();
  61749. if (alphaTexture) {
  61750. defines.push("#define ALPHATEST");
  61751. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61752. attribs.push(BABYLON.VertexBuffer.UVKind);
  61753. defines.push("#define UV1");
  61754. }
  61755. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61756. if (alphaTexture.coordinatesIndex === 1) {
  61757. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61758. defines.push("#define UV2");
  61759. }
  61760. }
  61761. }
  61762. }
  61763. // Bones
  61764. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61765. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61766. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61767. if (mesh.numBoneInfluencers > 4) {
  61768. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61769. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61770. }
  61771. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61772. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61773. }
  61774. else {
  61775. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61776. }
  61777. // Instances
  61778. if (useInstances) {
  61779. defines.push("#define INSTANCES");
  61780. attribs.push("world0");
  61781. attribs.push("world1");
  61782. attribs.push("world2");
  61783. attribs.push("world3");
  61784. }
  61785. // Get correct effect
  61786. var join = defines.join("\n");
  61787. if (this._cachedDefines !== join) {
  61788. this._cachedDefines = join;
  61789. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  61790. }
  61791. if (!this._effect.isReady()) {
  61792. return false;
  61793. }
  61794. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61795. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61796. this._initializeBlurRTTAndPostProcesses();
  61797. }
  61798. }
  61799. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61800. return false;
  61801. }
  61802. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61803. return false;
  61804. }
  61805. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61806. return false;
  61807. }
  61808. return true;
  61809. };
  61810. /**
  61811. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61812. * @param defines Defines of the material we want to update
  61813. * @param lightIndex Index of the light in the enabled light list of the material
  61814. */
  61815. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61816. var scene = this._scene;
  61817. var light = this._light;
  61818. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61819. return;
  61820. }
  61821. defines["SHADOW" + lightIndex] = true;
  61822. if (this.useContactHardeningShadow) {
  61823. defines["SHADOWPCSS" + lightIndex] = true;
  61824. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61825. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61826. }
  61827. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61828. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61829. }
  61830. // else default to high.
  61831. }
  61832. if (this.usePercentageCloserFiltering) {
  61833. defines["SHADOWPCF" + lightIndex] = true;
  61834. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61835. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61836. }
  61837. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61838. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61839. }
  61840. // else default to high.
  61841. }
  61842. else if (this.usePoissonSampling) {
  61843. defines["SHADOWPOISSON" + lightIndex] = true;
  61844. }
  61845. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61846. defines["SHADOWESM" + lightIndex] = true;
  61847. }
  61848. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61849. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61850. }
  61851. if (light.needCube()) {
  61852. defines["SHADOWCUBE" + lightIndex] = true;
  61853. }
  61854. };
  61855. /**
  61856. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61857. * defined in the generator but impacting the effect).
  61858. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61859. * @param effect The effect we are binfing the information for
  61860. */
  61861. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61862. var light = this._light;
  61863. var scene = this._scene;
  61864. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61865. return;
  61866. }
  61867. var camera = scene.activeCamera;
  61868. if (!camera) {
  61869. return;
  61870. }
  61871. var shadowMap = this.getShadowMap();
  61872. if (!shadowMap) {
  61873. return;
  61874. }
  61875. if (!light.needCube()) {
  61876. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61877. }
  61878. // Only PCF uses depth stencil texture.
  61879. if (this._filter === ShadowGenerator.FILTER_PCF) {
  61880. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61881. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61882. }
  61883. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  61884. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61885. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  61886. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61887. }
  61888. else {
  61889. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61890. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61891. }
  61892. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61893. };
  61894. /**
  61895. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61896. * (eq to shadow prjection matrix * light transform matrix)
  61897. * @returns The transform matrix used to create the shadow map
  61898. */
  61899. ShadowGenerator.prototype.getTransformMatrix = function () {
  61900. var scene = this._scene;
  61901. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61902. return this._transformMatrix;
  61903. }
  61904. this._currentRenderID = scene.getRenderId();
  61905. this._currentFaceIndexCache = this._currentFaceIndex;
  61906. var lightPosition = this._light.position;
  61907. if (this._light.computeTransformedInformation()) {
  61908. lightPosition = this._light.transformedPosition;
  61909. }
  61910. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61911. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61912. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61913. }
  61914. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61915. this._cachedPosition.copyFrom(lightPosition);
  61916. this._cachedDirection.copyFrom(this._lightDirection);
  61917. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61918. var shadowMap = this.getShadowMap();
  61919. if (shadowMap) {
  61920. var renderList = shadowMap.renderList;
  61921. if (renderList) {
  61922. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61923. }
  61924. }
  61925. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61926. }
  61927. return this._transformMatrix;
  61928. };
  61929. /**
  61930. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61931. * Cube and 2D textures for instance.
  61932. */
  61933. ShadowGenerator.prototype.recreateShadowMap = function () {
  61934. var shadowMap = this._shadowMap;
  61935. if (!shadowMap) {
  61936. return;
  61937. }
  61938. // Track render list.
  61939. var renderList = shadowMap.renderList;
  61940. // Clean up existing data.
  61941. this._disposeRTTandPostProcesses();
  61942. // Reinitializes.
  61943. this._initializeGenerator();
  61944. // Reaffect the filter to ensure a correct fallback if necessary.
  61945. this.filter = this.filter;
  61946. // Reaffect the filter.
  61947. this._applyFilterValues();
  61948. // Reaffect Render List.
  61949. this._shadowMap.renderList = renderList;
  61950. };
  61951. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61952. if (this._shadowMap2) {
  61953. this._shadowMap2.dispose();
  61954. this._shadowMap2 = null;
  61955. }
  61956. if (this._boxBlurPostprocess) {
  61957. this._boxBlurPostprocess.dispose();
  61958. this._boxBlurPostprocess = null;
  61959. }
  61960. if (this._kernelBlurXPostprocess) {
  61961. this._kernelBlurXPostprocess.dispose();
  61962. this._kernelBlurXPostprocess = null;
  61963. }
  61964. if (this._kernelBlurYPostprocess) {
  61965. this._kernelBlurYPostprocess.dispose();
  61966. this._kernelBlurYPostprocess = null;
  61967. }
  61968. this._blurPostProcesses = [];
  61969. };
  61970. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61971. if (this._shadowMap) {
  61972. this._shadowMap.dispose();
  61973. this._shadowMap = null;
  61974. }
  61975. this._disposeBlurPostProcesses();
  61976. };
  61977. /**
  61978. * Disposes the ShadowGenerator.
  61979. * Returns nothing.
  61980. */
  61981. ShadowGenerator.prototype.dispose = function () {
  61982. this._disposeRTTandPostProcesses();
  61983. if (this._light) {
  61984. this._light._shadowGenerator = null;
  61985. this._light._markMeshesAsLightDirty();
  61986. }
  61987. };
  61988. /**
  61989. * Serializes the shadow generator setup to a json object.
  61990. * @returns The serialized JSON object
  61991. */
  61992. ShadowGenerator.prototype.serialize = function () {
  61993. var serializationObject = {};
  61994. var shadowMap = this.getShadowMap();
  61995. if (!shadowMap) {
  61996. return serializationObject;
  61997. }
  61998. serializationObject.lightId = this._light.id;
  61999. serializationObject.mapSize = shadowMap.getRenderSize();
  62000. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  62001. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  62002. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62003. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62004. serializationObject.usePoissonSampling = this.usePoissonSampling;
  62005. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  62006. serializationObject.depthScale = this.depthScale;
  62007. serializationObject.darkness = this.getDarkness();
  62008. serializationObject.blurBoxOffset = this.blurBoxOffset;
  62009. serializationObject.blurKernel = this.blurKernel;
  62010. serializationObject.blurScale = this.blurScale;
  62011. serializationObject.useKernelBlur = this.useKernelBlur;
  62012. serializationObject.transparencyShadow = this._transparencyShadow;
  62013. serializationObject.bias = this.bias;
  62014. serializationObject.normalBias = this.normalBias;
  62015. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  62016. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  62017. serializationObject.filteringQuality = this.filteringQuality;
  62018. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  62019. serializationObject.renderList = [];
  62020. if (shadowMap.renderList) {
  62021. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  62022. var mesh = shadowMap.renderList[meshIndex];
  62023. serializationObject.renderList.push(mesh.id);
  62024. }
  62025. }
  62026. return serializationObject;
  62027. };
  62028. /**
  62029. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  62030. * @param parsedShadowGenerator The JSON object to parse
  62031. * @param scene The scene to create the shadow map for
  62032. * @returns The parsed shadow generator
  62033. */
  62034. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62035. //casting to point light, as light is missing the position attr and typescript complains.
  62036. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62037. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62038. var shadowMap = shadowGenerator.getShadowMap();
  62039. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62040. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62041. meshes.forEach(function (mesh) {
  62042. if (!shadowMap) {
  62043. return;
  62044. }
  62045. if (!shadowMap.renderList) {
  62046. shadowMap.renderList = [];
  62047. }
  62048. shadowMap.renderList.push(mesh);
  62049. });
  62050. }
  62051. if (parsedShadowGenerator.usePoissonSampling) {
  62052. shadowGenerator.usePoissonSampling = true;
  62053. }
  62054. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62055. shadowGenerator.useExponentialShadowMap = true;
  62056. }
  62057. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62058. shadowGenerator.useBlurExponentialShadowMap = true;
  62059. }
  62060. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62061. shadowGenerator.useCloseExponentialShadowMap = true;
  62062. }
  62063. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62064. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62065. }
  62066. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62067. shadowGenerator.usePercentageCloserFiltering = true;
  62068. }
  62069. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62070. shadowGenerator.useContactHardeningShadow = true;
  62071. }
  62072. if (parsedShadowGenerator.filteringQuality) {
  62073. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62074. }
  62075. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62076. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62077. }
  62078. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62079. shadowGenerator.useExponentialShadowMap = true;
  62080. }
  62081. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62082. shadowGenerator.useBlurExponentialShadowMap = true;
  62083. }
  62084. if (parsedShadowGenerator.depthScale) {
  62085. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62086. }
  62087. if (parsedShadowGenerator.blurScale) {
  62088. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62089. }
  62090. if (parsedShadowGenerator.blurBoxOffset) {
  62091. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62092. }
  62093. if (parsedShadowGenerator.useKernelBlur) {
  62094. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62095. }
  62096. if (parsedShadowGenerator.blurKernel) {
  62097. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62098. }
  62099. if (parsedShadowGenerator.bias !== undefined) {
  62100. shadowGenerator.bias = parsedShadowGenerator.bias;
  62101. }
  62102. if (parsedShadowGenerator.normalBias !== undefined) {
  62103. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62104. }
  62105. if (parsedShadowGenerator.darkness) {
  62106. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62107. }
  62108. if (parsedShadowGenerator.transparencyShadow) {
  62109. shadowGenerator.setTransparencyShadow(true);
  62110. }
  62111. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62112. return shadowGenerator;
  62113. };
  62114. /**
  62115. * Shadow generator mode None: no filtering applied.
  62116. */
  62117. ShadowGenerator.FILTER_NONE = 0;
  62118. /**
  62119. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62120. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62121. */
  62122. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62123. /**
  62124. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62125. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62126. */
  62127. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62128. /**
  62129. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62130. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62131. */
  62132. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62133. /**
  62134. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62135. * edge artifacts on steep falloff.
  62136. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62137. */
  62138. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62139. /**
  62140. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62141. * edge artifacts on steep falloff.
  62142. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62143. */
  62144. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62145. /**
  62146. * Shadow generator mode PCF: Percentage Closer Filtering
  62147. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62148. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62149. */
  62150. ShadowGenerator.FILTER_PCF = 6;
  62151. /**
  62152. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62153. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62154. * Contact Hardening
  62155. */
  62156. ShadowGenerator.FILTER_PCSS = 7;
  62157. /**
  62158. * Reserved for PCF and PCSS
  62159. * Highest Quality.
  62160. *
  62161. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62162. *
  62163. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62164. */
  62165. ShadowGenerator.QUALITY_HIGH = 0;
  62166. /**
  62167. * Reserved for PCF and PCSS
  62168. * Good tradeoff for quality/perf cross devices
  62169. *
  62170. * Execute PCF on a 3*3 kernel.
  62171. *
  62172. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62173. */
  62174. ShadowGenerator.QUALITY_MEDIUM = 1;
  62175. /**
  62176. * Reserved for PCF and PCSS
  62177. * The lowest quality but the fastest.
  62178. *
  62179. * Execute PCF on a 1*1 kernel.
  62180. *
  62181. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62182. */
  62183. ShadowGenerator.QUALITY_LOW = 2;
  62184. return ShadowGenerator;
  62185. }());
  62186. BABYLON.ShadowGenerator = ShadowGenerator;
  62187. })(BABYLON || (BABYLON = {}));
  62188. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62189. "use strict";
  62190. var BABYLON;
  62191. (function (BABYLON) {
  62192. var DefaultLoadingScreen = /** @class */ (function () {
  62193. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62194. if (_loadingText === void 0) { _loadingText = ""; }
  62195. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62196. var _this = this;
  62197. this._renderingCanvas = _renderingCanvas;
  62198. this._loadingText = _loadingText;
  62199. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62200. // Resize
  62201. this._resizeLoadingUI = function () {
  62202. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62203. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62204. if (!_this._loadingDiv) {
  62205. return;
  62206. }
  62207. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62208. _this._loadingDiv.style.left = canvasRect.left + "px";
  62209. _this._loadingDiv.style.top = canvasRect.top + "px";
  62210. _this._loadingDiv.style.width = canvasRect.width + "px";
  62211. _this._loadingDiv.style.height = canvasRect.height + "px";
  62212. };
  62213. }
  62214. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62215. if (this._loadingDiv) {
  62216. // Do not add a loading screen if there is already one
  62217. return;
  62218. }
  62219. this._loadingDiv = document.createElement("div");
  62220. this._loadingDiv.id = "babylonjsLoadingDiv";
  62221. this._loadingDiv.style.opacity = "0";
  62222. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62223. this._loadingDiv.style.pointerEvents = "none";
  62224. // Loading text
  62225. this._loadingTextDiv = document.createElement("div");
  62226. this._loadingTextDiv.style.position = "absolute";
  62227. this._loadingTextDiv.style.left = "0";
  62228. this._loadingTextDiv.style.top = "50%";
  62229. this._loadingTextDiv.style.marginTop = "80px";
  62230. this._loadingTextDiv.style.width = "100%";
  62231. this._loadingTextDiv.style.height = "20px";
  62232. this._loadingTextDiv.style.fontFamily = "Arial";
  62233. this._loadingTextDiv.style.fontSize = "14px";
  62234. this._loadingTextDiv.style.color = "white";
  62235. this._loadingTextDiv.style.textAlign = "center";
  62236. this._loadingTextDiv.innerHTML = "Loading";
  62237. this._loadingDiv.appendChild(this._loadingTextDiv);
  62238. //set the predefined text
  62239. this._loadingTextDiv.innerHTML = this._loadingText;
  62240. // Generating keyframes
  62241. var style = document.createElement('style');
  62242. style.type = 'text/css';
  62243. 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 }";
  62244. style.innerHTML = keyFrames;
  62245. document.getElementsByTagName('head')[0].appendChild(style);
  62246. // Loading img
  62247. var imgBack = new Image();
  62248. 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";
  62249. imgBack.style.position = "absolute";
  62250. imgBack.style.left = "50%";
  62251. imgBack.style.top = "50%";
  62252. imgBack.style.marginLeft = "-60px";
  62253. imgBack.style.marginTop = "-60px";
  62254. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62255. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62256. imgBack.style.transformOrigin = "50% 50%";
  62257. imgBack.style.webkitTransformOrigin = "50% 50%";
  62258. this._loadingDiv.appendChild(imgBack);
  62259. this._resizeLoadingUI();
  62260. window.addEventListener("resize", this._resizeLoadingUI);
  62261. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62262. document.body.appendChild(this._loadingDiv);
  62263. this._loadingDiv.style.opacity = "1";
  62264. };
  62265. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62266. var _this = this;
  62267. if (!this._loadingDiv) {
  62268. return;
  62269. }
  62270. var onTransitionEnd = function () {
  62271. if (!_this._loadingDiv) {
  62272. return;
  62273. }
  62274. document.body.removeChild(_this._loadingDiv);
  62275. window.removeEventListener("resize", _this._resizeLoadingUI);
  62276. _this._loadingDiv = null;
  62277. };
  62278. this._loadingDiv.style.opacity = "0";
  62279. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62280. };
  62281. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62282. set: function (text) {
  62283. this._loadingText = text;
  62284. if (this._loadingTextDiv) {
  62285. this._loadingTextDiv.innerHTML = this._loadingText;
  62286. }
  62287. },
  62288. enumerable: true,
  62289. configurable: true
  62290. });
  62291. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62292. get: function () {
  62293. return this._loadingDivBackgroundColor;
  62294. },
  62295. set: function (color) {
  62296. this._loadingDivBackgroundColor = color;
  62297. if (!this._loadingDiv) {
  62298. return;
  62299. }
  62300. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62301. },
  62302. enumerable: true,
  62303. configurable: true
  62304. });
  62305. return DefaultLoadingScreen;
  62306. }());
  62307. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62308. })(BABYLON || (BABYLON = {}));
  62309. //# sourceMappingURL=babylon.loadingScreen.js.map
  62310. "use strict";
  62311. var BABYLON;
  62312. (function (BABYLON) {
  62313. var SceneLoaderProgressEvent = /** @class */ (function () {
  62314. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62315. this.lengthComputable = lengthComputable;
  62316. this.loaded = loaded;
  62317. this.total = total;
  62318. }
  62319. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62320. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62321. };
  62322. return SceneLoaderProgressEvent;
  62323. }());
  62324. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62325. var SceneLoader = /** @class */ (function () {
  62326. function SceneLoader() {
  62327. }
  62328. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62329. get: function () {
  62330. return 0;
  62331. },
  62332. enumerable: true,
  62333. configurable: true
  62334. });
  62335. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62336. get: function () {
  62337. return 1;
  62338. },
  62339. enumerable: true,
  62340. configurable: true
  62341. });
  62342. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62343. get: function () {
  62344. return 2;
  62345. },
  62346. enumerable: true,
  62347. configurable: true
  62348. });
  62349. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62350. get: function () {
  62351. return 3;
  62352. },
  62353. enumerable: true,
  62354. configurable: true
  62355. });
  62356. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62357. get: function () {
  62358. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62359. },
  62360. set: function (value) {
  62361. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62362. },
  62363. enumerable: true,
  62364. configurable: true
  62365. });
  62366. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62367. get: function () {
  62368. return SceneLoader._ShowLoadingScreen;
  62369. },
  62370. set: function (value) {
  62371. SceneLoader._ShowLoadingScreen = value;
  62372. },
  62373. enumerable: true,
  62374. configurable: true
  62375. });
  62376. Object.defineProperty(SceneLoader, "loggingLevel", {
  62377. get: function () {
  62378. return SceneLoader._loggingLevel;
  62379. },
  62380. set: function (value) {
  62381. SceneLoader._loggingLevel = value;
  62382. },
  62383. enumerable: true,
  62384. configurable: true
  62385. });
  62386. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62387. get: function () {
  62388. return SceneLoader._CleanBoneMatrixWeights;
  62389. },
  62390. set: function (value) {
  62391. SceneLoader._CleanBoneMatrixWeights = value;
  62392. },
  62393. enumerable: true,
  62394. configurable: true
  62395. });
  62396. SceneLoader._getDefaultPlugin = function () {
  62397. return SceneLoader._registeredPlugins[".babylon"];
  62398. };
  62399. SceneLoader._getPluginForExtension = function (extension) {
  62400. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62401. if (registeredPlugin) {
  62402. return registeredPlugin;
  62403. }
  62404. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62405. return SceneLoader._getDefaultPlugin();
  62406. };
  62407. SceneLoader._getPluginForDirectLoad = function (data) {
  62408. for (var extension in SceneLoader._registeredPlugins) {
  62409. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62410. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62411. return SceneLoader._registeredPlugins[extension];
  62412. }
  62413. }
  62414. return SceneLoader._getDefaultPlugin();
  62415. };
  62416. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62417. if (sceneFilename.name) {
  62418. sceneFilename = sceneFilename.name;
  62419. }
  62420. var queryStringPosition = sceneFilename.indexOf("?");
  62421. if (queryStringPosition !== -1) {
  62422. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62423. }
  62424. var dotPosition = sceneFilename.lastIndexOf(".");
  62425. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62426. return SceneLoader._getPluginForExtension(extension);
  62427. };
  62428. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62429. SceneLoader._getDirectLoad = function (sceneFilename) {
  62430. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62431. return sceneFilename.substr(5);
  62432. }
  62433. return null;
  62434. };
  62435. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62436. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62437. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62438. var plugin;
  62439. if (registeredPlugin.plugin.createPlugin) {
  62440. plugin = registeredPlugin.plugin.createPlugin();
  62441. }
  62442. else {
  62443. plugin = registeredPlugin.plugin;
  62444. }
  62445. var useArrayBuffer = registeredPlugin.isBinary;
  62446. var database;
  62447. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62448. var dataCallback = function (data, responseURL) {
  62449. if (scene.isDisposed) {
  62450. onError("Scene has been disposed");
  62451. return;
  62452. }
  62453. scene.database = database;
  62454. onSuccess(plugin, data, responseURL);
  62455. };
  62456. var request = null;
  62457. var pluginDisposed = false;
  62458. var onDisposeObservable = plugin.onDisposeObservable;
  62459. if (onDisposeObservable) {
  62460. onDisposeObservable.add(function () {
  62461. pluginDisposed = true;
  62462. if (request) {
  62463. request.abort();
  62464. request = null;
  62465. }
  62466. onDispose();
  62467. });
  62468. }
  62469. var manifestChecked = function () {
  62470. if (pluginDisposed) {
  62471. return;
  62472. }
  62473. var url = rootUrl + sceneFilename;
  62474. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62475. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62476. } : undefined, database, useArrayBuffer, function (request, exception) {
  62477. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62478. });
  62479. };
  62480. if (directLoad) {
  62481. dataCallback(directLoad);
  62482. return plugin;
  62483. }
  62484. if (rootUrl.indexOf("file:") === -1) {
  62485. if (scene.getEngine().enableOfflineSupport) {
  62486. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62487. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62488. }
  62489. else {
  62490. manifestChecked();
  62491. }
  62492. }
  62493. else {
  62494. var fileOrString = sceneFilename;
  62495. if (fileOrString.name) {
  62496. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62497. }
  62498. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62499. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62500. }
  62501. else {
  62502. onError("Unable to find file named " + sceneFilename);
  62503. }
  62504. }
  62505. return plugin;
  62506. };
  62507. // Public functions
  62508. SceneLoader.GetPluginForExtension = function (extension) {
  62509. return SceneLoader._getPluginForExtension(extension).plugin;
  62510. };
  62511. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62512. return !!SceneLoader._registeredPlugins[extension];
  62513. };
  62514. SceneLoader.RegisterPlugin = function (plugin) {
  62515. if (typeof plugin.extensions === "string") {
  62516. var extension = plugin.extensions;
  62517. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62518. plugin: plugin,
  62519. isBinary: false
  62520. };
  62521. }
  62522. else {
  62523. var extensions = plugin.extensions;
  62524. Object.keys(extensions).forEach(function (extension) {
  62525. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62526. plugin: plugin,
  62527. isBinary: extensions[extension].isBinary
  62528. };
  62529. });
  62530. }
  62531. };
  62532. /**
  62533. * Import meshes into a scene
  62534. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62535. * @param rootUrl a string that defines the root url for scene and resources
  62536. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62537. * @param scene the instance of BABYLON.Scene to append to
  62538. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62539. * @param onProgress a callback with a progress event for each file being loaded
  62540. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62541. * @param pluginExtension the extension used to determine the plugin
  62542. * @returns The loaded plugin
  62543. */
  62544. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62545. if (onSuccess === void 0) { onSuccess = null; }
  62546. if (onProgress === void 0) { onProgress = null; }
  62547. if (onError === void 0) { onError = null; }
  62548. if (pluginExtension === void 0) { pluginExtension = null; }
  62549. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62550. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62551. return null;
  62552. }
  62553. var loadingToken = {};
  62554. scene._addPendingData(loadingToken);
  62555. var disposeHandler = function () {
  62556. scene._removePendingData(loadingToken);
  62557. };
  62558. var errorHandler = function (message, exception) {
  62559. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62560. if (onError) {
  62561. onError(scene, errorMessage, exception);
  62562. }
  62563. else {
  62564. BABYLON.Tools.Error(errorMessage);
  62565. // should the exception be thrown?
  62566. }
  62567. disposeHandler();
  62568. };
  62569. var progressHandler = onProgress ? function (event) {
  62570. try {
  62571. onProgress(event);
  62572. }
  62573. catch (e) {
  62574. errorHandler("Error in onProgress callback", e);
  62575. }
  62576. } : undefined;
  62577. var successHandler = function (meshes, particleSystems, skeletons) {
  62578. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62579. if (onSuccess) {
  62580. try {
  62581. onSuccess(meshes, particleSystems, skeletons);
  62582. }
  62583. catch (e) {
  62584. errorHandler("Error in onSuccess callback", e);
  62585. }
  62586. }
  62587. scene._removePendingData(loadingToken);
  62588. };
  62589. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62590. if (plugin.rewriteRootURL) {
  62591. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62592. }
  62593. if (sceneFilename === "") {
  62594. if (sceneFilename === "") {
  62595. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62596. }
  62597. }
  62598. if (plugin.importMesh) {
  62599. var syncedPlugin = plugin;
  62600. var meshes = new Array();
  62601. var particleSystems = new Array();
  62602. var skeletons = new Array();
  62603. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62604. return;
  62605. }
  62606. scene.loadingPluginName = plugin.name;
  62607. successHandler(meshes, particleSystems, skeletons);
  62608. }
  62609. else {
  62610. var asyncedPlugin = plugin;
  62611. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62612. scene.loadingPluginName = plugin.name;
  62613. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62614. }).catch(function (error) {
  62615. errorHandler(error.message, error);
  62616. });
  62617. }
  62618. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62619. };
  62620. /**
  62621. * Import meshes into a scene
  62622. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62623. * @param rootUrl a string that defines the root url for scene and resources
  62624. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62625. * @param scene the instance of BABYLON.Scene to append to
  62626. * @param onProgress a callback with a progress event for each file being loaded
  62627. * @param pluginExtension the extension used to determine the plugin
  62628. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62629. */
  62630. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62631. if (onProgress === void 0) { onProgress = null; }
  62632. if (pluginExtension === void 0) { pluginExtension = null; }
  62633. return new Promise(function (resolve, reject) {
  62634. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62635. resolve({
  62636. meshes: meshes,
  62637. particleSystems: particleSystems,
  62638. skeletons: skeletons
  62639. });
  62640. }, onProgress, function (scene, message, exception) {
  62641. reject(exception || new Error(message));
  62642. });
  62643. });
  62644. };
  62645. /**
  62646. * Load a scene
  62647. * @param rootUrl a string that defines the root url for scene and resources
  62648. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62649. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62650. * @param onSuccess a callback with the scene when import succeeds
  62651. * @param onProgress a callback with a progress event for each file being loaded
  62652. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62653. * @param pluginExtension the extension used to determine the plugin
  62654. * @returns The loaded plugin
  62655. */
  62656. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62657. if (onSuccess === void 0) { onSuccess = null; }
  62658. if (onProgress === void 0) { onProgress = null; }
  62659. if (onError === void 0) { onError = null; }
  62660. if (pluginExtension === void 0) { pluginExtension = null; }
  62661. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62662. };
  62663. /**
  62664. * Load a scene
  62665. * @param rootUrl a string that defines the root url for scene and resources
  62666. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62667. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62668. * @param onProgress a callback with a progress event for each file being loaded
  62669. * @param pluginExtension the extension used to determine the plugin
  62670. * @returns The loaded scene
  62671. */
  62672. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62673. if (onProgress === void 0) { onProgress = null; }
  62674. if (pluginExtension === void 0) { pluginExtension = null; }
  62675. return new Promise(function (resolve, reject) {
  62676. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62677. resolve(scene);
  62678. }, onProgress, function (scene, message, exception) {
  62679. reject(exception || new Error(message));
  62680. }, pluginExtension);
  62681. });
  62682. };
  62683. /**
  62684. * Append a scene
  62685. * @param rootUrl a string that defines the root url for scene and resources
  62686. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62687. * @param scene is the instance of BABYLON.Scene to append to
  62688. * @param onSuccess a callback with the scene when import succeeds
  62689. * @param onProgress a callback with a progress event for each file being loaded
  62690. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62691. * @param pluginExtension the extension used to determine the plugin
  62692. * @returns The loaded plugin
  62693. */
  62694. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62695. if (onSuccess === void 0) { onSuccess = null; }
  62696. if (onProgress === void 0) { onProgress = null; }
  62697. if (onError === void 0) { onError = null; }
  62698. if (pluginExtension === void 0) { pluginExtension = null; }
  62699. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62700. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62701. return null;
  62702. }
  62703. if (SceneLoader.ShowLoadingScreen) {
  62704. scene.getEngine().displayLoadingUI();
  62705. }
  62706. var loadingToken = {};
  62707. scene._addPendingData(loadingToken);
  62708. var disposeHandler = function () {
  62709. scene._removePendingData(loadingToken);
  62710. scene.getEngine().hideLoadingUI();
  62711. };
  62712. var errorHandler = function (message, exception) {
  62713. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62714. if (onError) {
  62715. onError(scene, errorMessage, exception);
  62716. }
  62717. else {
  62718. BABYLON.Tools.Error(errorMessage);
  62719. // should the exception be thrown?
  62720. }
  62721. disposeHandler();
  62722. };
  62723. var progressHandler = onProgress ? function (event) {
  62724. try {
  62725. onProgress(event);
  62726. }
  62727. catch (e) {
  62728. errorHandler("Error in onProgress callback", e);
  62729. }
  62730. } : undefined;
  62731. var successHandler = function () {
  62732. if (onSuccess) {
  62733. try {
  62734. onSuccess(scene);
  62735. }
  62736. catch (e) {
  62737. errorHandler("Error in onSuccess callback", e);
  62738. }
  62739. }
  62740. scene._removePendingData(loadingToken);
  62741. };
  62742. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62743. if (sceneFilename === "") {
  62744. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62745. }
  62746. if (plugin.load) {
  62747. var syncedPlugin = plugin;
  62748. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  62749. return;
  62750. }
  62751. scene.loadingPluginName = plugin.name;
  62752. successHandler();
  62753. }
  62754. else {
  62755. var asyncedPlugin = plugin;
  62756. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  62757. scene.loadingPluginName = plugin.name;
  62758. successHandler();
  62759. }).catch(function (error) {
  62760. errorHandler(error.message, error);
  62761. });
  62762. }
  62763. if (SceneLoader.ShowLoadingScreen) {
  62764. scene.executeWhenReady(function () {
  62765. scene.getEngine().hideLoadingUI();
  62766. });
  62767. }
  62768. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62769. };
  62770. /**
  62771. * Append a scene
  62772. * @param rootUrl a string that defines the root url for scene and resources
  62773. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62774. * @param scene is the instance of BABYLON.Scene to append to
  62775. * @param onProgress a callback with a progress event for each file being loaded
  62776. * @param pluginExtension the extension used to determine the plugin
  62777. * @returns The given scene
  62778. */
  62779. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62780. if (onProgress === void 0) { onProgress = null; }
  62781. if (pluginExtension === void 0) { pluginExtension = null; }
  62782. return new Promise(function (resolve, reject) {
  62783. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62784. resolve(scene);
  62785. }, onProgress, function (scene, message, exception) {
  62786. reject(exception || new Error(message));
  62787. }, pluginExtension);
  62788. });
  62789. };
  62790. /**
  62791. * Load a scene into an asset container
  62792. * @param rootUrl a string that defines the root url for scene and resources
  62793. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62794. * @param scene is the instance of BABYLON.Scene to append to
  62795. * @param onSuccess a callback with the scene when import succeeds
  62796. * @param onProgress a callback with a progress event for each file being loaded
  62797. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62798. * @param pluginExtension the extension used to determine the plugin
  62799. * @returns The loaded plugin
  62800. */
  62801. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62802. if (onSuccess === void 0) { onSuccess = null; }
  62803. if (onProgress === void 0) { onProgress = null; }
  62804. if (onError === void 0) { onError = null; }
  62805. if (pluginExtension === void 0) { pluginExtension = null; }
  62806. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62807. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62808. return null;
  62809. }
  62810. var loadingToken = {};
  62811. scene._addPendingData(loadingToken);
  62812. var disposeHandler = function () {
  62813. scene._removePendingData(loadingToken);
  62814. };
  62815. var errorHandler = function (message, exception) {
  62816. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62817. if (onError) {
  62818. onError(scene, errorMessage, exception);
  62819. }
  62820. else {
  62821. BABYLON.Tools.Error(errorMessage);
  62822. // should the exception be thrown?
  62823. }
  62824. disposeHandler();
  62825. };
  62826. var progressHandler = onProgress ? function (event) {
  62827. try {
  62828. onProgress(event);
  62829. }
  62830. catch (e) {
  62831. errorHandler("Error in onProgress callback", e);
  62832. }
  62833. } : undefined;
  62834. var successHandler = function (assets) {
  62835. if (onSuccess) {
  62836. try {
  62837. onSuccess(assets);
  62838. }
  62839. catch (e) {
  62840. errorHandler("Error in onSuccess callback", e);
  62841. }
  62842. }
  62843. scene._removePendingData(loadingToken);
  62844. };
  62845. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62846. if (plugin.loadAssetContainer) {
  62847. var syncedPlugin = plugin;
  62848. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62849. if (!assetContainer) {
  62850. return;
  62851. }
  62852. scene.loadingPluginName = plugin.name;
  62853. successHandler(assetContainer);
  62854. }
  62855. else if (plugin.loadAssetContainerAsync) {
  62856. var asyncedPlugin = plugin;
  62857. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62858. scene.loadingPluginName = plugin.name;
  62859. successHandler(assetContainer);
  62860. }).catch(function (error) {
  62861. errorHandler(error.message, error);
  62862. });
  62863. }
  62864. else {
  62865. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62866. }
  62867. if (SceneLoader.ShowLoadingScreen) {
  62868. scene.executeWhenReady(function () {
  62869. scene.getEngine().hideLoadingUI();
  62870. });
  62871. }
  62872. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62873. };
  62874. /**
  62875. * Load a scene into an asset container
  62876. * @param rootUrl a string that defines the root url for scene and resources
  62877. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62878. * @param scene is the instance of BABYLON.Scene to append to
  62879. * @param onProgress a callback with a progress event for each file being loaded
  62880. * @param pluginExtension the extension used to determine the plugin
  62881. * @returns The loaded asset container
  62882. */
  62883. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62884. if (onProgress === void 0) { onProgress = null; }
  62885. if (pluginExtension === void 0) { pluginExtension = null; }
  62886. return new Promise(function (resolve, reject) {
  62887. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62888. resolve(assetContainer);
  62889. }, onProgress, function (scene, message, exception) {
  62890. reject(exception || new Error(message));
  62891. }, pluginExtension);
  62892. });
  62893. };
  62894. // Flags
  62895. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62896. SceneLoader._ShowLoadingScreen = true;
  62897. SceneLoader._CleanBoneMatrixWeights = false;
  62898. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62899. // Members
  62900. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62901. SceneLoader._registeredPlugins = {};
  62902. return SceneLoader;
  62903. }());
  62904. BABYLON.SceneLoader = SceneLoader;
  62905. ;
  62906. })(BABYLON || (BABYLON = {}));
  62907. //# sourceMappingURL=babylon.sceneLoader.js.map
  62908. "use strict";
  62909. var BABYLON;
  62910. (function (BABYLON) {
  62911. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62912. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62913. var parsedMaterial = parsedData.materials[index];
  62914. if (parsedMaterial.id === id) {
  62915. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62916. }
  62917. }
  62918. return null;
  62919. };
  62920. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62921. for (var i in names) {
  62922. if (mesh.name === names[i]) {
  62923. hierarchyIds.push(mesh.id);
  62924. return true;
  62925. }
  62926. }
  62927. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62928. hierarchyIds.push(mesh.id);
  62929. return true;
  62930. }
  62931. return false;
  62932. };
  62933. var logOperation = function (operation, producer) {
  62934. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62935. };
  62936. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62937. if (addToScene === void 0) { addToScene = false; }
  62938. var container = new BABYLON.AssetContainer(scene);
  62939. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62940. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62941. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62942. // and avoid problems with multiple concurrent .babylon loads.
  62943. var log = "importScene has failed JSON parse";
  62944. try {
  62945. var parsedData = JSON.parse(data);
  62946. log = "";
  62947. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62948. var index;
  62949. var cache;
  62950. // Lights
  62951. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62952. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62953. var parsedLight = parsedData.lights[index];
  62954. var light = BABYLON.Light.Parse(parsedLight, scene);
  62955. if (light) {
  62956. container.lights.push(light);
  62957. log += (index === 0 ? "\n\tLights:" : "");
  62958. log += "\n\t\t" + light.toString(fullDetails);
  62959. }
  62960. }
  62961. }
  62962. // Animations
  62963. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62964. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62965. var parsedAnimation = parsedData.animations[index];
  62966. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62967. scene.animations.push(animation);
  62968. container.animations.push(animation);
  62969. log += (index === 0 ? "\n\tAnimations:" : "");
  62970. log += "\n\t\t" + animation.toString(fullDetails);
  62971. }
  62972. }
  62973. // Materials
  62974. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62975. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62976. var parsedMaterial = parsedData.materials[index];
  62977. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62978. container.materials.push(mat);
  62979. log += (index === 0 ? "\n\tMaterials:" : "");
  62980. log += "\n\t\t" + mat.toString(fullDetails);
  62981. }
  62982. }
  62983. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62984. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62985. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62986. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62987. container.multiMaterials.push(mmat);
  62988. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62989. log += "\n\t\t" + mmat.toString(fullDetails);
  62990. }
  62991. }
  62992. // Morph targets
  62993. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62994. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62995. var managerData = _a[_i];
  62996. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62997. }
  62998. }
  62999. // Skeletons
  63000. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63001. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  63002. var parsedSkeleton = parsedData.skeletons[index];
  63003. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63004. container.skeletons.push(skeleton);
  63005. log += (index === 0 ? "\n\tSkeletons:" : "");
  63006. log += "\n\t\t" + skeleton.toString(fullDetails);
  63007. }
  63008. }
  63009. // Geometries
  63010. var geometries = parsedData.geometries;
  63011. if (geometries !== undefined && geometries !== null) {
  63012. var addedGeometry = new Array();
  63013. // Boxes
  63014. var boxes = geometries.boxes;
  63015. if (boxes !== undefined && boxes !== null) {
  63016. for (index = 0, cache = boxes.length; index < cache; index++) {
  63017. var parsedBox = boxes[index];
  63018. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  63019. }
  63020. }
  63021. // Spheres
  63022. var spheres = geometries.spheres;
  63023. if (spheres !== undefined && spheres !== null) {
  63024. for (index = 0, cache = spheres.length; index < cache; index++) {
  63025. var parsedSphere = spheres[index];
  63026. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  63027. }
  63028. }
  63029. // Cylinders
  63030. var cylinders = geometries.cylinders;
  63031. if (cylinders !== undefined && cylinders !== null) {
  63032. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63033. var parsedCylinder = cylinders[index];
  63034. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63035. }
  63036. }
  63037. // Toruses
  63038. var toruses = geometries.toruses;
  63039. if (toruses !== undefined && toruses !== null) {
  63040. for (index = 0, cache = toruses.length; index < cache; index++) {
  63041. var parsedTorus = toruses[index];
  63042. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63043. }
  63044. }
  63045. // Grounds
  63046. var grounds = geometries.grounds;
  63047. if (grounds !== undefined && grounds !== null) {
  63048. for (index = 0, cache = grounds.length; index < cache; index++) {
  63049. var parsedGround = grounds[index];
  63050. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63051. }
  63052. }
  63053. // Planes
  63054. var planes = geometries.planes;
  63055. if (planes !== undefined && planes !== null) {
  63056. for (index = 0, cache = planes.length; index < cache; index++) {
  63057. var parsedPlane = planes[index];
  63058. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63059. }
  63060. }
  63061. // TorusKnots
  63062. var torusKnots = geometries.torusKnots;
  63063. if (torusKnots !== undefined && torusKnots !== null) {
  63064. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63065. var parsedTorusKnot = torusKnots[index];
  63066. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63067. }
  63068. }
  63069. // VertexData
  63070. var vertexData = geometries.vertexData;
  63071. if (vertexData !== undefined && vertexData !== null) {
  63072. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63073. var parsedVertexData = vertexData[index];
  63074. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63075. }
  63076. }
  63077. addedGeometry.forEach(function (g) {
  63078. if (g) {
  63079. container.geometries.push(g);
  63080. }
  63081. });
  63082. }
  63083. // Transform nodes
  63084. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63085. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63086. var parsedTransformNode = parsedData.transformNodes[index];
  63087. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63088. container.transformNodes.push(node);
  63089. }
  63090. }
  63091. // Meshes
  63092. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63093. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63094. var parsedMesh = parsedData.meshes[index];
  63095. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63096. container.meshes.push(mesh);
  63097. log += (index === 0 ? "\n\tMeshes:" : "");
  63098. log += "\n\t\t" + mesh.toString(fullDetails);
  63099. }
  63100. }
  63101. // Cameras
  63102. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63103. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63104. var parsedCamera = parsedData.cameras[index];
  63105. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63106. container.cameras.push(camera);
  63107. log += (index === 0 ? "\n\tCameras:" : "");
  63108. log += "\n\t\t" + camera.toString(fullDetails);
  63109. }
  63110. }
  63111. // Browsing all the graph to connect the dots
  63112. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63113. var camera = scene.cameras[index];
  63114. if (camera._waitingParentId) {
  63115. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63116. camera._waitingParentId = null;
  63117. }
  63118. }
  63119. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63120. var light_1 = scene.lights[index];
  63121. if (light_1 && light_1._waitingParentId) {
  63122. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63123. light_1._waitingParentId = null;
  63124. }
  63125. }
  63126. // Sounds
  63127. // TODO: add sound
  63128. var loadedSounds = [];
  63129. var loadedSound;
  63130. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63131. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63132. var parsedSound = parsedData.sounds[index];
  63133. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63134. if (!parsedSound.url)
  63135. parsedSound.url = parsedSound.name;
  63136. if (!loadedSounds[parsedSound.url]) {
  63137. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63138. loadedSounds[parsedSound.url] = loadedSound;
  63139. container.sounds.push(loadedSound);
  63140. }
  63141. else {
  63142. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63143. }
  63144. }
  63145. else {
  63146. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63147. }
  63148. }
  63149. }
  63150. loadedSounds = [];
  63151. // Connect parents & children and parse actions
  63152. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63153. var transformNode = scene.transformNodes[index];
  63154. if (transformNode._waitingParentId) {
  63155. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63156. transformNode._waitingParentId = null;
  63157. }
  63158. }
  63159. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63160. var mesh = scene.meshes[index];
  63161. if (mesh._waitingParentId) {
  63162. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63163. mesh._waitingParentId = null;
  63164. }
  63165. if (mesh._waitingActions) {
  63166. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63167. mesh._waitingActions = null;
  63168. }
  63169. }
  63170. // freeze world matrix application
  63171. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63172. var currentMesh = scene.meshes[index];
  63173. if (currentMesh._waitingFreezeWorldMatrix) {
  63174. currentMesh.freezeWorldMatrix();
  63175. currentMesh._waitingFreezeWorldMatrix = null;
  63176. }
  63177. else {
  63178. currentMesh.computeWorldMatrix(true);
  63179. }
  63180. }
  63181. // Particles Systems
  63182. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63183. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63184. var parsedParticleSystem = parsedData.particleSystems[index];
  63185. if (parsedParticleSystem.activeParticleCount) {
  63186. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63187. container.particleSystems.push(ps);
  63188. }
  63189. else {
  63190. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63191. container.particleSystems.push(ps);
  63192. }
  63193. }
  63194. }
  63195. // Lens flares
  63196. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63197. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63198. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63199. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63200. container.lensFlareSystems.push(lf);
  63201. }
  63202. }
  63203. // Shadows
  63204. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63205. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63206. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63207. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63208. container.shadowGenerators.push(sg);
  63209. }
  63210. }
  63211. // Lights exclusions / inclusions
  63212. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63213. var light_2 = scene.lights[index];
  63214. // Excluded check
  63215. if (light_2._excludedMeshesIds.length > 0) {
  63216. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63217. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63218. if (excludedMesh) {
  63219. light_2.excludedMeshes.push(excludedMesh);
  63220. }
  63221. }
  63222. light_2._excludedMeshesIds = [];
  63223. }
  63224. // Included check
  63225. if (light_2._includedOnlyMeshesIds.length > 0) {
  63226. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63227. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63228. if (includedOnlyMesh) {
  63229. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63230. }
  63231. }
  63232. light_2._includedOnlyMeshesIds = [];
  63233. }
  63234. }
  63235. // Actions (scene)
  63236. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63237. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63238. }
  63239. if (!addToScene) {
  63240. container.removeAllFromScene();
  63241. }
  63242. }
  63243. catch (err) {
  63244. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63245. if (onError) {
  63246. onError(msg, err);
  63247. }
  63248. else {
  63249. BABYLON.Tools.Log(msg);
  63250. throw err;
  63251. }
  63252. }
  63253. finally {
  63254. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63255. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63256. }
  63257. }
  63258. return container;
  63259. };
  63260. BABYLON.SceneLoader.RegisterPlugin({
  63261. name: "babylon.js",
  63262. extensions: ".babylon",
  63263. canDirectLoad: function (data) {
  63264. if (data.indexOf("babylon") !== -1) {
  63265. return true;
  63266. }
  63267. return false;
  63268. },
  63269. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63270. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63271. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63272. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63273. // and avoid problems with multiple concurrent .babylon loads.
  63274. var log = "importMesh has failed JSON parse";
  63275. try {
  63276. var parsedData = JSON.parse(data);
  63277. log = "";
  63278. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63279. if (!meshesNames) {
  63280. meshesNames = null;
  63281. }
  63282. else if (!Array.isArray(meshesNames)) {
  63283. meshesNames = [meshesNames];
  63284. }
  63285. var hierarchyIds = new Array();
  63286. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63287. var loadedSkeletonsIds = [];
  63288. var loadedMaterialsIds = [];
  63289. var index;
  63290. var cache;
  63291. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63292. var parsedMesh = parsedData.meshes[index];
  63293. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63294. if (meshesNames !== null) {
  63295. // Remove found mesh name from list.
  63296. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63297. }
  63298. //Geometry?
  63299. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63300. //does the file contain geometries?
  63301. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63302. //find the correct geometry and add it to the scene
  63303. var found = false;
  63304. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63305. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63306. return;
  63307. }
  63308. else {
  63309. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63310. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63311. switch (geometryType) {
  63312. case "boxes":
  63313. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63314. break;
  63315. case "spheres":
  63316. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63317. break;
  63318. case "cylinders":
  63319. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63320. break;
  63321. case "toruses":
  63322. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63323. break;
  63324. case "grounds":
  63325. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63326. break;
  63327. case "planes":
  63328. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63329. break;
  63330. case "torusKnots":
  63331. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63332. break;
  63333. case "vertexData":
  63334. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63335. break;
  63336. }
  63337. found = true;
  63338. }
  63339. });
  63340. }
  63341. });
  63342. if (found === false) {
  63343. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63344. }
  63345. }
  63346. }
  63347. // Material ?
  63348. if (parsedMesh.materialId) {
  63349. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63350. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63351. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63352. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63353. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63354. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63355. var subMatId = parsedMultiMaterial.materials[matIndex];
  63356. loadedMaterialsIds.push(subMatId);
  63357. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63358. if (mat) {
  63359. log += "\n\tMaterial " + mat.toString(fullDetails);
  63360. }
  63361. }
  63362. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63363. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63364. if (mmat) {
  63365. materialFound = true;
  63366. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63367. }
  63368. break;
  63369. }
  63370. }
  63371. }
  63372. if (materialFound === false) {
  63373. loadedMaterialsIds.push(parsedMesh.materialId);
  63374. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63375. if (!mat) {
  63376. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63377. }
  63378. else {
  63379. log += "\n\tMaterial " + mat.toString(fullDetails);
  63380. }
  63381. }
  63382. }
  63383. // Skeleton ?
  63384. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63385. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63386. if (skeletonAlreadyLoaded === false) {
  63387. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63388. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63389. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63390. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63391. skeletons.push(skeleton);
  63392. loadedSkeletonsIds.push(parsedSkeleton.id);
  63393. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63394. }
  63395. }
  63396. }
  63397. }
  63398. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63399. meshes.push(mesh);
  63400. log += "\n\tMesh " + mesh.toString(fullDetails);
  63401. }
  63402. }
  63403. // Connecting parents
  63404. var currentMesh;
  63405. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63406. currentMesh = scene.meshes[index];
  63407. if (currentMesh._waitingParentId) {
  63408. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63409. currentMesh._waitingParentId = null;
  63410. }
  63411. }
  63412. // freeze and compute world matrix application
  63413. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63414. currentMesh = scene.meshes[index];
  63415. if (currentMesh._waitingFreezeWorldMatrix) {
  63416. currentMesh.freezeWorldMatrix();
  63417. currentMesh._waitingFreezeWorldMatrix = null;
  63418. }
  63419. else {
  63420. currentMesh.computeWorldMatrix(true);
  63421. }
  63422. }
  63423. }
  63424. // Particles
  63425. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63426. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63427. var parsedParticleSystem = parsedData.particleSystems[index];
  63428. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63429. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63430. }
  63431. }
  63432. }
  63433. return true;
  63434. }
  63435. catch (err) {
  63436. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63437. if (onError) {
  63438. onError(msg, err);
  63439. }
  63440. else {
  63441. BABYLON.Tools.Log(msg);
  63442. throw err;
  63443. }
  63444. }
  63445. finally {
  63446. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63447. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63448. }
  63449. }
  63450. return false;
  63451. },
  63452. load: function (scene, data, rootUrl, onError) {
  63453. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63454. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63455. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63456. // and avoid problems with multiple concurrent .babylon loads.
  63457. var log = "importScene has failed JSON parse";
  63458. try {
  63459. var parsedData = JSON.parse(data);
  63460. log = "";
  63461. // Scene
  63462. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63463. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63464. }
  63465. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63466. scene.autoClear = parsedData.autoClear;
  63467. }
  63468. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63469. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63470. }
  63471. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63472. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63473. }
  63474. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63475. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63476. }
  63477. // Fog
  63478. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63479. scene.fogMode = parsedData.fogMode;
  63480. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63481. scene.fogStart = parsedData.fogStart;
  63482. scene.fogEnd = parsedData.fogEnd;
  63483. scene.fogDensity = parsedData.fogDensity;
  63484. log += "\tFog mode for scene: ";
  63485. switch (scene.fogMode) {
  63486. // getters not compiling, so using hardcoded
  63487. case 1:
  63488. log += "exp\n";
  63489. break;
  63490. case 2:
  63491. log += "exp2\n";
  63492. break;
  63493. case 3:
  63494. log += "linear\n";
  63495. break;
  63496. }
  63497. }
  63498. //Physics
  63499. if (parsedData.physicsEnabled) {
  63500. var physicsPlugin;
  63501. if (parsedData.physicsEngine === "cannon") {
  63502. physicsPlugin = new BABYLON.CannonJSPlugin();
  63503. }
  63504. else if (parsedData.physicsEngine === "oimo") {
  63505. physicsPlugin = new BABYLON.OimoJSPlugin();
  63506. }
  63507. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63508. //else - default engine, which is currently oimo
  63509. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63510. scene.enablePhysics(physicsGravity, physicsPlugin);
  63511. }
  63512. // Metadata
  63513. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63514. scene.metadata = parsedData.metadata;
  63515. }
  63516. //collisions, if defined. otherwise, default is true
  63517. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63518. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63519. }
  63520. scene.workerCollisions = !!parsedData.workerCollisions;
  63521. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63522. if (!container) {
  63523. return false;
  63524. }
  63525. if (parsedData.autoAnimate) {
  63526. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63527. }
  63528. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63529. scene.setActiveCameraByID(parsedData.activeCameraID);
  63530. }
  63531. // Environment texture
  63532. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63533. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63534. if (parsedData.createDefaultSkybox === true) {
  63535. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63536. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63537. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63538. }
  63539. }
  63540. // Finish
  63541. return true;
  63542. }
  63543. catch (err) {
  63544. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63545. if (onError) {
  63546. onError(msg, err);
  63547. }
  63548. else {
  63549. BABYLON.Tools.Log(msg);
  63550. throw err;
  63551. }
  63552. }
  63553. finally {
  63554. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63555. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63556. }
  63557. }
  63558. return false;
  63559. },
  63560. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63561. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63562. return container;
  63563. }
  63564. });
  63565. })(BABYLON || (BABYLON = {}));
  63566. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63567. "use strict";
  63568. var BABYLON;
  63569. (function (BABYLON) {
  63570. var FilesInput = /** @class */ (function () {
  63571. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63572. this.onProcessFileCallback = function () { return true; };
  63573. this._engine = engine;
  63574. this._currentScene = scene;
  63575. this._sceneLoadedCallback = sceneLoadedCallback;
  63576. this._progressCallback = progressCallback;
  63577. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63578. this._textureLoadingCallback = textureLoadingCallback;
  63579. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63580. this._onReloadCallback = onReloadCallback;
  63581. this._errorCallback = errorCallback;
  63582. }
  63583. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63584. var _this = this;
  63585. if (elementToMonitor) {
  63586. this._elementToMonitor = elementToMonitor;
  63587. this._dragEnterHandler = function (e) { _this.drag(e); };
  63588. this._dragOverHandler = function (e) { _this.drag(e); };
  63589. this._dropHandler = function (e) { _this.drop(e); };
  63590. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63591. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63592. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63593. }
  63594. };
  63595. FilesInput.prototype.dispose = function () {
  63596. if (!this._elementToMonitor) {
  63597. return;
  63598. }
  63599. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63600. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63601. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63602. };
  63603. FilesInput.prototype.renderFunction = function () {
  63604. if (this._additionalRenderLoopLogicCallback) {
  63605. this._additionalRenderLoopLogicCallback();
  63606. }
  63607. if (this._currentScene) {
  63608. if (this._textureLoadingCallback) {
  63609. var remaining = this._currentScene.getWaitingItemsCount();
  63610. if (remaining > 0) {
  63611. this._textureLoadingCallback(remaining);
  63612. }
  63613. }
  63614. this._currentScene.render();
  63615. }
  63616. };
  63617. FilesInput.prototype.drag = function (e) {
  63618. e.stopPropagation();
  63619. e.preventDefault();
  63620. };
  63621. FilesInput.prototype.drop = function (eventDrop) {
  63622. eventDrop.stopPropagation();
  63623. eventDrop.preventDefault();
  63624. this.loadFiles(eventDrop);
  63625. };
  63626. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63627. var _this = this;
  63628. var reader = folder.createReader();
  63629. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63630. reader.readEntries(function (entries) {
  63631. remaining.count += entries.length;
  63632. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63633. var entry = entries_1[_i];
  63634. if (entry.isFile) {
  63635. entry.file(function (file) {
  63636. file.correctName = relativePath + file.name;
  63637. files.push(file);
  63638. if (--remaining.count === 0) {
  63639. callback();
  63640. }
  63641. });
  63642. }
  63643. else if (entry.isDirectory) {
  63644. _this._traverseFolder(entry, files, remaining, callback);
  63645. }
  63646. }
  63647. if (--remaining.count) {
  63648. callback();
  63649. }
  63650. });
  63651. };
  63652. FilesInput.prototype._processFiles = function (files) {
  63653. for (var i = 0; i < files.length; i++) {
  63654. var name = files[i].correctName.toLowerCase();
  63655. var extension = name.split('.').pop();
  63656. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63657. continue;
  63658. }
  63659. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63660. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63661. this._sceneFileToLoad = files[i];
  63662. }
  63663. else {
  63664. FilesInput.FilesToLoad[name] = files[i];
  63665. }
  63666. }
  63667. };
  63668. FilesInput.prototype.loadFiles = function (event) {
  63669. var _this = this;
  63670. if (this._startingProcessingFilesCallback)
  63671. this._startingProcessingFilesCallback();
  63672. // Handling data transfer via drag'n'drop
  63673. if (event && event.dataTransfer && event.dataTransfer.files) {
  63674. this._filesToLoad = event.dataTransfer.files;
  63675. }
  63676. // Handling files from input files
  63677. if (event && event.target && event.target.files) {
  63678. this._filesToLoad = event.target.files;
  63679. }
  63680. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63681. var files_1 = new Array();
  63682. var folders = [];
  63683. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63684. for (var i = 0; i < this._filesToLoad.length; i++) {
  63685. var fileToLoad = this._filesToLoad[i];
  63686. var name_1 = fileToLoad.name.toLowerCase();
  63687. var entry = void 0;
  63688. fileToLoad.correctName = name_1;
  63689. if (items) {
  63690. var item = items[i];
  63691. if (item.getAsEntry) {
  63692. entry = item.getAsEntry();
  63693. }
  63694. else if (item.webkitGetAsEntry) {
  63695. entry = item.webkitGetAsEntry();
  63696. }
  63697. }
  63698. if (!entry) {
  63699. files_1.push(fileToLoad);
  63700. }
  63701. else {
  63702. if (entry.isDirectory) {
  63703. folders.push(entry);
  63704. }
  63705. else {
  63706. files_1.push(fileToLoad);
  63707. }
  63708. }
  63709. }
  63710. if (folders.length === 0) {
  63711. this._processFiles(files_1);
  63712. this._processReload();
  63713. }
  63714. else {
  63715. var remaining = { count: folders.length };
  63716. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  63717. var folder = folders_1[_i];
  63718. this._traverseFolder(folder, files_1, remaining, function () {
  63719. _this._processFiles(files_1);
  63720. if (remaining.count === 0) {
  63721. _this._processReload();
  63722. }
  63723. });
  63724. }
  63725. }
  63726. }
  63727. };
  63728. FilesInput.prototype._processReload = function () {
  63729. if (this._onReloadCallback) {
  63730. this._onReloadCallback(this._sceneFileToLoad);
  63731. }
  63732. else {
  63733. this.reload();
  63734. }
  63735. };
  63736. FilesInput.prototype.reload = function () {
  63737. var _this = this;
  63738. // If a scene file has been provided
  63739. if (this._sceneFileToLoad) {
  63740. if (this._currentScene) {
  63741. if (BABYLON.Tools.errorsCount > 0) {
  63742. BABYLON.Tools.ClearLogCache();
  63743. }
  63744. this._engine.stopRenderLoop();
  63745. this._currentScene.dispose();
  63746. }
  63747. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  63748. if (_this._progressCallback) {
  63749. _this._progressCallback(progress);
  63750. }
  63751. }).then(function (scene) {
  63752. _this._currentScene = scene;
  63753. if (_this._sceneLoadedCallback) {
  63754. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  63755. }
  63756. // Wait for textures and shaders to be ready
  63757. _this._currentScene.executeWhenReady(function () {
  63758. _this._engine.runRenderLoop(function () {
  63759. _this.renderFunction();
  63760. });
  63761. });
  63762. }).catch(function (error) {
  63763. if (_this._errorCallback) {
  63764. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  63765. }
  63766. });
  63767. }
  63768. else {
  63769. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63770. }
  63771. };
  63772. FilesInput.FilesToLoad = {};
  63773. return FilesInput;
  63774. }());
  63775. BABYLON.FilesInput = FilesInput;
  63776. })(BABYLON || (BABYLON = {}));
  63777. //# sourceMappingURL=babylon.filesInput.js.map
  63778. "use strict";
  63779. var BABYLON;
  63780. (function (BABYLON) {
  63781. /**
  63782. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63783. * The underlying implementation relies on an associative array to ensure the best performances.
  63784. * The value can be anything including 'null' but except 'undefined'
  63785. */
  63786. var StringDictionary = /** @class */ (function () {
  63787. function StringDictionary() {
  63788. this._count = 0;
  63789. this._data = {};
  63790. }
  63791. /**
  63792. * This will clear this dictionary and copy the content from the 'source' one.
  63793. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63794. * @param source the dictionary to take the content from and copy to this dictionary
  63795. */
  63796. StringDictionary.prototype.copyFrom = function (source) {
  63797. var _this = this;
  63798. this.clear();
  63799. source.forEach(function (t, v) { return _this.add(t, v); });
  63800. };
  63801. /**
  63802. * Get a value based from its key
  63803. * @param key the given key to get the matching value from
  63804. * @return the value if found, otherwise undefined is returned
  63805. */
  63806. StringDictionary.prototype.get = function (key) {
  63807. var val = this._data[key];
  63808. if (val !== undefined) {
  63809. return val;
  63810. }
  63811. return undefined;
  63812. };
  63813. /**
  63814. * Get a value from its key or add it if it doesn't exist.
  63815. * This method will ensure you that a given key/data will be present in the dictionary.
  63816. * @param key the given key to get the matching value from
  63817. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63818. * The factory will only be invoked if there's no data for the given key.
  63819. * @return the value corresponding to the key.
  63820. */
  63821. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63822. var val = this.get(key);
  63823. if (val !== undefined) {
  63824. return val;
  63825. }
  63826. val = factory(key);
  63827. if (val) {
  63828. this.add(key, val);
  63829. }
  63830. return val;
  63831. };
  63832. /**
  63833. * Get a value from its key if present in the dictionary otherwise add it
  63834. * @param key the key to get the value from
  63835. * @param val if there's no such key/value pair in the dictionary add it with this value
  63836. * @return the value corresponding to the key
  63837. */
  63838. StringDictionary.prototype.getOrAdd = function (key, val) {
  63839. var curVal = this.get(key);
  63840. if (curVal !== undefined) {
  63841. return curVal;
  63842. }
  63843. this.add(key, val);
  63844. return val;
  63845. };
  63846. /**
  63847. * Check if there's a given key in the dictionary
  63848. * @param key the key to check for
  63849. * @return true if the key is present, false otherwise
  63850. */
  63851. StringDictionary.prototype.contains = function (key) {
  63852. return this._data[key] !== undefined;
  63853. };
  63854. /**
  63855. * Add a new key and its corresponding value
  63856. * @param key the key to add
  63857. * @param value the value corresponding to the key
  63858. * @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
  63859. */
  63860. StringDictionary.prototype.add = function (key, value) {
  63861. if (this._data[key] !== undefined) {
  63862. return false;
  63863. }
  63864. this._data[key] = value;
  63865. ++this._count;
  63866. return true;
  63867. };
  63868. StringDictionary.prototype.set = function (key, value) {
  63869. if (this._data[key] === undefined) {
  63870. return false;
  63871. }
  63872. this._data[key] = value;
  63873. return true;
  63874. };
  63875. /**
  63876. * Get the element of the given key and remove it from the dictionary
  63877. * @param key
  63878. */
  63879. StringDictionary.prototype.getAndRemove = function (key) {
  63880. var val = this.get(key);
  63881. if (val !== undefined) {
  63882. delete this._data[key];
  63883. --this._count;
  63884. return val;
  63885. }
  63886. return null;
  63887. };
  63888. /**
  63889. * Remove a key/value from the dictionary.
  63890. * @param key the key to remove
  63891. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63892. */
  63893. StringDictionary.prototype.remove = function (key) {
  63894. if (this.contains(key)) {
  63895. delete this._data[key];
  63896. --this._count;
  63897. return true;
  63898. }
  63899. return false;
  63900. };
  63901. /**
  63902. * Clear the whole content of the dictionary
  63903. */
  63904. StringDictionary.prototype.clear = function () {
  63905. this._data = {};
  63906. this._count = 0;
  63907. };
  63908. Object.defineProperty(StringDictionary.prototype, "count", {
  63909. get: function () {
  63910. return this._count;
  63911. },
  63912. enumerable: true,
  63913. configurable: true
  63914. });
  63915. /**
  63916. * Execute a callback on each key/val of the dictionary.
  63917. * Note that you can remove any element in this dictionary in the callback implementation
  63918. * @param callback the callback to execute on a given key/value pair
  63919. */
  63920. StringDictionary.prototype.forEach = function (callback) {
  63921. for (var cur in this._data) {
  63922. var val = this._data[cur];
  63923. callback(cur, val);
  63924. }
  63925. };
  63926. /**
  63927. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63928. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63929. * Note that you can remove any element in this dictionary in the callback implementation
  63930. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63931. */
  63932. StringDictionary.prototype.first = function (callback) {
  63933. for (var cur in this._data) {
  63934. var val = this._data[cur];
  63935. var res = callback(cur, val);
  63936. if (res) {
  63937. return res;
  63938. }
  63939. }
  63940. return null;
  63941. };
  63942. return StringDictionary;
  63943. }());
  63944. BABYLON.StringDictionary = StringDictionary;
  63945. })(BABYLON || (BABYLON = {}));
  63946. //# sourceMappingURL=babylon.stringDictionary.js.map
  63947. "use strict";
  63948. var BABYLON;
  63949. (function (BABYLON) {
  63950. var Tags = /** @class */ (function () {
  63951. function Tags() {
  63952. }
  63953. Tags.EnableFor = function (obj) {
  63954. obj._tags = obj._tags || {};
  63955. obj.hasTags = function () {
  63956. return Tags.HasTags(obj);
  63957. };
  63958. obj.addTags = function (tagsString) {
  63959. return Tags.AddTagsTo(obj, tagsString);
  63960. };
  63961. obj.removeTags = function (tagsString) {
  63962. return Tags.RemoveTagsFrom(obj, tagsString);
  63963. };
  63964. obj.matchesTagsQuery = function (tagsQuery) {
  63965. return Tags.MatchesQuery(obj, tagsQuery);
  63966. };
  63967. };
  63968. Tags.DisableFor = function (obj) {
  63969. delete obj._tags;
  63970. delete obj.hasTags;
  63971. delete obj.addTags;
  63972. delete obj.removeTags;
  63973. delete obj.matchesTagsQuery;
  63974. };
  63975. Tags.HasTags = function (obj) {
  63976. if (!obj._tags) {
  63977. return false;
  63978. }
  63979. return !BABYLON.Tools.IsEmpty(obj._tags);
  63980. };
  63981. Tags.GetTags = function (obj, asString) {
  63982. if (asString === void 0) { asString = true; }
  63983. if (!obj._tags) {
  63984. return null;
  63985. }
  63986. if (asString) {
  63987. var tagsArray = [];
  63988. for (var tag in obj._tags) {
  63989. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63990. tagsArray.push(tag);
  63991. }
  63992. }
  63993. return tagsArray.join(" ");
  63994. }
  63995. else {
  63996. return obj._tags;
  63997. }
  63998. };
  63999. // the tags 'true' and 'false' are reserved and cannot be used as tags
  64000. // a tag cannot start with '||', '&&', and '!'
  64001. // it cannot contain whitespaces
  64002. Tags.AddTagsTo = function (obj, tagsString) {
  64003. if (!tagsString) {
  64004. return;
  64005. }
  64006. if (typeof tagsString !== "string") {
  64007. return;
  64008. }
  64009. var tags = tagsString.split(" ");
  64010. tags.forEach(function (tag, index, array) {
  64011. Tags._AddTagTo(obj, tag);
  64012. });
  64013. };
  64014. Tags._AddTagTo = function (obj, tag) {
  64015. tag = tag.trim();
  64016. if (tag === "" || tag === "true" || tag === "false") {
  64017. return;
  64018. }
  64019. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  64020. return;
  64021. }
  64022. Tags.EnableFor(obj);
  64023. obj._tags[tag] = true;
  64024. };
  64025. Tags.RemoveTagsFrom = function (obj, tagsString) {
  64026. if (!Tags.HasTags(obj)) {
  64027. return;
  64028. }
  64029. var tags = tagsString.split(" ");
  64030. for (var t in tags) {
  64031. Tags._RemoveTagFrom(obj, tags[t]);
  64032. }
  64033. };
  64034. Tags._RemoveTagFrom = function (obj, tag) {
  64035. delete obj._tags[tag];
  64036. };
  64037. Tags.MatchesQuery = function (obj, tagsQuery) {
  64038. if (tagsQuery === undefined) {
  64039. return true;
  64040. }
  64041. if (tagsQuery === "") {
  64042. return Tags.HasTags(obj);
  64043. }
  64044. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64045. };
  64046. return Tags;
  64047. }());
  64048. BABYLON.Tags = Tags;
  64049. })(BABYLON || (BABYLON = {}));
  64050. //# sourceMappingURL=babylon.tags.js.map
  64051. "use strict";
  64052. var BABYLON;
  64053. (function (BABYLON) {
  64054. var AndOrNotEvaluator = /** @class */ (function () {
  64055. function AndOrNotEvaluator() {
  64056. }
  64057. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64058. if (!query.match(/\([^\(\)]*\)/g)) {
  64059. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64060. }
  64061. else {
  64062. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64063. // remove parenthesis
  64064. r = r.slice(1, r.length - 1);
  64065. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64066. });
  64067. }
  64068. if (query === "true") {
  64069. return true;
  64070. }
  64071. if (query === "false") {
  64072. return false;
  64073. }
  64074. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64075. };
  64076. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64077. evaluateCallback = evaluateCallback || (function (r) {
  64078. return r === "true" ? true : false;
  64079. });
  64080. var result;
  64081. var or = parenthesisContent.split("||");
  64082. for (var i in or) {
  64083. if (or.hasOwnProperty(i)) {
  64084. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64085. var and = ori.split("&&");
  64086. if (and.length > 1) {
  64087. for (var j = 0; j < and.length; ++j) {
  64088. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64089. if (andj !== "true" && andj !== "false") {
  64090. if (andj[0] === "!") {
  64091. result = !evaluateCallback(andj.substring(1));
  64092. }
  64093. else {
  64094. result = evaluateCallback(andj);
  64095. }
  64096. }
  64097. else {
  64098. result = andj === "true" ? true : false;
  64099. }
  64100. if (!result) {
  64101. ori = "false";
  64102. break;
  64103. }
  64104. }
  64105. }
  64106. if (result || ori === "true") {
  64107. result = true;
  64108. break;
  64109. }
  64110. // result equals false (or undefined)
  64111. if (ori !== "true" && ori !== "false") {
  64112. if (ori[0] === "!") {
  64113. result = !evaluateCallback(ori.substring(1));
  64114. }
  64115. else {
  64116. result = evaluateCallback(ori);
  64117. }
  64118. }
  64119. else {
  64120. result = ori === "true" ? true : false;
  64121. }
  64122. }
  64123. }
  64124. // the whole parenthesis scope is replaced by 'true' or 'false'
  64125. return result ? "true" : "false";
  64126. };
  64127. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64128. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64129. // remove whitespaces
  64130. r = r.replace(/[\s]/g, function () { return ""; });
  64131. return r.length % 2 ? "!" : "";
  64132. });
  64133. booleanString = booleanString.trim();
  64134. if (booleanString === "!true") {
  64135. booleanString = "false";
  64136. }
  64137. else if (booleanString === "!false") {
  64138. booleanString = "true";
  64139. }
  64140. return booleanString;
  64141. };
  64142. return AndOrNotEvaluator;
  64143. }());
  64144. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64145. })(BABYLON || (BABYLON = {}));
  64146. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64147. "use strict";
  64148. var BABYLON;
  64149. (function (BABYLON) {
  64150. var Database = /** @class */ (function () {
  64151. function Database(urlToScene, callbackManifestChecked) {
  64152. // Handling various flavors of prefixed version of IndexedDB
  64153. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64154. this.callbackManifestChecked = callbackManifestChecked;
  64155. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64156. this.db = null;
  64157. this._enableSceneOffline = false;
  64158. this._enableTexturesOffline = false;
  64159. this.manifestVersionFound = 0;
  64160. this.mustUpdateRessources = false;
  64161. this.hasReachedQuota = false;
  64162. if (!Database.IDBStorageEnabled) {
  64163. this.callbackManifestChecked(true);
  64164. }
  64165. else {
  64166. this.checkManifestFile();
  64167. }
  64168. }
  64169. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64170. get: function () {
  64171. return this._enableSceneOffline;
  64172. },
  64173. enumerable: true,
  64174. configurable: true
  64175. });
  64176. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64177. get: function () {
  64178. return this._enableTexturesOffline;
  64179. },
  64180. enumerable: true,
  64181. configurable: true
  64182. });
  64183. Database.prototype.checkManifestFile = function () {
  64184. var _this = this;
  64185. var noManifestFile = function () {
  64186. _this._enableSceneOffline = false;
  64187. _this._enableTexturesOffline = false;
  64188. _this.callbackManifestChecked(false);
  64189. };
  64190. var timeStampUsed = false;
  64191. var manifestURL = this.currentSceneUrl + ".manifest";
  64192. var xhr = new XMLHttpRequest();
  64193. if (navigator.onLine) {
  64194. // Adding a timestamp to by-pass browsers' cache
  64195. timeStampUsed = true;
  64196. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64197. }
  64198. xhr.open("GET", manifestURL, true);
  64199. xhr.addEventListener("load", function () {
  64200. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64201. try {
  64202. var manifestFile = JSON.parse(xhr.response);
  64203. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64204. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64205. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64206. _this.manifestVersionFound = manifestFile.version;
  64207. }
  64208. if (_this.callbackManifestChecked) {
  64209. _this.callbackManifestChecked(true);
  64210. }
  64211. }
  64212. catch (ex) {
  64213. noManifestFile();
  64214. }
  64215. }
  64216. else {
  64217. noManifestFile();
  64218. }
  64219. }, false);
  64220. xhr.addEventListener("error", function (event) {
  64221. if (timeStampUsed) {
  64222. timeStampUsed = false;
  64223. // Let's retry without the timeStamp
  64224. // It could fail when coupled with HTML5 Offline API
  64225. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64226. xhr.open("GET", retryManifestURL, true);
  64227. xhr.send();
  64228. }
  64229. else {
  64230. noManifestFile();
  64231. }
  64232. }, false);
  64233. try {
  64234. xhr.send();
  64235. }
  64236. catch (ex) {
  64237. BABYLON.Tools.Error("Error on XHR send request.");
  64238. this.callbackManifestChecked(false);
  64239. }
  64240. };
  64241. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64242. var _this = this;
  64243. var handleError = function () {
  64244. _this.isSupported = false;
  64245. if (errorCallback)
  64246. errorCallback();
  64247. };
  64248. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64249. // Your browser doesn't support IndexedDB
  64250. this.isSupported = false;
  64251. if (errorCallback)
  64252. errorCallback();
  64253. }
  64254. else {
  64255. // If the DB hasn't been opened or created yet
  64256. if (!this.db) {
  64257. this.hasReachedQuota = false;
  64258. this.isSupported = true;
  64259. var request = this.idbFactory.open("babylonjs", 1);
  64260. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64261. request.onerror = function (event) {
  64262. handleError();
  64263. };
  64264. // executes when a version change transaction cannot complete due to other active transactions
  64265. request.onblocked = function (event) {
  64266. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64267. handleError();
  64268. };
  64269. // DB has been opened successfully
  64270. request.onsuccess = function (event) {
  64271. _this.db = request.result;
  64272. successCallback();
  64273. };
  64274. // Initialization of the DB. Creating Scenes & Textures stores
  64275. request.onupgradeneeded = function (event) {
  64276. _this.db = (event.target).result;
  64277. if (_this.db) {
  64278. try {
  64279. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64280. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64281. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64282. }
  64283. catch (ex) {
  64284. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64285. handleError();
  64286. }
  64287. }
  64288. };
  64289. }
  64290. else {
  64291. if (successCallback)
  64292. successCallback();
  64293. }
  64294. }
  64295. };
  64296. Database.prototype.loadImageFromDB = function (url, image) {
  64297. var _this = this;
  64298. var completeURL = Database.ReturnFullUrlLocation(url);
  64299. var saveAndLoadImage = function () {
  64300. if (!_this.hasReachedQuota && _this.db !== null) {
  64301. // the texture is not yet in the DB, let's try to save it
  64302. _this._saveImageIntoDBAsync(completeURL, image);
  64303. }
  64304. else {
  64305. image.src = url;
  64306. }
  64307. };
  64308. if (!this.mustUpdateRessources) {
  64309. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64310. }
  64311. else {
  64312. saveAndLoadImage();
  64313. }
  64314. };
  64315. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64316. if (this.isSupported && this.db !== null) {
  64317. var texture;
  64318. var transaction = this.db.transaction(["textures"]);
  64319. transaction.onabort = function (event) {
  64320. image.src = url;
  64321. };
  64322. transaction.oncomplete = function (event) {
  64323. var blobTextureURL;
  64324. if (texture) {
  64325. var URL = window.URL || window.webkitURL;
  64326. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64327. image.onerror = function () {
  64328. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64329. image.src = url;
  64330. };
  64331. image.src = blobTextureURL;
  64332. }
  64333. else {
  64334. notInDBCallback();
  64335. }
  64336. };
  64337. var getRequest = transaction.objectStore("textures").get(url);
  64338. getRequest.onsuccess = function (event) {
  64339. texture = (event.target).result;
  64340. };
  64341. getRequest.onerror = function (event) {
  64342. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64343. image.src = url;
  64344. };
  64345. }
  64346. else {
  64347. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64348. image.src = url;
  64349. }
  64350. };
  64351. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64352. var _this = this;
  64353. if (this.isSupported) {
  64354. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64355. var generateBlobUrl = function () {
  64356. var blobTextureURL;
  64357. if (blob) {
  64358. var URL = window.URL || window.webkitURL;
  64359. try {
  64360. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64361. }
  64362. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64363. catch (ex) {
  64364. blobTextureURL = URL.createObjectURL(blob);
  64365. }
  64366. }
  64367. if (blobTextureURL) {
  64368. image.src = blobTextureURL;
  64369. }
  64370. };
  64371. if (Database.IsUASupportingBlobStorage) {
  64372. var xhr = new XMLHttpRequest(), blob;
  64373. xhr.open("GET", url, true);
  64374. xhr.responseType = "blob";
  64375. xhr.addEventListener("load", function () {
  64376. if (xhr.status === 200 && _this.db) {
  64377. // Blob as response (XHR2)
  64378. blob = xhr.response;
  64379. var transaction = _this.db.transaction(["textures"], "readwrite");
  64380. // the transaction could abort because of a QuotaExceededError error
  64381. transaction.onabort = function (event) {
  64382. try {
  64383. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64384. var srcElement = (event.srcElement || event.target);
  64385. var error = srcElement.error;
  64386. if (error && error.name === "QuotaExceededError") {
  64387. _this.hasReachedQuota = true;
  64388. }
  64389. }
  64390. catch (ex) { }
  64391. generateBlobUrl();
  64392. };
  64393. transaction.oncomplete = function (event) {
  64394. generateBlobUrl();
  64395. };
  64396. var newTexture = { textureUrl: url, data: blob };
  64397. try {
  64398. // Put the blob into the dabase
  64399. var addRequest = transaction.objectStore("textures").put(newTexture);
  64400. addRequest.onsuccess = function (event) {
  64401. };
  64402. addRequest.onerror = function (event) {
  64403. generateBlobUrl();
  64404. };
  64405. }
  64406. catch (ex) {
  64407. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64408. if (ex.code === 25) {
  64409. Database.IsUASupportingBlobStorage = false;
  64410. }
  64411. image.src = url;
  64412. }
  64413. }
  64414. else {
  64415. image.src = url;
  64416. }
  64417. }, false);
  64418. xhr.addEventListener("error", function (event) {
  64419. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64420. image.src = url;
  64421. }, false);
  64422. xhr.send();
  64423. }
  64424. else {
  64425. image.src = url;
  64426. }
  64427. }
  64428. else {
  64429. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64430. image.src = url;
  64431. }
  64432. };
  64433. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64434. var _this = this;
  64435. var updateVersion = function () {
  64436. // the version is not yet in the DB or we need to update it
  64437. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64438. };
  64439. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64440. };
  64441. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64442. var _this = this;
  64443. if (this.isSupported && this.db) {
  64444. var version;
  64445. try {
  64446. var transaction = this.db.transaction(["versions"]);
  64447. transaction.oncomplete = function (event) {
  64448. if (version) {
  64449. // If the version in the JSON file is > than the version in DB
  64450. if (_this.manifestVersionFound > version.data) {
  64451. _this.mustUpdateRessources = true;
  64452. updateInDBCallback();
  64453. }
  64454. else {
  64455. callback(version.data);
  64456. }
  64457. }
  64458. else {
  64459. _this.mustUpdateRessources = true;
  64460. updateInDBCallback();
  64461. }
  64462. };
  64463. transaction.onabort = function (event) {
  64464. callback(-1);
  64465. };
  64466. var getRequest = transaction.objectStore("versions").get(url);
  64467. getRequest.onsuccess = function (event) {
  64468. version = (event.target).result;
  64469. };
  64470. getRequest.onerror = function (event) {
  64471. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64472. callback(-1);
  64473. };
  64474. }
  64475. catch (ex) {
  64476. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64477. callback(-1);
  64478. }
  64479. }
  64480. else {
  64481. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64482. callback(-1);
  64483. }
  64484. };
  64485. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64486. var _this = this;
  64487. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64488. try {
  64489. // Open a transaction to the database
  64490. var transaction = this.db.transaction(["versions"], "readwrite");
  64491. // the transaction could abort because of a QuotaExceededError error
  64492. transaction.onabort = function (event) {
  64493. try {
  64494. var error = event.srcElement['error'];
  64495. if (error && error.name === "QuotaExceededError") {
  64496. _this.hasReachedQuota = true;
  64497. }
  64498. }
  64499. catch (ex) { }
  64500. callback(-1);
  64501. };
  64502. transaction.oncomplete = function (event) {
  64503. callback(_this.manifestVersionFound);
  64504. };
  64505. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64506. // Put the scene into the database
  64507. var addRequest = transaction.objectStore("versions").put(newVersion);
  64508. addRequest.onsuccess = function (event) {
  64509. };
  64510. addRequest.onerror = function (event) {
  64511. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64512. };
  64513. }
  64514. catch (ex) {
  64515. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64516. callback(-1);
  64517. }
  64518. }
  64519. else {
  64520. callback(-1);
  64521. }
  64522. };
  64523. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64524. var _this = this;
  64525. var completeUrl = Database.ReturnFullUrlLocation(url);
  64526. var saveAndLoadFile = function () {
  64527. // the scene is not yet in the DB, let's try to save it
  64528. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64529. };
  64530. this._checkVersionFromDB(completeUrl, function (version) {
  64531. if (version !== -1) {
  64532. if (!_this.mustUpdateRessources) {
  64533. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64534. }
  64535. else {
  64536. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64537. }
  64538. }
  64539. else {
  64540. if (errorCallback) {
  64541. errorCallback();
  64542. }
  64543. }
  64544. });
  64545. };
  64546. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64547. if (this.isSupported && this.db) {
  64548. var targetStore;
  64549. if (url.indexOf(".babylon") !== -1) {
  64550. targetStore = "scenes";
  64551. }
  64552. else {
  64553. targetStore = "textures";
  64554. }
  64555. var file;
  64556. var transaction = this.db.transaction([targetStore]);
  64557. transaction.oncomplete = function (event) {
  64558. if (file) {
  64559. callback(file.data);
  64560. }
  64561. else {
  64562. notInDBCallback();
  64563. }
  64564. };
  64565. transaction.onabort = function (event) {
  64566. notInDBCallback();
  64567. };
  64568. var getRequest = transaction.objectStore(targetStore).get(url);
  64569. getRequest.onsuccess = function (event) {
  64570. file = (event.target).result;
  64571. };
  64572. getRequest.onerror = function (event) {
  64573. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64574. notInDBCallback();
  64575. };
  64576. }
  64577. else {
  64578. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64579. callback();
  64580. }
  64581. };
  64582. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64583. var _this = this;
  64584. if (this.isSupported) {
  64585. var targetStore;
  64586. if (url.indexOf(".babylon") !== -1) {
  64587. targetStore = "scenes";
  64588. }
  64589. else {
  64590. targetStore = "textures";
  64591. }
  64592. // Create XHR
  64593. var xhr = new XMLHttpRequest();
  64594. var fileData;
  64595. xhr.open("GET", url, true);
  64596. if (useArrayBuffer) {
  64597. xhr.responseType = "arraybuffer";
  64598. }
  64599. if (progressCallback) {
  64600. xhr.onprogress = progressCallback;
  64601. }
  64602. xhr.addEventListener("load", function () {
  64603. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64604. // Blob as response (XHR2)
  64605. //fileData = xhr.responseText;
  64606. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64607. if (!_this.hasReachedQuota && _this.db) {
  64608. // Open a transaction to the database
  64609. var transaction = _this.db.transaction([targetStore], "readwrite");
  64610. // the transaction could abort because of a QuotaExceededError error
  64611. transaction.onabort = function (event) {
  64612. try {
  64613. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64614. var error = event.srcElement['error'];
  64615. if (error && error.name === "QuotaExceededError") {
  64616. _this.hasReachedQuota = true;
  64617. }
  64618. }
  64619. catch (ex) { }
  64620. callback(fileData);
  64621. };
  64622. transaction.oncomplete = function (event) {
  64623. callback(fileData);
  64624. };
  64625. var newFile;
  64626. if (targetStore === "scenes") {
  64627. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64628. }
  64629. else {
  64630. newFile = { textureUrl: url, data: fileData };
  64631. }
  64632. try {
  64633. // Put the scene into the database
  64634. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64635. addRequest.onsuccess = function (event) {
  64636. };
  64637. addRequest.onerror = function (event) {
  64638. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64639. };
  64640. }
  64641. catch (ex) {
  64642. callback(fileData);
  64643. }
  64644. }
  64645. else {
  64646. callback(fileData);
  64647. }
  64648. }
  64649. else {
  64650. callback();
  64651. }
  64652. }, false);
  64653. xhr.addEventListener("error", function (event) {
  64654. BABYLON.Tools.Error("error on XHR request.");
  64655. callback();
  64656. }, false);
  64657. xhr.send();
  64658. }
  64659. else {
  64660. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64661. callback();
  64662. }
  64663. };
  64664. Database.IsUASupportingBlobStorage = true;
  64665. Database.IDBStorageEnabled = true;
  64666. Database.parseURL = function (url) {
  64667. var a = document.createElement('a');
  64668. a.href = url;
  64669. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64670. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64671. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64672. return absLocation;
  64673. };
  64674. Database.ReturnFullUrlLocation = function (url) {
  64675. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64676. return (Database.parseURL(window.location.href) + url);
  64677. }
  64678. else {
  64679. return url;
  64680. }
  64681. };
  64682. return Database;
  64683. }());
  64684. BABYLON.Database = Database;
  64685. })(BABYLON || (BABYLON = {}));
  64686. //# sourceMappingURL=babylon.database.js.map
  64687. "use strict";
  64688. var BABYLON;
  64689. (function (BABYLON) {
  64690. var FresnelParameters = /** @class */ (function () {
  64691. function FresnelParameters() {
  64692. this._isEnabled = true;
  64693. this.leftColor = BABYLON.Color3.White();
  64694. this.rightColor = BABYLON.Color3.Black();
  64695. this.bias = 0;
  64696. this.power = 1;
  64697. }
  64698. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64699. get: function () {
  64700. return this._isEnabled;
  64701. },
  64702. set: function (value) {
  64703. if (this._isEnabled === value) {
  64704. return;
  64705. }
  64706. this._isEnabled = value;
  64707. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64708. },
  64709. enumerable: true,
  64710. configurable: true
  64711. });
  64712. FresnelParameters.prototype.clone = function () {
  64713. var newFresnelParameters = new FresnelParameters();
  64714. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  64715. return newFresnelParameters;
  64716. };
  64717. FresnelParameters.prototype.serialize = function () {
  64718. var serializationObject = {};
  64719. serializationObject.isEnabled = this.isEnabled;
  64720. serializationObject.leftColor = this.leftColor;
  64721. serializationObject.rightColor = this.rightColor;
  64722. serializationObject.bias = this.bias;
  64723. serializationObject.power = this.power;
  64724. return serializationObject;
  64725. };
  64726. FresnelParameters.Parse = function (parsedFresnelParameters) {
  64727. var fresnelParameters = new FresnelParameters();
  64728. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  64729. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  64730. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  64731. fresnelParameters.bias = parsedFresnelParameters.bias;
  64732. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  64733. return fresnelParameters;
  64734. };
  64735. return FresnelParameters;
  64736. }());
  64737. BABYLON.FresnelParameters = FresnelParameters;
  64738. })(BABYLON || (BABYLON = {}));
  64739. //# sourceMappingURL=babylon.fresnelParameters.js.map
  64740. "use strict";
  64741. var BABYLON;
  64742. (function (BABYLON) {
  64743. var MultiMaterial = /** @class */ (function (_super) {
  64744. __extends(MultiMaterial, _super);
  64745. function MultiMaterial(name, scene) {
  64746. var _this = _super.call(this, name, scene, true) || this;
  64747. scene.multiMaterials.push(_this);
  64748. _this.subMaterials = new Array();
  64749. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  64750. return _this;
  64751. }
  64752. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  64753. get: function () {
  64754. return this._subMaterials;
  64755. },
  64756. set: function (value) {
  64757. this._subMaterials = value;
  64758. this._hookArray(value);
  64759. },
  64760. enumerable: true,
  64761. configurable: true
  64762. });
  64763. MultiMaterial.prototype._hookArray = function (array) {
  64764. var _this = this;
  64765. var oldPush = array.push;
  64766. array.push = function () {
  64767. var items = [];
  64768. for (var _i = 0; _i < arguments.length; _i++) {
  64769. items[_i] = arguments[_i];
  64770. }
  64771. var result = oldPush.apply(array, items);
  64772. _this._markAllSubMeshesAsTexturesDirty();
  64773. return result;
  64774. };
  64775. var oldSplice = array.splice;
  64776. array.splice = function (index, deleteCount) {
  64777. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64778. _this._markAllSubMeshesAsTexturesDirty();
  64779. return deleted;
  64780. };
  64781. };
  64782. // Properties
  64783. MultiMaterial.prototype.getSubMaterial = function (index) {
  64784. if (index < 0 || index >= this.subMaterials.length) {
  64785. return this.getScene().defaultMaterial;
  64786. }
  64787. return this.subMaterials[index];
  64788. };
  64789. MultiMaterial.prototype.getActiveTextures = function () {
  64790. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64791. if (subMaterial) {
  64792. return subMaterial.getActiveTextures();
  64793. }
  64794. else {
  64795. return [];
  64796. }
  64797. }));
  64798. var _a;
  64799. };
  64800. // Methods
  64801. MultiMaterial.prototype.getClassName = function () {
  64802. return "MultiMaterial";
  64803. };
  64804. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64805. for (var index = 0; index < this.subMaterials.length; index++) {
  64806. var subMaterial = this.subMaterials[index];
  64807. if (subMaterial) {
  64808. if (subMaterial.storeEffectOnSubMeshes) {
  64809. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64810. return false;
  64811. }
  64812. continue;
  64813. }
  64814. if (!subMaterial.isReady(mesh)) {
  64815. return false;
  64816. }
  64817. }
  64818. }
  64819. return true;
  64820. };
  64821. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  64822. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  64823. for (var index = 0; index < this.subMaterials.length; index++) {
  64824. var subMaterial = null;
  64825. var current = this.subMaterials[index];
  64826. if (cloneChildren && current) {
  64827. subMaterial = current.clone(name + "-" + current.name);
  64828. }
  64829. else {
  64830. subMaterial = this.subMaterials[index];
  64831. }
  64832. newMultiMaterial.subMaterials.push(subMaterial);
  64833. }
  64834. return newMultiMaterial;
  64835. };
  64836. MultiMaterial.prototype.serialize = function () {
  64837. var serializationObject = {};
  64838. serializationObject.name = this.name;
  64839. serializationObject.id = this.id;
  64840. if (BABYLON.Tags) {
  64841. serializationObject.tags = BABYLON.Tags.GetTags(this);
  64842. }
  64843. serializationObject.materials = [];
  64844. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  64845. var subMat = this.subMaterials[matIndex];
  64846. if (subMat) {
  64847. serializationObject.materials.push(subMat.id);
  64848. }
  64849. else {
  64850. serializationObject.materials.push(null);
  64851. }
  64852. }
  64853. return serializationObject;
  64854. };
  64855. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64856. var scene = this.getScene();
  64857. if (!scene) {
  64858. return;
  64859. }
  64860. var index = scene.multiMaterials.indexOf(this);
  64861. if (index >= 0) {
  64862. scene.multiMaterials.splice(index, 1);
  64863. }
  64864. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64865. };
  64866. return MultiMaterial;
  64867. }(BABYLON.Material));
  64868. BABYLON.MultiMaterial = MultiMaterial;
  64869. })(BABYLON || (BABYLON = {}));
  64870. //# sourceMappingURL=babylon.multiMaterial.js.map
  64871. "use strict";
  64872. var BABYLON;
  64873. (function (BABYLON) {
  64874. var FreeCameraTouchInput = /** @class */ (function () {
  64875. function FreeCameraTouchInput() {
  64876. this._offsetX = null;
  64877. this._offsetY = null;
  64878. this._pointerPressed = new Array();
  64879. this.touchAngularSensibility = 200000.0;
  64880. this.touchMoveSensibility = 250.0;
  64881. }
  64882. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64883. var _this = this;
  64884. var previousPosition = null;
  64885. if (this._pointerInput === undefined) {
  64886. this._onLostFocus = function (evt) {
  64887. _this._offsetX = null;
  64888. _this._offsetY = null;
  64889. };
  64890. this._pointerInput = function (p, s) {
  64891. var evt = p.event;
  64892. if (evt.pointerType === "mouse") {
  64893. return;
  64894. }
  64895. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64896. if (!noPreventDefault) {
  64897. evt.preventDefault();
  64898. }
  64899. _this._pointerPressed.push(evt.pointerId);
  64900. if (_this._pointerPressed.length !== 1) {
  64901. return;
  64902. }
  64903. previousPosition = {
  64904. x: evt.clientX,
  64905. y: evt.clientY
  64906. };
  64907. }
  64908. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64909. if (!noPreventDefault) {
  64910. evt.preventDefault();
  64911. }
  64912. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64913. if (index === -1) {
  64914. return;
  64915. }
  64916. _this._pointerPressed.splice(index, 1);
  64917. if (index != 0) {
  64918. return;
  64919. }
  64920. previousPosition = null;
  64921. _this._offsetX = null;
  64922. _this._offsetY = null;
  64923. }
  64924. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64925. if (!noPreventDefault) {
  64926. evt.preventDefault();
  64927. }
  64928. if (!previousPosition) {
  64929. return;
  64930. }
  64931. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64932. if (index != 0) {
  64933. return;
  64934. }
  64935. _this._offsetX = evt.clientX - previousPosition.x;
  64936. _this._offsetY = -(evt.clientY - previousPosition.y);
  64937. }
  64938. };
  64939. }
  64940. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64941. if (this._onLostFocus) {
  64942. element.addEventListener("blur", this._onLostFocus);
  64943. }
  64944. };
  64945. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64946. if (this._pointerInput && element) {
  64947. if (this._observer) {
  64948. this.camera.getScene().onPointerObservable.remove(this._observer);
  64949. this._observer = null;
  64950. }
  64951. if (this._onLostFocus) {
  64952. element.removeEventListener("blur", this._onLostFocus);
  64953. this._onLostFocus = null;
  64954. }
  64955. this._pointerPressed = [];
  64956. this._offsetX = null;
  64957. this._offsetY = null;
  64958. }
  64959. };
  64960. FreeCameraTouchInput.prototype.checkInputs = function () {
  64961. if (this._offsetX && this._offsetY) {
  64962. var camera = this.camera;
  64963. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64964. if (this._pointerPressed.length > 1) {
  64965. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64966. }
  64967. else {
  64968. var speed = camera._computeLocalCameraSpeed();
  64969. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64970. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64971. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64972. }
  64973. }
  64974. };
  64975. FreeCameraTouchInput.prototype.getClassName = function () {
  64976. return "FreeCameraTouchInput";
  64977. };
  64978. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64979. return "touch";
  64980. };
  64981. __decorate([
  64982. BABYLON.serialize()
  64983. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64984. __decorate([
  64985. BABYLON.serialize()
  64986. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64987. return FreeCameraTouchInput;
  64988. }());
  64989. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64990. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64991. })(BABYLON || (BABYLON = {}));
  64992. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64993. "use strict";
  64994. var BABYLON;
  64995. (function (BABYLON) {
  64996. // We're mainly based on the logic defined into the FreeCamera code
  64997. var TouchCamera = /** @class */ (function (_super) {
  64998. __extends(TouchCamera, _super);
  64999. //-- end properties for backward compatibility for inputs
  65000. function TouchCamera(name, position, scene) {
  65001. var _this = _super.call(this, name, position, scene) || this;
  65002. _this.inputs.addTouch();
  65003. _this._setupInputs();
  65004. return _this;
  65005. }
  65006. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  65007. //-- Begin properties for backward compatibility for inputs
  65008. get: function () {
  65009. var touch = this.inputs.attached["touch"];
  65010. if (touch)
  65011. return touch.touchAngularSensibility;
  65012. return 0;
  65013. },
  65014. set: function (value) {
  65015. var touch = this.inputs.attached["touch"];
  65016. if (touch)
  65017. touch.touchAngularSensibility = value;
  65018. },
  65019. enumerable: true,
  65020. configurable: true
  65021. });
  65022. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  65023. get: function () {
  65024. var touch = this.inputs.attached["touch"];
  65025. if (touch)
  65026. return touch.touchMoveSensibility;
  65027. return 0;
  65028. },
  65029. set: function (value) {
  65030. var touch = this.inputs.attached["touch"];
  65031. if (touch)
  65032. touch.touchMoveSensibility = value;
  65033. },
  65034. enumerable: true,
  65035. configurable: true
  65036. });
  65037. TouchCamera.prototype.getClassName = function () {
  65038. return "TouchCamera";
  65039. };
  65040. TouchCamera.prototype._setupInputs = function () {
  65041. var mouse = this.inputs.attached["mouse"];
  65042. if (mouse) {
  65043. mouse.touchEnabled = false;
  65044. }
  65045. };
  65046. return TouchCamera;
  65047. }(BABYLON.FreeCamera));
  65048. BABYLON.TouchCamera = TouchCamera;
  65049. })(BABYLON || (BABYLON = {}));
  65050. //# sourceMappingURL=babylon.touchCamera.js.map
  65051. "use strict";
  65052. var BABYLON;
  65053. (function (BABYLON) {
  65054. var ProceduralTexture = /** @class */ (function (_super) {
  65055. __extends(ProceduralTexture, _super);
  65056. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65057. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65058. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65059. if (isCube === void 0) { isCube = false; }
  65060. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65061. _this.isCube = isCube;
  65062. _this.isEnabled = true;
  65063. _this._currentRefreshId = -1;
  65064. _this._refreshRate = 1;
  65065. _this._vertexBuffers = {};
  65066. _this._uniforms = new Array();
  65067. _this._samplers = new Array();
  65068. _this._textures = {};
  65069. _this._floats = {};
  65070. _this._floatsArrays = {};
  65071. _this._colors3 = {};
  65072. _this._colors4 = {};
  65073. _this._vectors2 = {};
  65074. _this._vectors3 = {};
  65075. _this._matrices = {};
  65076. _this._fallbackTextureUsed = false;
  65077. scene._proceduralTextures.push(_this);
  65078. _this._engine = scene.getEngine();
  65079. _this.name = name;
  65080. _this.isRenderTarget = true;
  65081. _this._size = size;
  65082. _this._generateMipMaps = generateMipMaps;
  65083. _this.setFragment(fragment);
  65084. _this._fallbackTexture = fallbackTexture;
  65085. if (isCube) {
  65086. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65087. _this.setFloat("face", 0);
  65088. }
  65089. else {
  65090. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65091. }
  65092. // VBO
  65093. var vertices = [];
  65094. vertices.push(1, 1);
  65095. vertices.push(-1, 1);
  65096. vertices.push(-1, -1);
  65097. vertices.push(1, -1);
  65098. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65099. _this._createIndexBuffer();
  65100. return _this;
  65101. }
  65102. ProceduralTexture.prototype._createIndexBuffer = function () {
  65103. var engine = this._engine;
  65104. // Indices
  65105. var indices = [];
  65106. indices.push(0);
  65107. indices.push(1);
  65108. indices.push(2);
  65109. indices.push(0);
  65110. indices.push(2);
  65111. indices.push(3);
  65112. this._indexBuffer = engine.createIndexBuffer(indices);
  65113. };
  65114. ProceduralTexture.prototype._rebuild = function () {
  65115. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65116. if (vb) {
  65117. vb._rebuild();
  65118. }
  65119. this._createIndexBuffer();
  65120. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65121. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65122. }
  65123. };
  65124. ProceduralTexture.prototype.reset = function () {
  65125. if (this._effect === undefined) {
  65126. return;
  65127. }
  65128. var engine = this._engine;
  65129. engine._releaseEffect(this._effect);
  65130. };
  65131. ProceduralTexture.prototype.isReady = function () {
  65132. var _this = this;
  65133. var engine = this._engine;
  65134. var shaders;
  65135. if (!this._fragment) {
  65136. return false;
  65137. }
  65138. if (this._fallbackTextureUsed) {
  65139. return true;
  65140. }
  65141. if (this._fragment.fragmentElement !== undefined) {
  65142. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65143. }
  65144. else {
  65145. shaders = { vertex: "procedural", fragment: this._fragment };
  65146. }
  65147. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65148. _this.releaseInternalTexture();
  65149. if (_this._fallbackTexture) {
  65150. _this._texture = _this._fallbackTexture._texture;
  65151. if (_this._texture) {
  65152. _this._texture.incrementReferences();
  65153. }
  65154. }
  65155. _this._fallbackTextureUsed = true;
  65156. });
  65157. return this._effect.isReady();
  65158. };
  65159. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65160. this._currentRefreshId = -1;
  65161. };
  65162. ProceduralTexture.prototype.setFragment = function (fragment) {
  65163. this._fragment = fragment;
  65164. };
  65165. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65166. get: function () {
  65167. return this._refreshRate;
  65168. },
  65169. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65170. set: function (value) {
  65171. this._refreshRate = value;
  65172. this.resetRefreshCounter();
  65173. },
  65174. enumerable: true,
  65175. configurable: true
  65176. });
  65177. ProceduralTexture.prototype._shouldRender = function () {
  65178. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65179. return false;
  65180. }
  65181. if (this._fallbackTextureUsed) {
  65182. return false;
  65183. }
  65184. if (this._currentRefreshId === -1) {
  65185. this._currentRefreshId = 1;
  65186. return true;
  65187. }
  65188. if (this.refreshRate === this._currentRefreshId) {
  65189. this._currentRefreshId = 1;
  65190. return true;
  65191. }
  65192. this._currentRefreshId++;
  65193. return false;
  65194. };
  65195. ProceduralTexture.prototype.getRenderSize = function () {
  65196. return this._size;
  65197. };
  65198. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65199. if (this._fallbackTextureUsed) {
  65200. return;
  65201. }
  65202. this.releaseInternalTexture();
  65203. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65204. };
  65205. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65206. if (this._uniforms.indexOf(uniformName) === -1) {
  65207. this._uniforms.push(uniformName);
  65208. }
  65209. };
  65210. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65211. if (this._samplers.indexOf(name) === -1) {
  65212. this._samplers.push(name);
  65213. }
  65214. this._textures[name] = texture;
  65215. return this;
  65216. };
  65217. ProceduralTexture.prototype.setFloat = function (name, value) {
  65218. this._checkUniform(name);
  65219. this._floats[name] = value;
  65220. return this;
  65221. };
  65222. ProceduralTexture.prototype.setFloats = function (name, value) {
  65223. this._checkUniform(name);
  65224. this._floatsArrays[name] = value;
  65225. return this;
  65226. };
  65227. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65228. this._checkUniform(name);
  65229. this._colors3[name] = value;
  65230. return this;
  65231. };
  65232. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65233. this._checkUniform(name);
  65234. this._colors4[name] = value;
  65235. return this;
  65236. };
  65237. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65238. this._checkUniform(name);
  65239. this._vectors2[name] = value;
  65240. return this;
  65241. };
  65242. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65243. this._checkUniform(name);
  65244. this._vectors3[name] = value;
  65245. return this;
  65246. };
  65247. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65248. this._checkUniform(name);
  65249. this._matrices[name] = value;
  65250. return this;
  65251. };
  65252. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65253. var scene = this.getScene();
  65254. if (!scene) {
  65255. return;
  65256. }
  65257. var engine = this._engine;
  65258. // Render
  65259. engine.enableEffect(this._effect);
  65260. engine.setState(false);
  65261. // Texture
  65262. for (var name in this._textures) {
  65263. this._effect.setTexture(name, this._textures[name]);
  65264. }
  65265. // Float
  65266. for (name in this._floats) {
  65267. this._effect.setFloat(name, this._floats[name]);
  65268. }
  65269. // Floats
  65270. for (name in this._floatsArrays) {
  65271. this._effect.setArray(name, this._floatsArrays[name]);
  65272. }
  65273. // Color3
  65274. for (name in this._colors3) {
  65275. this._effect.setColor3(name, this._colors3[name]);
  65276. }
  65277. // Color4
  65278. for (name in this._colors4) {
  65279. var color = this._colors4[name];
  65280. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65281. }
  65282. // Vector2
  65283. for (name in this._vectors2) {
  65284. this._effect.setVector2(name, this._vectors2[name]);
  65285. }
  65286. // Vector3
  65287. for (name in this._vectors3) {
  65288. this._effect.setVector3(name, this._vectors3[name]);
  65289. }
  65290. // Matrix
  65291. for (name in this._matrices) {
  65292. this._effect.setMatrix(name, this._matrices[name]);
  65293. }
  65294. if (!this._texture) {
  65295. return;
  65296. }
  65297. if (this.isCube) {
  65298. for (var face = 0; face < 6; face++) {
  65299. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65300. // VBOs
  65301. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65302. this._effect.setFloat("face", face);
  65303. // Clear
  65304. engine.clear(scene.clearColor, true, true, true);
  65305. // Draw order
  65306. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65307. // Mipmaps
  65308. if (face === 5) {
  65309. engine.generateMipMapsForCubemap(this._texture);
  65310. }
  65311. }
  65312. }
  65313. else {
  65314. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65315. // VBOs
  65316. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65317. // Clear
  65318. engine.clear(scene.clearColor, true, true, true);
  65319. // Draw order
  65320. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65321. }
  65322. // Unbind
  65323. engine.unBindFramebuffer(this._texture, this.isCube);
  65324. if (this.onGenerated) {
  65325. this.onGenerated();
  65326. }
  65327. };
  65328. ProceduralTexture.prototype.clone = function () {
  65329. var textureSize = this.getSize();
  65330. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65331. // Base texture
  65332. newTexture.hasAlpha = this.hasAlpha;
  65333. newTexture.level = this.level;
  65334. // RenderTarget Texture
  65335. newTexture.coordinatesMode = this.coordinatesMode;
  65336. return newTexture;
  65337. };
  65338. ProceduralTexture.prototype.dispose = function () {
  65339. var scene = this.getScene();
  65340. if (!scene) {
  65341. return;
  65342. }
  65343. var index = scene._proceduralTextures.indexOf(this);
  65344. if (index >= 0) {
  65345. scene._proceduralTextures.splice(index, 1);
  65346. }
  65347. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65348. if (vertexBuffer) {
  65349. vertexBuffer.dispose();
  65350. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65351. }
  65352. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65353. this._indexBuffer = null;
  65354. }
  65355. _super.prototype.dispose.call(this);
  65356. };
  65357. return ProceduralTexture;
  65358. }(BABYLON.Texture));
  65359. BABYLON.ProceduralTexture = ProceduralTexture;
  65360. })(BABYLON || (BABYLON = {}));
  65361. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65362. "use strict";
  65363. var BABYLON;
  65364. (function (BABYLON) {
  65365. var CustomProceduralTexture = /** @class */ (function (_super) {
  65366. __extends(CustomProceduralTexture, _super);
  65367. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65368. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65369. _this._animate = true;
  65370. _this._time = 0;
  65371. _this._texturePath = texturePath;
  65372. //Try to load json
  65373. _this.loadJson(texturePath);
  65374. _this.refreshRate = 1;
  65375. return _this;
  65376. }
  65377. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65378. var _this = this;
  65379. var noConfigFile = function () {
  65380. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65381. try {
  65382. _this.setFragment(_this._texturePath);
  65383. }
  65384. catch (ex) {
  65385. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65386. }
  65387. };
  65388. var configFileUrl = jsonUrl + "/config.json";
  65389. var xhr = new XMLHttpRequest();
  65390. xhr.open("GET", configFileUrl, true);
  65391. xhr.addEventListener("load", function () {
  65392. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65393. try {
  65394. _this._config = JSON.parse(xhr.response);
  65395. _this.updateShaderUniforms();
  65396. _this.updateTextures();
  65397. _this.setFragment(_this._texturePath + "/custom");
  65398. _this._animate = _this._config.animate;
  65399. _this.refreshRate = _this._config.refreshrate;
  65400. }
  65401. catch (ex) {
  65402. noConfigFile();
  65403. }
  65404. }
  65405. else {
  65406. noConfigFile();
  65407. }
  65408. }, false);
  65409. xhr.addEventListener("error", function () {
  65410. noConfigFile();
  65411. }, false);
  65412. try {
  65413. xhr.send();
  65414. }
  65415. catch (ex) {
  65416. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65417. }
  65418. };
  65419. CustomProceduralTexture.prototype.isReady = function () {
  65420. if (!_super.prototype.isReady.call(this)) {
  65421. return false;
  65422. }
  65423. for (var name in this._textures) {
  65424. var texture = this._textures[name];
  65425. if (!texture.isReady()) {
  65426. return false;
  65427. }
  65428. }
  65429. return true;
  65430. };
  65431. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65432. var scene = this.getScene();
  65433. if (this._animate && scene) {
  65434. this._time += scene.getAnimationRatio() * 0.03;
  65435. this.updateShaderUniforms();
  65436. }
  65437. _super.prototype.render.call(this, useCameraPostProcess);
  65438. };
  65439. CustomProceduralTexture.prototype.updateTextures = function () {
  65440. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65441. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65442. }
  65443. };
  65444. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65445. if (this._config) {
  65446. for (var j = 0; j < this._config.uniforms.length; j++) {
  65447. var uniform = this._config.uniforms[j];
  65448. switch (uniform.type) {
  65449. case "float":
  65450. this.setFloat(uniform.name, uniform.value);
  65451. break;
  65452. case "color3":
  65453. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65454. break;
  65455. case "color4":
  65456. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65457. break;
  65458. case "vector2":
  65459. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65460. break;
  65461. case "vector3":
  65462. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65463. break;
  65464. }
  65465. }
  65466. }
  65467. this.setFloat("time", this._time);
  65468. };
  65469. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65470. get: function () {
  65471. return this._animate;
  65472. },
  65473. set: function (value) {
  65474. this._animate = value;
  65475. },
  65476. enumerable: true,
  65477. configurable: true
  65478. });
  65479. return CustomProceduralTexture;
  65480. }(BABYLON.ProceduralTexture));
  65481. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65482. })(BABYLON || (BABYLON = {}));
  65483. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65484. "use strict";
  65485. var BABYLON;
  65486. (function (BABYLON) {
  65487. var FreeCameraGamepadInput = /** @class */ (function () {
  65488. function FreeCameraGamepadInput() {
  65489. this.gamepadAngularSensibility = 200;
  65490. this.gamepadMoveSensibility = 40;
  65491. // private members
  65492. this._cameraTransform = BABYLON.Matrix.Identity();
  65493. this._deltaTransform = BABYLON.Vector3.Zero();
  65494. this._vector3 = BABYLON.Vector3.Zero();
  65495. this._vector2 = BABYLON.Vector2.Zero();
  65496. }
  65497. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65498. var _this = this;
  65499. var manager = this.camera.getScene().gamepadManager;
  65500. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65501. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65502. // prioritize XBOX gamepads.
  65503. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65504. _this.gamepad = gamepad;
  65505. }
  65506. }
  65507. });
  65508. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65509. if (_this.gamepad === gamepad) {
  65510. _this.gamepad = null;
  65511. }
  65512. });
  65513. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65514. };
  65515. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65516. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65517. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65518. this.gamepad = null;
  65519. };
  65520. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65521. if (this.gamepad && this.gamepad.leftStick) {
  65522. var camera = this.camera;
  65523. var LSValues = this.gamepad.leftStick;
  65524. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65525. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65526. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65527. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65528. var RSValues = this.gamepad.rightStick;
  65529. if (RSValues) {
  65530. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65531. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65532. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65533. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65534. }
  65535. else {
  65536. RSValues = { x: 0, y: 0 };
  65537. }
  65538. if (!camera.rotationQuaternion) {
  65539. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65540. }
  65541. else {
  65542. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65543. }
  65544. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65545. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65546. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65547. camera.cameraDirection.addInPlace(this._deltaTransform);
  65548. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65549. camera.cameraRotation.addInPlace(this._vector2);
  65550. }
  65551. };
  65552. FreeCameraGamepadInput.prototype.getClassName = function () {
  65553. return "FreeCameraGamepadInput";
  65554. };
  65555. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65556. return "gamepad";
  65557. };
  65558. __decorate([
  65559. BABYLON.serialize()
  65560. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65561. __decorate([
  65562. BABYLON.serialize()
  65563. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65564. return FreeCameraGamepadInput;
  65565. }());
  65566. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65567. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65568. })(BABYLON || (BABYLON = {}));
  65569. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65570. "use strict";
  65571. var BABYLON;
  65572. (function (BABYLON) {
  65573. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65574. function ArcRotateCameraGamepadInput() {
  65575. this.gamepadRotationSensibility = 80;
  65576. this.gamepadMoveSensibility = 40;
  65577. }
  65578. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65579. var _this = this;
  65580. var manager = this.camera.getScene().gamepadManager;
  65581. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65582. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65583. // prioritize XBOX gamepads.
  65584. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65585. _this.gamepad = gamepad;
  65586. }
  65587. }
  65588. });
  65589. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65590. if (_this.gamepad === gamepad) {
  65591. _this.gamepad = null;
  65592. }
  65593. });
  65594. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65595. };
  65596. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65597. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65598. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65599. this.gamepad = null;
  65600. };
  65601. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65602. if (this.gamepad) {
  65603. var camera = this.camera;
  65604. var RSValues = this.gamepad.rightStick;
  65605. if (RSValues) {
  65606. if (RSValues.x != 0) {
  65607. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65608. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65609. camera.inertialAlphaOffset += normalizedRX;
  65610. }
  65611. }
  65612. if (RSValues.y != 0) {
  65613. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65614. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65615. camera.inertialBetaOffset += normalizedRY;
  65616. }
  65617. }
  65618. }
  65619. var LSValues = this.gamepad.leftStick;
  65620. if (LSValues && LSValues.y != 0) {
  65621. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65622. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65623. this.camera.inertialRadiusOffset -= normalizedLY;
  65624. }
  65625. }
  65626. }
  65627. };
  65628. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65629. return "ArcRotateCameraGamepadInput";
  65630. };
  65631. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65632. return "gamepad";
  65633. };
  65634. __decorate([
  65635. BABYLON.serialize()
  65636. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65637. __decorate([
  65638. BABYLON.serialize()
  65639. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65640. return ArcRotateCameraGamepadInput;
  65641. }());
  65642. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65643. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65644. })(BABYLON || (BABYLON = {}));
  65645. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65646. "use strict";
  65647. var BABYLON;
  65648. (function (BABYLON) {
  65649. var GamepadManager = /** @class */ (function () {
  65650. function GamepadManager(_scene) {
  65651. var _this = this;
  65652. this._scene = _scene;
  65653. this._babylonGamepads = [];
  65654. this._oneGamepadConnected = false;
  65655. this._isMonitoring = false;
  65656. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65657. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65658. this._gamepadEventSupported = false;
  65659. }
  65660. else {
  65661. this._gamepadEventSupported = 'GamepadEvent' in window;
  65662. this._gamepadSupport = (navigator.getGamepads ||
  65663. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65664. }
  65665. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65666. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65667. for (var i in _this._babylonGamepads) {
  65668. var gamepad = _this._babylonGamepads[i];
  65669. if (gamepad && gamepad._isConnected) {
  65670. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65671. }
  65672. }
  65673. });
  65674. this._onGamepadConnectedEvent = function (evt) {
  65675. var gamepad = evt.gamepad;
  65676. if (gamepad.index in _this._babylonGamepads) {
  65677. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65678. return;
  65679. }
  65680. }
  65681. var newGamepad;
  65682. if (_this._babylonGamepads[gamepad.index]) {
  65683. newGamepad = _this._babylonGamepads[gamepad.index];
  65684. newGamepad.browserGamepad = gamepad;
  65685. newGamepad._isConnected = true;
  65686. }
  65687. else {
  65688. newGamepad = _this._addNewGamepad(gamepad);
  65689. }
  65690. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65691. _this._startMonitoringGamepads();
  65692. };
  65693. this._onGamepadDisconnectedEvent = function (evt) {
  65694. var gamepad = evt.gamepad;
  65695. // Remove the gamepad from the list of gamepads to monitor.
  65696. for (var i in _this._babylonGamepads) {
  65697. if (_this._babylonGamepads[i].index === gamepad.index) {
  65698. var disconnectedGamepad = _this._babylonGamepads[i];
  65699. disconnectedGamepad._isConnected = false;
  65700. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65701. break;
  65702. }
  65703. }
  65704. };
  65705. if (this._gamepadSupport) {
  65706. //first add already-connected gamepads
  65707. this._updateGamepadObjects();
  65708. if (this._babylonGamepads.length) {
  65709. this._startMonitoringGamepads();
  65710. }
  65711. // Checking if the gamepad connected event is supported (like in Firefox)
  65712. if (this._gamepadEventSupported) {
  65713. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  65714. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  65715. }
  65716. else {
  65717. this._startMonitoringGamepads();
  65718. }
  65719. }
  65720. }
  65721. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  65722. get: function () {
  65723. return this._babylonGamepads;
  65724. },
  65725. enumerable: true,
  65726. configurable: true
  65727. });
  65728. GamepadManager.prototype.getGamepadByType = function (type) {
  65729. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  65730. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  65731. var gamepad = _a[_i];
  65732. if (gamepad && gamepad.type === type) {
  65733. return gamepad;
  65734. }
  65735. }
  65736. return null;
  65737. };
  65738. GamepadManager.prototype.dispose = function () {
  65739. if (this._gamepadEventSupported) {
  65740. if (this._onGamepadConnectedEvent) {
  65741. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  65742. }
  65743. if (this._onGamepadDisconnectedEvent) {
  65744. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  65745. }
  65746. this._onGamepadConnectedEvent = null;
  65747. this._onGamepadDisconnectedEvent = null;
  65748. }
  65749. this._babylonGamepads.forEach(function (gamepad) {
  65750. gamepad.dispose();
  65751. });
  65752. this.onGamepadConnectedObservable.clear();
  65753. this.onGamepadDisconnectedObservable.clear();
  65754. this._oneGamepadConnected = false;
  65755. this._stopMonitoringGamepads();
  65756. this._babylonGamepads = [];
  65757. };
  65758. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  65759. if (!this._oneGamepadConnected) {
  65760. this._oneGamepadConnected = true;
  65761. }
  65762. var newGamepad;
  65763. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  65764. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  65765. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  65766. }
  65767. else if (gamepad.pose) {
  65768. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65769. }
  65770. else {
  65771. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65772. }
  65773. this._babylonGamepads[newGamepad.index] = newGamepad;
  65774. return newGamepad;
  65775. };
  65776. GamepadManager.prototype._startMonitoringGamepads = function () {
  65777. if (!this._isMonitoring) {
  65778. this._isMonitoring = true;
  65779. //back-comp
  65780. if (!this._scene) {
  65781. this._checkGamepadsStatus();
  65782. }
  65783. }
  65784. };
  65785. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65786. this._isMonitoring = false;
  65787. };
  65788. GamepadManager.prototype._checkGamepadsStatus = function () {
  65789. var _this = this;
  65790. // Hack to be compatible Chrome
  65791. this._updateGamepadObjects();
  65792. for (var i in this._babylonGamepads) {
  65793. var gamepad = this._babylonGamepads[i];
  65794. if (!gamepad || !gamepad.isConnected) {
  65795. continue;
  65796. }
  65797. gamepad.update();
  65798. }
  65799. if (this._isMonitoring && !this._scene) {
  65800. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65801. }
  65802. };
  65803. // This function is called only on Chrome, which does not properly support
  65804. // connection/disconnection events and forces you to recopy again the gamepad object
  65805. GamepadManager.prototype._updateGamepadObjects = function () {
  65806. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65807. for (var i = 0; i < gamepads.length; i++) {
  65808. if (gamepads[i]) {
  65809. if (!this._babylonGamepads[gamepads[i].index]) {
  65810. var newGamepad = this._addNewGamepad(gamepads[i]);
  65811. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65812. }
  65813. else {
  65814. // Forced to copy again this object for Chrome for unknown reason
  65815. this._babylonGamepads[i].browserGamepad = gamepads[i];
  65816. if (!this._babylonGamepads[i].isConnected) {
  65817. this._babylonGamepads[i]._isConnected = true;
  65818. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  65819. }
  65820. }
  65821. }
  65822. }
  65823. };
  65824. return GamepadManager;
  65825. }());
  65826. BABYLON.GamepadManager = GamepadManager;
  65827. })(BABYLON || (BABYLON = {}));
  65828. //# sourceMappingURL=babylon.gamepadManager.js.map
  65829. "use strict";
  65830. var BABYLON;
  65831. (function (BABYLON) {
  65832. var StickValues = /** @class */ (function () {
  65833. function StickValues(x, y) {
  65834. this.x = x;
  65835. this.y = y;
  65836. }
  65837. return StickValues;
  65838. }());
  65839. BABYLON.StickValues = StickValues;
  65840. var Gamepad = /** @class */ (function () {
  65841. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  65842. if (leftStickX === void 0) { leftStickX = 0; }
  65843. if (leftStickY === void 0) { leftStickY = 1; }
  65844. if (rightStickX === void 0) { rightStickX = 2; }
  65845. if (rightStickY === void 0) { rightStickY = 3; }
  65846. this.id = id;
  65847. this.index = index;
  65848. this.browserGamepad = browserGamepad;
  65849. this._isConnected = true;
  65850. this._invertLeftStickY = false;
  65851. this.type = Gamepad.GAMEPAD;
  65852. this._leftStickAxisX = leftStickX;
  65853. this._leftStickAxisY = leftStickY;
  65854. this._rightStickAxisX = rightStickX;
  65855. this._rightStickAxisY = rightStickY;
  65856. if (this.browserGamepad.axes.length >= 2) {
  65857. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65858. }
  65859. if (this.browserGamepad.axes.length >= 4) {
  65860. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65861. }
  65862. }
  65863. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65864. get: function () {
  65865. return this._isConnected;
  65866. },
  65867. enumerable: true,
  65868. configurable: true
  65869. });
  65870. Gamepad.prototype.onleftstickchanged = function (callback) {
  65871. this._onleftstickchanged = callback;
  65872. };
  65873. Gamepad.prototype.onrightstickchanged = function (callback) {
  65874. this._onrightstickchanged = callback;
  65875. };
  65876. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65877. get: function () {
  65878. return this._leftStick;
  65879. },
  65880. set: function (newValues) {
  65881. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65882. this._onleftstickchanged(newValues);
  65883. }
  65884. this._leftStick = newValues;
  65885. },
  65886. enumerable: true,
  65887. configurable: true
  65888. });
  65889. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65890. get: function () {
  65891. return this._rightStick;
  65892. },
  65893. set: function (newValues) {
  65894. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65895. this._onrightstickchanged(newValues);
  65896. }
  65897. this._rightStick = newValues;
  65898. },
  65899. enumerable: true,
  65900. configurable: true
  65901. });
  65902. Gamepad.prototype.update = function () {
  65903. if (this._leftStick) {
  65904. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65905. if (this._invertLeftStickY) {
  65906. this.leftStick.y *= -1;
  65907. }
  65908. }
  65909. if (this._rightStick) {
  65910. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65911. }
  65912. };
  65913. Gamepad.prototype.dispose = function () {
  65914. };
  65915. Gamepad.GAMEPAD = 0;
  65916. Gamepad.GENERIC = 1;
  65917. Gamepad.XBOX = 2;
  65918. Gamepad.POSE_ENABLED = 3;
  65919. return Gamepad;
  65920. }());
  65921. BABYLON.Gamepad = Gamepad;
  65922. var GenericPad = /** @class */ (function (_super) {
  65923. __extends(GenericPad, _super);
  65924. function GenericPad(id, index, browserGamepad) {
  65925. var _this = _super.call(this, id, index, browserGamepad) || this;
  65926. _this.onButtonDownObservable = new BABYLON.Observable();
  65927. _this.onButtonUpObservable = new BABYLON.Observable();
  65928. _this.type = Gamepad.GENERIC;
  65929. _this._buttons = new Array(browserGamepad.buttons.length);
  65930. return _this;
  65931. }
  65932. GenericPad.prototype.onbuttondown = function (callback) {
  65933. this._onbuttondown = callback;
  65934. };
  65935. GenericPad.prototype.onbuttonup = function (callback) {
  65936. this._onbuttonup = callback;
  65937. };
  65938. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65939. if (newValue !== currentValue) {
  65940. if (newValue === 1) {
  65941. if (this._onbuttondown) {
  65942. this._onbuttondown(buttonIndex);
  65943. }
  65944. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65945. }
  65946. if (newValue === 0) {
  65947. if (this._onbuttonup) {
  65948. this._onbuttonup(buttonIndex);
  65949. }
  65950. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65951. }
  65952. }
  65953. return newValue;
  65954. };
  65955. GenericPad.prototype.update = function () {
  65956. _super.prototype.update.call(this);
  65957. for (var index = 0; index < this._buttons.length; index++) {
  65958. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65959. }
  65960. };
  65961. GenericPad.prototype.dispose = function () {
  65962. _super.prototype.dispose.call(this);
  65963. this.onButtonDownObservable.clear();
  65964. this.onButtonUpObservable.clear();
  65965. };
  65966. return GenericPad;
  65967. }(Gamepad));
  65968. BABYLON.GenericPad = GenericPad;
  65969. })(BABYLON || (BABYLON = {}));
  65970. //# sourceMappingURL=babylon.gamepad.js.map
  65971. "use strict";
  65972. var BABYLON;
  65973. (function (BABYLON) {
  65974. var Xbox360Button;
  65975. (function (Xbox360Button) {
  65976. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65977. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65978. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65979. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65980. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65981. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65982. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65983. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65984. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65985. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65986. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65987. var Xbox360Dpad;
  65988. (function (Xbox360Dpad) {
  65989. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65990. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65991. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65992. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65993. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65994. var Xbox360Pad = /** @class */ (function (_super) {
  65995. __extends(Xbox360Pad, _super);
  65996. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65997. if (xboxOne === void 0) { xboxOne = false; }
  65998. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65999. _this._leftTrigger = 0;
  66000. _this._rightTrigger = 0;
  66001. _this.onButtonDownObservable = new BABYLON.Observable();
  66002. _this.onButtonUpObservable = new BABYLON.Observable();
  66003. _this.onPadDownObservable = new BABYLON.Observable();
  66004. _this.onPadUpObservable = new BABYLON.Observable();
  66005. _this._buttonA = 0;
  66006. _this._buttonB = 0;
  66007. _this._buttonX = 0;
  66008. _this._buttonY = 0;
  66009. _this._buttonBack = 0;
  66010. _this._buttonStart = 0;
  66011. _this._buttonLB = 0;
  66012. _this._buttonRB = 0;
  66013. _this._buttonLeftStick = 0;
  66014. _this._buttonRightStick = 0;
  66015. _this._dPadUp = 0;
  66016. _this._dPadDown = 0;
  66017. _this._dPadLeft = 0;
  66018. _this._dPadRight = 0;
  66019. _this._isXboxOnePad = false;
  66020. _this.type = BABYLON.Gamepad.XBOX;
  66021. _this._isXboxOnePad = xboxOne;
  66022. return _this;
  66023. }
  66024. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  66025. this._onlefttriggerchanged = callback;
  66026. };
  66027. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  66028. this._onrighttriggerchanged = callback;
  66029. };
  66030. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  66031. get: function () {
  66032. return this._leftTrigger;
  66033. },
  66034. set: function (newValue) {
  66035. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66036. this._onlefttriggerchanged(newValue);
  66037. }
  66038. this._leftTrigger = newValue;
  66039. },
  66040. enumerable: true,
  66041. configurable: true
  66042. });
  66043. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66044. get: function () {
  66045. return this._rightTrigger;
  66046. },
  66047. set: function (newValue) {
  66048. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66049. this._onrighttriggerchanged(newValue);
  66050. }
  66051. this._rightTrigger = newValue;
  66052. },
  66053. enumerable: true,
  66054. configurable: true
  66055. });
  66056. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66057. this._onbuttondown = callback;
  66058. };
  66059. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66060. this._onbuttonup = callback;
  66061. };
  66062. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66063. this._ondpaddown = callback;
  66064. };
  66065. Xbox360Pad.prototype.ondpadup = function (callback) {
  66066. this._ondpadup = callback;
  66067. };
  66068. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66069. if (newValue !== currentValue) {
  66070. if (newValue === 1) {
  66071. if (this._onbuttondown) {
  66072. this._onbuttondown(buttonType);
  66073. }
  66074. this.onButtonDownObservable.notifyObservers(buttonType);
  66075. }
  66076. if (newValue === 0) {
  66077. if (this._onbuttonup) {
  66078. this._onbuttonup(buttonType);
  66079. }
  66080. this.onButtonUpObservable.notifyObservers(buttonType);
  66081. }
  66082. }
  66083. return newValue;
  66084. };
  66085. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66086. if (newValue !== currentValue) {
  66087. if (newValue === 1) {
  66088. if (this._ondpaddown) {
  66089. this._ondpaddown(buttonType);
  66090. }
  66091. this.onPadDownObservable.notifyObservers(buttonType);
  66092. }
  66093. if (newValue === 0) {
  66094. if (this._ondpadup) {
  66095. this._ondpadup(buttonType);
  66096. }
  66097. this.onPadUpObservable.notifyObservers(buttonType);
  66098. }
  66099. }
  66100. return newValue;
  66101. };
  66102. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66103. get: function () {
  66104. return this._buttonA;
  66105. },
  66106. set: function (value) {
  66107. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66108. },
  66109. enumerable: true,
  66110. configurable: true
  66111. });
  66112. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66113. get: function () {
  66114. return this._buttonB;
  66115. },
  66116. set: function (value) {
  66117. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66118. },
  66119. enumerable: true,
  66120. configurable: true
  66121. });
  66122. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66123. get: function () {
  66124. return this._buttonX;
  66125. },
  66126. set: function (value) {
  66127. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66128. },
  66129. enumerable: true,
  66130. configurable: true
  66131. });
  66132. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66133. get: function () {
  66134. return this._buttonY;
  66135. },
  66136. set: function (value) {
  66137. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66138. },
  66139. enumerable: true,
  66140. configurable: true
  66141. });
  66142. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66143. get: function () {
  66144. return this._buttonStart;
  66145. },
  66146. set: function (value) {
  66147. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66148. },
  66149. enumerable: true,
  66150. configurable: true
  66151. });
  66152. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66153. get: function () {
  66154. return this._buttonBack;
  66155. },
  66156. set: function (value) {
  66157. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66158. },
  66159. enumerable: true,
  66160. configurable: true
  66161. });
  66162. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66163. get: function () {
  66164. return this._buttonLB;
  66165. },
  66166. set: function (value) {
  66167. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66168. },
  66169. enumerable: true,
  66170. configurable: true
  66171. });
  66172. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66173. get: function () {
  66174. return this._buttonRB;
  66175. },
  66176. set: function (value) {
  66177. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66178. },
  66179. enumerable: true,
  66180. configurable: true
  66181. });
  66182. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66183. get: function () {
  66184. return this._buttonLeftStick;
  66185. },
  66186. set: function (value) {
  66187. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66188. },
  66189. enumerable: true,
  66190. configurable: true
  66191. });
  66192. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66193. get: function () {
  66194. return this._buttonRightStick;
  66195. },
  66196. set: function (value) {
  66197. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66198. },
  66199. enumerable: true,
  66200. configurable: true
  66201. });
  66202. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66203. get: function () {
  66204. return this._dPadUp;
  66205. },
  66206. set: function (value) {
  66207. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66208. },
  66209. enumerable: true,
  66210. configurable: true
  66211. });
  66212. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66213. get: function () {
  66214. return this._dPadDown;
  66215. },
  66216. set: function (value) {
  66217. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66218. },
  66219. enumerable: true,
  66220. configurable: true
  66221. });
  66222. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66223. get: function () {
  66224. return this._dPadLeft;
  66225. },
  66226. set: function (value) {
  66227. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66228. },
  66229. enumerable: true,
  66230. configurable: true
  66231. });
  66232. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66233. get: function () {
  66234. return this._dPadRight;
  66235. },
  66236. set: function (value) {
  66237. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66238. },
  66239. enumerable: true,
  66240. configurable: true
  66241. });
  66242. Xbox360Pad.prototype.update = function () {
  66243. _super.prototype.update.call(this);
  66244. if (this._isXboxOnePad) {
  66245. this.buttonA = this.browserGamepad.buttons[0].value;
  66246. this.buttonB = this.browserGamepad.buttons[1].value;
  66247. this.buttonX = this.browserGamepad.buttons[2].value;
  66248. this.buttonY = this.browserGamepad.buttons[3].value;
  66249. this.buttonLB = this.browserGamepad.buttons[4].value;
  66250. this.buttonRB = this.browserGamepad.buttons[5].value;
  66251. this.leftTrigger = this.browserGamepad.axes[2];
  66252. this.rightTrigger = this.browserGamepad.axes[5];
  66253. this.buttonBack = this.browserGamepad.buttons[9].value;
  66254. this.buttonStart = this.browserGamepad.buttons[8].value;
  66255. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66256. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66257. this.dPadUp = this.browserGamepad.buttons[11].value;
  66258. this.dPadDown = this.browserGamepad.buttons[12].value;
  66259. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66260. this.dPadRight = this.browserGamepad.buttons[14].value;
  66261. }
  66262. else {
  66263. this.buttonA = this.browserGamepad.buttons[0].value;
  66264. this.buttonB = this.browserGamepad.buttons[1].value;
  66265. this.buttonX = this.browserGamepad.buttons[2].value;
  66266. this.buttonY = this.browserGamepad.buttons[3].value;
  66267. this.buttonLB = this.browserGamepad.buttons[4].value;
  66268. this.buttonRB = this.browserGamepad.buttons[5].value;
  66269. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66270. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66271. this.buttonBack = this.browserGamepad.buttons[8].value;
  66272. this.buttonStart = this.browserGamepad.buttons[9].value;
  66273. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66274. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66275. this.dPadUp = this.browserGamepad.buttons[12].value;
  66276. this.dPadDown = this.browserGamepad.buttons[13].value;
  66277. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66278. this.dPadRight = this.browserGamepad.buttons[15].value;
  66279. }
  66280. };
  66281. Xbox360Pad.prototype.dispose = function () {
  66282. _super.prototype.dispose.call(this);
  66283. this.onButtonDownObservable.clear();
  66284. this.onButtonUpObservable.clear();
  66285. this.onPadDownObservable.clear();
  66286. this.onPadUpObservable.clear();
  66287. };
  66288. return Xbox360Pad;
  66289. }(BABYLON.Gamepad));
  66290. BABYLON.Xbox360Pad = Xbox360Pad;
  66291. })(BABYLON || (BABYLON = {}));
  66292. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66293. "use strict";
  66294. var BABYLON;
  66295. (function (BABYLON) {
  66296. var PoseEnabledControllerType;
  66297. (function (PoseEnabledControllerType) {
  66298. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66299. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66300. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66301. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66302. /**
  66303. * Google Daydream
  66304. */
  66305. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66306. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66307. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66308. var PoseEnabledControllerHelper = /** @class */ (function () {
  66309. function PoseEnabledControllerHelper() {
  66310. }
  66311. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66312. // Oculus Touch
  66313. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66314. return new BABYLON.OculusTouchController(vrGamepad);
  66315. }
  66316. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66317. return new BABYLON.WindowsMotionController(vrGamepad);
  66318. }
  66319. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66320. return new BABYLON.ViveController(vrGamepad);
  66321. }
  66322. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66323. return new BABYLON.GearVRController(vrGamepad);
  66324. }
  66325. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66326. return new BABYLON.DaydreamController(vrGamepad);
  66327. }
  66328. else {
  66329. return new BABYLON.GenericController(vrGamepad);
  66330. }
  66331. };
  66332. return PoseEnabledControllerHelper;
  66333. }());
  66334. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66335. var PoseEnabledController = /** @class */ (function (_super) {
  66336. __extends(PoseEnabledController, _super);
  66337. function PoseEnabledController(browserGamepad) {
  66338. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66339. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66340. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66341. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66342. // Represents device position and rotation in babylon space
  66343. _this.devicePosition = BABYLON.Vector3.Zero();
  66344. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66345. _this.deviceScaleFactor = 1;
  66346. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66347. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66348. /**
  66349. * Node to be used when casting a ray from the controller
  66350. */
  66351. _this._pointingPoseNode = null;
  66352. _this._workingMatrix = BABYLON.Matrix.Identity();
  66353. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66354. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66355. _this.position = BABYLON.Vector3.Zero();
  66356. _this.rotationQuaternion = new BABYLON.Quaternion();
  66357. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66358. _this._calculatedRotation = new BABYLON.Quaternion();
  66359. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66360. return _this;
  66361. }
  66362. PoseEnabledController.prototype.update = function () {
  66363. _super.prototype.update.call(this);
  66364. var pose = this.browserGamepad.pose;
  66365. this.updateFromDevice(pose);
  66366. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66367. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66368. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66369. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66370. if (this._mesh) {
  66371. this._mesh.position.copyFrom(this.devicePosition);
  66372. if (this._mesh.rotationQuaternion) {
  66373. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66374. }
  66375. }
  66376. };
  66377. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66378. if (poseData) {
  66379. this.rawPose = poseData;
  66380. if (poseData.position) {
  66381. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66382. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66383. this._deviceRoomPosition.z *= -1;
  66384. }
  66385. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66386. this._calculatedPosition.addInPlace(this.position);
  66387. }
  66388. var pose = this.rawPose;
  66389. if (poseData.orientation && pose.orientation) {
  66390. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66391. if (this._mesh) {
  66392. if (this._mesh.getScene().useRightHandedSystem) {
  66393. this._deviceRoomRotationQuaternion.z *= -1;
  66394. this._deviceRoomRotationQuaternion.w *= -1;
  66395. }
  66396. else {
  66397. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66398. }
  66399. }
  66400. // if the camera is set, rotate to the camera's rotation
  66401. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66402. }
  66403. }
  66404. };
  66405. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66406. if (this._mesh) {
  66407. this._mesh.parent = null;
  66408. }
  66409. this._mesh = mesh;
  66410. if (this._poseControlledCamera) {
  66411. this._mesh.parent = this._poseControlledCamera;
  66412. }
  66413. if (!this._mesh.rotationQuaternion) {
  66414. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66415. }
  66416. };
  66417. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66418. this._poseControlledCamera = camera;
  66419. if (this._mesh) {
  66420. this._mesh.parent = this._poseControlledCamera;
  66421. }
  66422. };
  66423. PoseEnabledController.prototype.dispose = function () {
  66424. if (this._mesh) {
  66425. this._mesh.dispose();
  66426. }
  66427. this._mesh = null;
  66428. _super.prototype.dispose.call(this);
  66429. };
  66430. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66431. get: function () {
  66432. return this._mesh;
  66433. },
  66434. enumerable: true,
  66435. configurable: true
  66436. });
  66437. PoseEnabledController.prototype.getForwardRay = function (length) {
  66438. if (length === void 0) { length = 100; }
  66439. if (!this.mesh) {
  66440. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66441. }
  66442. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66443. var origin = m.getTranslation();
  66444. var forward = new BABYLON.Vector3(0, 0, -1);
  66445. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66446. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66447. return new BABYLON.Ray(origin, direction, length);
  66448. };
  66449. /**
  66450. * Name of the child mesh that can be used to cast a ray from the controller
  66451. */
  66452. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66453. return PoseEnabledController;
  66454. }(BABYLON.Gamepad));
  66455. BABYLON.PoseEnabledController = PoseEnabledController;
  66456. })(BABYLON || (BABYLON = {}));
  66457. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66458. "use strict";
  66459. var BABYLON;
  66460. (function (BABYLON) {
  66461. var WebVRController = /** @class */ (function (_super) {
  66462. __extends(WebVRController, _super);
  66463. function WebVRController(vrGamepad) {
  66464. var _this = _super.call(this, vrGamepad) || this;
  66465. // Observables
  66466. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66467. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66468. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66469. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66470. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66471. _this.pad = { x: 0, y: 0 };
  66472. // avoid GC, store state in a tmp object
  66473. _this._changes = {
  66474. pressChanged: false,
  66475. touchChanged: false,
  66476. valueChanged: false,
  66477. changed: false
  66478. };
  66479. _this._buttons = new Array(vrGamepad.buttons.length);
  66480. _this.hand = vrGamepad.hand;
  66481. return _this;
  66482. }
  66483. WebVRController.prototype.onButtonStateChange = function (callback) {
  66484. this._onButtonStateChange = callback;
  66485. };
  66486. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66487. get: function () {
  66488. return this._defaultModel;
  66489. },
  66490. enumerable: true,
  66491. configurable: true
  66492. });
  66493. WebVRController.prototype.update = function () {
  66494. _super.prototype.update.call(this);
  66495. for (var index = 0; index < this._buttons.length; index++) {
  66496. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66497. }
  66498. ;
  66499. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66500. this.pad.x = this.leftStick.x;
  66501. this.pad.y = this.leftStick.y;
  66502. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66503. }
  66504. };
  66505. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66506. if (!newState) {
  66507. newState = {
  66508. pressed: false,
  66509. touched: false,
  66510. value: 0
  66511. };
  66512. }
  66513. if (!currentState) {
  66514. this._buttons[buttonIndex] = {
  66515. pressed: newState.pressed,
  66516. touched: newState.touched,
  66517. value: newState.value
  66518. };
  66519. return;
  66520. }
  66521. this._checkChanges(newState, currentState);
  66522. if (this._changes.changed) {
  66523. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66524. this._handleButtonChange(buttonIndex, newState, this._changes);
  66525. }
  66526. this._buttons[buttonIndex].pressed = newState.pressed;
  66527. this._buttons[buttonIndex].touched = newState.touched;
  66528. // oculus triggers are never 0, thou not touched.
  66529. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66530. };
  66531. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66532. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66533. this._changes.touchChanged = newState.touched !== currentState.touched;
  66534. this._changes.valueChanged = newState.value !== currentState.value;
  66535. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66536. return this._changes;
  66537. };
  66538. WebVRController.prototype.dispose = function () {
  66539. _super.prototype.dispose.call(this);
  66540. this.onTriggerStateChangedObservable.clear();
  66541. this.onMainButtonStateChangedObservable.clear();
  66542. this.onSecondaryButtonStateChangedObservable.clear();
  66543. this.onPadStateChangedObservable.clear();
  66544. this.onPadValuesChangedObservable.clear();
  66545. };
  66546. return WebVRController;
  66547. }(BABYLON.PoseEnabledController));
  66548. BABYLON.WebVRController = WebVRController;
  66549. })(BABYLON || (BABYLON = {}));
  66550. //# sourceMappingURL=babylon.webVRController.js.map
  66551. "use strict";
  66552. var BABYLON;
  66553. (function (BABYLON) {
  66554. var OculusTouchController = /** @class */ (function (_super) {
  66555. __extends(OculusTouchController, _super);
  66556. function OculusTouchController(vrGamepad) {
  66557. var _this = _super.call(this, vrGamepad) || this;
  66558. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66559. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66560. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66561. return _this;
  66562. }
  66563. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66564. var _this = this;
  66565. var meshName;
  66566. // Hand
  66567. if (this.hand === 'left') {
  66568. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66569. }
  66570. else {
  66571. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66572. }
  66573. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66574. /*
  66575. Parent Mesh name: oculus_touch_left
  66576. - body
  66577. - trigger
  66578. - thumbstick
  66579. - grip
  66580. - button_y
  66581. - button_x
  66582. - button_enter
  66583. */
  66584. _this._defaultModel = newMeshes[1];
  66585. _this.attachToMesh(_this._defaultModel);
  66586. if (meshLoaded) {
  66587. meshLoaded(_this._defaultModel);
  66588. }
  66589. });
  66590. };
  66591. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66592. // helper getters for left and right hand.
  66593. get: function () {
  66594. if (this.hand === 'right') {
  66595. return this.onMainButtonStateChangedObservable;
  66596. }
  66597. else {
  66598. throw new Error('No A button on left hand');
  66599. }
  66600. },
  66601. enumerable: true,
  66602. configurable: true
  66603. });
  66604. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66605. get: function () {
  66606. if (this.hand === 'right') {
  66607. return this.onSecondaryButtonStateChangedObservable;
  66608. }
  66609. else {
  66610. throw new Error('No B button on left hand');
  66611. }
  66612. },
  66613. enumerable: true,
  66614. configurable: true
  66615. });
  66616. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66617. get: function () {
  66618. if (this.hand === 'left') {
  66619. return this.onMainButtonStateChangedObservable;
  66620. }
  66621. else {
  66622. throw new Error('No X button on right hand');
  66623. }
  66624. },
  66625. enumerable: true,
  66626. configurable: true
  66627. });
  66628. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66629. get: function () {
  66630. if (this.hand === 'left') {
  66631. return this.onSecondaryButtonStateChangedObservable;
  66632. }
  66633. else {
  66634. throw new Error('No Y button on right hand');
  66635. }
  66636. },
  66637. enumerable: true,
  66638. configurable: true
  66639. });
  66640. /*
  66641. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66642. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66643. 2) secondary trigger (same)
  66644. 3) A (right) X (left), touch, pressed = value
  66645. 4) B / Y
  66646. 5) thumb rest
  66647. */
  66648. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66649. var notifyObject = state; //{ state: state, changes: changes };
  66650. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66651. switch (buttonIdx) {
  66652. case 0:
  66653. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66654. return;
  66655. case 1:// index trigger
  66656. if (this._defaultModel) {
  66657. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66658. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66659. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66660. }
  66661. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66662. return;
  66663. case 2:// secondary trigger
  66664. if (this._defaultModel) {
  66665. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66666. }
  66667. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66668. return;
  66669. case 3:
  66670. if (this._defaultModel) {
  66671. if (notifyObject.pressed) {
  66672. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66673. }
  66674. else {
  66675. (this._defaultModel.getChildren()[1]).position.y = 0;
  66676. }
  66677. }
  66678. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66679. return;
  66680. case 4:
  66681. if (this._defaultModel) {
  66682. if (notifyObject.pressed) {
  66683. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66684. }
  66685. else {
  66686. (this._defaultModel.getChildren()[2]).position.y = 0;
  66687. }
  66688. }
  66689. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66690. return;
  66691. case 5:
  66692. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66693. return;
  66694. }
  66695. };
  66696. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66697. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66698. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66699. return OculusTouchController;
  66700. }(BABYLON.WebVRController));
  66701. BABYLON.OculusTouchController = OculusTouchController;
  66702. })(BABYLON || (BABYLON = {}));
  66703. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66704. "use strict";
  66705. var BABYLON;
  66706. (function (BABYLON) {
  66707. var ViveController = /** @class */ (function (_super) {
  66708. __extends(ViveController, _super);
  66709. function ViveController(vrGamepad) {
  66710. var _this = _super.call(this, vrGamepad) || this;
  66711. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66712. _this._invertLeftStickY = true;
  66713. return _this;
  66714. }
  66715. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66716. var _this = this;
  66717. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  66718. /*
  66719. Parent Mesh name: ViveWand
  66720. - body
  66721. - r_gripper
  66722. - l_gripper
  66723. - menu_button
  66724. - system_button
  66725. - trackpad
  66726. - trigger
  66727. - LED
  66728. */
  66729. _this._defaultModel = newMeshes[1];
  66730. _this.attachToMesh(_this._defaultModel);
  66731. if (meshLoaded) {
  66732. meshLoaded(_this._defaultModel);
  66733. }
  66734. });
  66735. };
  66736. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  66737. get: function () {
  66738. return this.onMainButtonStateChangedObservable;
  66739. },
  66740. enumerable: true,
  66741. configurable: true
  66742. });
  66743. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  66744. get: function () {
  66745. return this.onMainButtonStateChangedObservable;
  66746. },
  66747. enumerable: true,
  66748. configurable: true
  66749. });
  66750. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  66751. get: function () {
  66752. return this.onSecondaryButtonStateChangedObservable;
  66753. },
  66754. enumerable: true,
  66755. configurable: true
  66756. });
  66757. /**
  66758. * Vive mapping:
  66759. * 0: touchpad
  66760. * 1: trigger
  66761. * 2: left AND right buttons
  66762. * 3: menu button
  66763. */
  66764. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66765. var notifyObject = state; //{ state: state, changes: changes };
  66766. switch (buttonIdx) {
  66767. case 0:
  66768. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66769. return;
  66770. case 1:// index trigger
  66771. if (this._defaultModel) {
  66772. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66773. }
  66774. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66775. return;
  66776. case 2:// left AND right button
  66777. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66778. return;
  66779. case 3:
  66780. if (this._defaultModel) {
  66781. if (notifyObject.pressed) {
  66782. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66783. }
  66784. else {
  66785. (this._defaultModel.getChildren()[2]).position.y = 0;
  66786. }
  66787. }
  66788. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66789. return;
  66790. }
  66791. };
  66792. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66793. ViveController.MODEL_FILENAME = 'wand.babylon';
  66794. return ViveController;
  66795. }(BABYLON.WebVRController));
  66796. BABYLON.ViveController = ViveController;
  66797. })(BABYLON || (BABYLON = {}));
  66798. //# sourceMappingURL=babylon.viveController.js.map
  66799. "use strict";
  66800. var BABYLON;
  66801. (function (BABYLON) {
  66802. var GenericController = /** @class */ (function (_super) {
  66803. __extends(GenericController, _super);
  66804. function GenericController(vrGamepad) {
  66805. return _super.call(this, vrGamepad) || this;
  66806. }
  66807. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66808. var _this = this;
  66809. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66810. _this._defaultModel = newMeshes[1];
  66811. _this.attachToMesh(_this._defaultModel);
  66812. if (meshLoaded) {
  66813. meshLoaded(_this._defaultModel);
  66814. }
  66815. });
  66816. };
  66817. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66818. console.log("Button id: " + buttonIdx + "state: ");
  66819. console.dir(state);
  66820. };
  66821. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66822. GenericController.MODEL_FILENAME = 'generic.babylon';
  66823. return GenericController;
  66824. }(BABYLON.WebVRController));
  66825. BABYLON.GenericController = GenericController;
  66826. })(BABYLON || (BABYLON = {}));
  66827. //# sourceMappingURL=babylon.genericController.js.map
  66828. "use strict";
  66829. var BABYLON;
  66830. (function (BABYLON) {
  66831. var LoadedMeshInfo = /** @class */ (function () {
  66832. function LoadedMeshInfo() {
  66833. this.buttonMeshes = {};
  66834. this.axisMeshes = {};
  66835. }
  66836. return LoadedMeshInfo;
  66837. }());
  66838. var WindowsMotionController = /** @class */ (function (_super) {
  66839. __extends(WindowsMotionController, _super);
  66840. function WindowsMotionController(vrGamepad) {
  66841. var _this = _super.call(this, vrGamepad) || this;
  66842. _this._mapping = {
  66843. // Semantic button names
  66844. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  66845. // A mapping of the button name to glTF model node name
  66846. // that should be transformed by button value.
  66847. buttonMeshNames: {
  66848. 'trigger': 'SELECT',
  66849. 'menu': 'MENU',
  66850. 'grip': 'GRASP',
  66851. 'thumbstick': 'THUMBSTICK_PRESS',
  66852. 'trackpad': 'TOUCHPAD_PRESS'
  66853. },
  66854. // This mapping is used to translate from the Motion Controller to Babylon semantics
  66855. buttonObservableNames: {
  66856. 'trigger': 'onTriggerStateChangedObservable',
  66857. 'menu': 'onSecondaryButtonStateChangedObservable',
  66858. 'grip': 'onMainButtonStateChangedObservable',
  66859. 'thumbstick': 'onPadStateChangedObservable',
  66860. 'trackpad': 'onTrackpadChangedObservable'
  66861. },
  66862. // A mapping of the axis name to glTF model node name
  66863. // that should be transformed by axis value.
  66864. // This array mirrors the browserGamepad.axes array, such that
  66865. // the mesh corresponding to axis 0 is in this array index 0.
  66866. axisMeshNames: [
  66867. 'THUMBSTICK_X',
  66868. 'THUMBSTICK_Y',
  66869. 'TOUCHPAD_TOUCH_X',
  66870. 'TOUCHPAD_TOUCH_Y'
  66871. ],
  66872. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66873. };
  66874. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66875. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66876. _this.trackpad = { x: 0, y: 0 };
  66877. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66878. _this._loadedMeshInfo = null;
  66879. return _this;
  66880. }
  66881. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66882. get: function () {
  66883. return this.onTriggerStateChangedObservable;
  66884. },
  66885. enumerable: true,
  66886. configurable: true
  66887. });
  66888. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66889. get: function () {
  66890. return this.onSecondaryButtonStateChangedObservable;
  66891. },
  66892. enumerable: true,
  66893. configurable: true
  66894. });
  66895. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66896. get: function () {
  66897. return this.onMainButtonStateChangedObservable;
  66898. },
  66899. enumerable: true,
  66900. configurable: true
  66901. });
  66902. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66903. get: function () {
  66904. return this.onPadStateChangedObservable;
  66905. },
  66906. enumerable: true,
  66907. configurable: true
  66908. });
  66909. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66910. get: function () {
  66911. return this.onTrackpadChangedObservable;
  66912. },
  66913. enumerable: true,
  66914. configurable: true
  66915. });
  66916. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66917. get: function () {
  66918. return this.onTrackpadValuesChangedObservable;
  66919. },
  66920. enumerable: true,
  66921. configurable: true
  66922. });
  66923. /**
  66924. * Called once per frame by the engine.
  66925. */
  66926. WindowsMotionController.prototype.update = function () {
  66927. _super.prototype.update.call(this);
  66928. if (this.browserGamepad.axes) {
  66929. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66930. this.trackpad.x = this.browserGamepad["axes"][2];
  66931. this.trackpad.y = this.browserGamepad["axes"][3];
  66932. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66933. }
  66934. // Only need to animate axes if there is a loaded mesh
  66935. if (this._loadedMeshInfo) {
  66936. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66937. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66938. }
  66939. }
  66940. }
  66941. };
  66942. /**
  66943. * Called once for each button that changed state since the last frame
  66944. * @param buttonIdx Which button index changed
  66945. * @param state New state of the button
  66946. * @param changes Which properties on the state changed since last frame
  66947. */
  66948. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66949. var buttonName = this._mapping.buttons[buttonIdx];
  66950. if (!buttonName) {
  66951. return;
  66952. }
  66953. // Only emit events for buttons that we know how to map from index to name
  66954. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66955. if (observable) {
  66956. observable.notifyObservers(state);
  66957. }
  66958. this.lerpButtonTransform(buttonName, state.value);
  66959. };
  66960. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66961. // If there is no loaded mesh, there is nothing to transform.
  66962. if (!this._loadedMeshInfo) {
  66963. return;
  66964. }
  66965. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66966. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66967. return;
  66968. }
  66969. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66970. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66971. };
  66972. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66973. if (!this._loadedMeshInfo) {
  66974. return;
  66975. }
  66976. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66977. if (!meshInfo) {
  66978. return;
  66979. }
  66980. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66981. return;
  66982. }
  66983. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66984. var lerpValue = axisValue * 0.5 + 0.5;
  66985. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66986. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66987. };
  66988. /**
  66989. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  66990. * @param scene scene in which to add meshes
  66991. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66992. */
  66993. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66994. var _this = this;
  66995. if (forceDefault === void 0) { forceDefault = false; }
  66996. var path;
  66997. var filename;
  66998. // Checking if GLB loader is present
  66999. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  67000. // Determine the device specific folder based on the ID suffix
  67001. var device = 'default';
  67002. if (this.id && !forceDefault) {
  67003. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  67004. device = ((match && match[0]) || device);
  67005. }
  67006. // Hand
  67007. if (this.hand === 'left') {
  67008. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  67009. }
  67010. else {
  67011. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  67012. }
  67013. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  67014. }
  67015. else {
  67016. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  67017. path = BABYLON.GenericController.MODEL_BASE_URL;
  67018. filename = BABYLON.GenericController.MODEL_FILENAME;
  67019. }
  67020. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  67021. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  67022. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  67023. if (!_this._loadedMeshInfo) {
  67024. return;
  67025. }
  67026. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  67027. _this.attachToMesh(_this._defaultModel);
  67028. if (meshLoaded) {
  67029. meshLoaded(_this._defaultModel);
  67030. }
  67031. }, null, function (scene, message) {
  67032. BABYLON.Tools.Log(message);
  67033. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67034. if (!forceDefault) {
  67035. _this.initControllerMesh(scene, meshLoaded, true);
  67036. }
  67037. });
  67038. };
  67039. /**
  67040. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67041. * can be transformed by button presses and axes values, based on this._mapping.
  67042. *
  67043. * @param scene scene in which the meshes exist
  67044. * @param meshes list of meshes that make up the controller model to process
  67045. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67046. */
  67047. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67048. var loadedMeshInfo = null;
  67049. // Create a new mesh to contain the glTF hierarchy
  67050. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67051. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67052. var childMesh = null;
  67053. for (var i = 0; i < meshes.length; i++) {
  67054. var mesh = meshes[i];
  67055. if (!mesh.parent) {
  67056. // Exclude controller meshes from picking results
  67057. mesh.isPickable = false;
  67058. // Handle root node, attach to the new parentMesh
  67059. childMesh = mesh;
  67060. break;
  67061. }
  67062. }
  67063. if (childMesh) {
  67064. childMesh.setParent(parentMesh);
  67065. // Create our mesh info. Note that this method will always return non-null.
  67066. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67067. }
  67068. else {
  67069. BABYLON.Tools.Warn('Could not find root node in model file.');
  67070. }
  67071. return loadedMeshInfo;
  67072. };
  67073. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67074. var loadedMeshInfo = new LoadedMeshInfo();
  67075. var i;
  67076. loadedMeshInfo.rootNode = rootNode;
  67077. // Reset the caches
  67078. loadedMeshInfo.buttonMeshes = {};
  67079. loadedMeshInfo.axisMeshes = {};
  67080. // Button Meshes
  67081. for (i = 0; i < this._mapping.buttons.length; i++) {
  67082. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67083. if (!buttonMeshName) {
  67084. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67085. continue;
  67086. }
  67087. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67088. if (!buttonMesh) {
  67089. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67090. continue;
  67091. }
  67092. var buttonMeshInfo = {
  67093. index: i,
  67094. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67095. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67096. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67097. };
  67098. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67099. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67100. }
  67101. else {
  67102. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67103. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67104. '(VALUE: ' + !!buttonMeshInfo.value +
  67105. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67106. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67107. ')');
  67108. }
  67109. }
  67110. // Axis Meshes
  67111. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67112. var axisMeshName = this._mapping.axisMeshNames[i];
  67113. if (!axisMeshName) {
  67114. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67115. continue;
  67116. }
  67117. var axisMesh = getChildByName(rootNode, axisMeshName);
  67118. if (!axisMesh) {
  67119. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67120. continue;
  67121. }
  67122. var axisMeshInfo = {
  67123. index: i,
  67124. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67125. min: getImmediateChildByName(axisMesh, 'MIN'),
  67126. max: getImmediateChildByName(axisMesh, 'MAX')
  67127. };
  67128. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67129. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67130. }
  67131. else {
  67132. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67133. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67134. '(VALUE: ' + !!axisMeshInfo.value +
  67135. ', MIN: ' + !!axisMeshInfo.min +
  67136. ', MAX:' + !!axisMeshInfo.max +
  67137. ')');
  67138. }
  67139. }
  67140. // Pointing Ray
  67141. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67142. if (!loadedMeshInfo.pointingPoseNode) {
  67143. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67144. }
  67145. return loadedMeshInfo;
  67146. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67147. function getChildByName(node, name) {
  67148. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67149. }
  67150. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67151. function getImmediateChildByName(node, name) {
  67152. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67153. }
  67154. };
  67155. WindowsMotionController.prototype.getForwardRay = function (length) {
  67156. if (length === void 0) { length = 100; }
  67157. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67158. return _super.prototype.getForwardRay.call(this, length);
  67159. }
  67160. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67161. var origin = m.getTranslation();
  67162. var forward = new BABYLON.Vector3(0, 0, -1);
  67163. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67164. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67165. return new BABYLON.Ray(origin, direction, length);
  67166. };
  67167. WindowsMotionController.prototype.dispose = function () {
  67168. _super.prototype.dispose.call(this);
  67169. this.onTrackpadChangedObservable.clear();
  67170. };
  67171. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67172. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67173. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67174. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67175. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67176. return WindowsMotionController;
  67177. }(BABYLON.WebVRController));
  67178. BABYLON.WindowsMotionController = WindowsMotionController;
  67179. })(BABYLON || (BABYLON = {}));
  67180. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67181. "use strict";
  67182. var BABYLON;
  67183. (function (BABYLON) {
  67184. var GearVRController = /** @class */ (function (_super) {
  67185. __extends(GearVRController, _super);
  67186. function GearVRController(vrGamepad) {
  67187. var _this = _super.call(this, vrGamepad) || this;
  67188. _this._buttonIndexToObservableNameMap = [
  67189. 'onTrackpadChangedObservable',
  67190. 'onTriggerStateChangedObservable' // Trigger
  67191. ];
  67192. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67193. return _this;
  67194. }
  67195. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67196. var _this = this;
  67197. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67198. _this._defaultModel = newMeshes[1];
  67199. _this.attachToMesh(_this._defaultModel);
  67200. if (meshLoaded) {
  67201. meshLoaded(_this._defaultModel);
  67202. }
  67203. });
  67204. };
  67205. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67206. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67207. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67208. // Only emit events for buttons that we know how to map from index to observable
  67209. var observable = this[observableName];
  67210. if (observable) {
  67211. observable.notifyObservers(state);
  67212. }
  67213. }
  67214. };
  67215. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67216. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67217. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67218. return GearVRController;
  67219. }(BABYLON.WebVRController));
  67220. BABYLON.GearVRController = GearVRController;
  67221. })(BABYLON || (BABYLON = {}));
  67222. //# sourceMappingURL=babylon.gearVRController.js.map
  67223. "use strict";
  67224. var BABYLON;
  67225. (function (BABYLON) {
  67226. /**
  67227. * Google Daydream controller
  67228. */
  67229. var DaydreamController = /** @class */ (function (_super) {
  67230. __extends(DaydreamController, _super);
  67231. function DaydreamController(vrGamepad) {
  67232. var _this = _super.call(this, vrGamepad) || this;
  67233. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67234. return _this;
  67235. }
  67236. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67237. var _this = this;
  67238. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67239. _this._defaultModel = newMeshes[1];
  67240. _this.attachToMesh(_this._defaultModel);
  67241. if (meshLoaded) {
  67242. meshLoaded(_this._defaultModel);
  67243. }
  67244. });
  67245. };
  67246. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67247. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67248. if (buttonIdx === 0) {
  67249. var observable = this.onTriggerStateChangedObservable;
  67250. if (observable) {
  67251. observable.notifyObservers(state);
  67252. }
  67253. }
  67254. else {
  67255. // If the app or home buttons are ever made available
  67256. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67257. }
  67258. };
  67259. /**
  67260. * Base Url for the controller model.
  67261. */
  67262. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67263. /**
  67264. * File name for the controller model.
  67265. */
  67266. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67267. /**
  67268. * Gamepad Id prefix used to identify Daydream Controller.
  67269. */
  67270. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67271. return DaydreamController;
  67272. }(BABYLON.WebVRController));
  67273. BABYLON.DaydreamController = DaydreamController;
  67274. })(BABYLON || (BABYLON = {}));
  67275. //# sourceMappingURL=babylon.daydreamController.js.map
  67276. "use strict";
  67277. var BABYLON;
  67278. (function (BABYLON) {
  67279. var FollowCamera = /** @class */ (function (_super) {
  67280. __extends(FollowCamera, _super);
  67281. function FollowCamera(name, position, scene, lockedTarget) {
  67282. if (lockedTarget === void 0) { lockedTarget = null; }
  67283. var _this = _super.call(this, name, position, scene) || this;
  67284. _this.radius = 12;
  67285. _this.rotationOffset = 0;
  67286. _this.heightOffset = 4;
  67287. _this.cameraAcceleration = 0.05;
  67288. _this.maxCameraSpeed = 20;
  67289. _this.lockedTarget = lockedTarget;
  67290. return _this;
  67291. }
  67292. FollowCamera.prototype.getRadians = function (degrees) {
  67293. return degrees * Math.PI / 180;
  67294. };
  67295. FollowCamera.prototype.follow = function (cameraTarget) {
  67296. if (!cameraTarget)
  67297. return;
  67298. var yRotation;
  67299. if (cameraTarget.rotationQuaternion) {
  67300. var rotMatrix = new BABYLON.Matrix();
  67301. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67302. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67303. }
  67304. else {
  67305. yRotation = cameraTarget.rotation.y;
  67306. }
  67307. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67308. var targetPosition = cameraTarget.getAbsolutePosition();
  67309. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67310. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67311. var dx = targetX - this.position.x;
  67312. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67313. var dz = (targetZ) - this.position.z;
  67314. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67315. var vy = dy * this.cameraAcceleration;
  67316. var vz = dz * this.cameraAcceleration * 2;
  67317. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67318. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67319. }
  67320. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67321. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67322. }
  67323. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67324. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67325. }
  67326. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67327. this.setTarget(targetPosition);
  67328. };
  67329. FollowCamera.prototype._checkInputs = function () {
  67330. _super.prototype._checkInputs.call(this);
  67331. if (this.lockedTarget) {
  67332. this.follow(this.lockedTarget);
  67333. }
  67334. };
  67335. FollowCamera.prototype.getClassName = function () {
  67336. return "FollowCamera";
  67337. };
  67338. __decorate([
  67339. BABYLON.serialize()
  67340. ], FollowCamera.prototype, "radius", void 0);
  67341. __decorate([
  67342. BABYLON.serialize()
  67343. ], FollowCamera.prototype, "rotationOffset", void 0);
  67344. __decorate([
  67345. BABYLON.serialize()
  67346. ], FollowCamera.prototype, "heightOffset", void 0);
  67347. __decorate([
  67348. BABYLON.serialize()
  67349. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67350. __decorate([
  67351. BABYLON.serialize()
  67352. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67353. __decorate([
  67354. BABYLON.serializeAsMeshReference("lockedTargetId")
  67355. ], FollowCamera.prototype, "lockedTarget", void 0);
  67356. return FollowCamera;
  67357. }(BABYLON.TargetCamera));
  67358. BABYLON.FollowCamera = FollowCamera;
  67359. var ArcFollowCamera = /** @class */ (function (_super) {
  67360. __extends(ArcFollowCamera, _super);
  67361. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67362. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67363. _this.alpha = alpha;
  67364. _this.beta = beta;
  67365. _this.radius = radius;
  67366. _this.target = target;
  67367. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67368. _this.follow();
  67369. return _this;
  67370. }
  67371. ArcFollowCamera.prototype.follow = function () {
  67372. if (!this.target) {
  67373. return;
  67374. }
  67375. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67376. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67377. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67378. var targetPosition = this.target.getAbsolutePosition();
  67379. this.position = targetPosition.add(this._cartesianCoordinates);
  67380. this.setTarget(targetPosition);
  67381. };
  67382. ArcFollowCamera.prototype._checkInputs = function () {
  67383. _super.prototype._checkInputs.call(this);
  67384. this.follow();
  67385. };
  67386. ArcFollowCamera.prototype.getClassName = function () {
  67387. return "ArcFollowCamera";
  67388. };
  67389. return ArcFollowCamera;
  67390. }(BABYLON.TargetCamera));
  67391. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67392. })(BABYLON || (BABYLON = {}));
  67393. //# sourceMappingURL=babylon.followCamera.js.map
  67394. "use strict";
  67395. var BABYLON;
  67396. (function (BABYLON) {
  67397. // We're mainly based on the logic defined into the FreeCamera code
  67398. var UniversalCamera = /** @class */ (function (_super) {
  67399. __extends(UniversalCamera, _super);
  67400. //-- end properties for backward compatibility for inputs
  67401. function UniversalCamera(name, position, scene) {
  67402. var _this = _super.call(this, name, position, scene) || this;
  67403. _this.inputs.addGamepad();
  67404. return _this;
  67405. }
  67406. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67407. //-- Begin properties for backward compatibility for inputs
  67408. get: function () {
  67409. var gamepad = this.inputs.attached["gamepad"];
  67410. if (gamepad)
  67411. return gamepad.gamepadAngularSensibility;
  67412. return 0;
  67413. },
  67414. set: function (value) {
  67415. var gamepad = this.inputs.attached["gamepad"];
  67416. if (gamepad)
  67417. gamepad.gamepadAngularSensibility = value;
  67418. },
  67419. enumerable: true,
  67420. configurable: true
  67421. });
  67422. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67423. get: function () {
  67424. var gamepad = this.inputs.attached["gamepad"];
  67425. if (gamepad)
  67426. return gamepad.gamepadMoveSensibility;
  67427. return 0;
  67428. },
  67429. set: function (value) {
  67430. var gamepad = this.inputs.attached["gamepad"];
  67431. if (gamepad)
  67432. gamepad.gamepadMoveSensibility = value;
  67433. },
  67434. enumerable: true,
  67435. configurable: true
  67436. });
  67437. UniversalCamera.prototype.getClassName = function () {
  67438. return "UniversalCamera";
  67439. };
  67440. return UniversalCamera;
  67441. }(BABYLON.TouchCamera));
  67442. BABYLON.UniversalCamera = UniversalCamera;
  67443. })(BABYLON || (BABYLON = {}));
  67444. //# sourceMappingURL=babylon.universalCamera.js.map
  67445. "use strict";
  67446. var BABYLON;
  67447. (function (BABYLON) {
  67448. // We're mainly based on the logic defined into the FreeCamera code
  67449. var GamepadCamera = /** @class */ (function (_super) {
  67450. __extends(GamepadCamera, _super);
  67451. //-- end properties for backward compatibility for inputs
  67452. function GamepadCamera(name, position, scene) {
  67453. return _super.call(this, name, position, scene) || this;
  67454. }
  67455. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67456. //-- Begin properties for backward compatibility for inputs
  67457. get: function () {
  67458. var gamepad = this.inputs.attached["gamepad"];
  67459. if (gamepad)
  67460. return gamepad.gamepadAngularSensibility;
  67461. return 0;
  67462. },
  67463. set: function (value) {
  67464. var gamepad = this.inputs.attached["gamepad"];
  67465. if (gamepad)
  67466. gamepad.gamepadAngularSensibility = value;
  67467. },
  67468. enumerable: true,
  67469. configurable: true
  67470. });
  67471. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67472. get: function () {
  67473. var gamepad = this.inputs.attached["gamepad"];
  67474. if (gamepad)
  67475. return gamepad.gamepadMoveSensibility;
  67476. return 0;
  67477. },
  67478. set: function (value) {
  67479. var gamepad = this.inputs.attached["gamepad"];
  67480. if (gamepad)
  67481. gamepad.gamepadMoveSensibility = value;
  67482. },
  67483. enumerable: true,
  67484. configurable: true
  67485. });
  67486. GamepadCamera.prototype.getClassName = function () {
  67487. return "GamepadCamera";
  67488. };
  67489. return GamepadCamera;
  67490. }(BABYLON.UniversalCamera));
  67491. BABYLON.GamepadCamera = GamepadCamera;
  67492. })(BABYLON || (BABYLON = {}));
  67493. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67494. "use strict";
  67495. var BABYLON;
  67496. (function (BABYLON) {
  67497. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67498. function PostProcessRenderPipelineManager() {
  67499. this._renderPipelines = {};
  67500. }
  67501. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67502. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67503. };
  67504. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67505. if (unique === void 0) { unique = false; }
  67506. var renderPipeline = this._renderPipelines[renderPipelineName];
  67507. if (!renderPipeline) {
  67508. return;
  67509. }
  67510. renderPipeline._attachCameras(cameras, unique);
  67511. };
  67512. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67513. var renderPipeline = this._renderPipelines[renderPipelineName];
  67514. if (!renderPipeline) {
  67515. return;
  67516. }
  67517. renderPipeline._detachCameras(cameras);
  67518. };
  67519. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67520. var renderPipeline = this._renderPipelines[renderPipelineName];
  67521. if (!renderPipeline) {
  67522. return;
  67523. }
  67524. renderPipeline._enableEffect(renderEffectName, cameras);
  67525. };
  67526. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67527. var renderPipeline = this._renderPipelines[renderPipelineName];
  67528. if (!renderPipeline) {
  67529. return;
  67530. }
  67531. renderPipeline._disableEffect(renderEffectName, cameras);
  67532. };
  67533. PostProcessRenderPipelineManager.prototype.update = function () {
  67534. for (var renderPipelineName in this._renderPipelines) {
  67535. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67536. var pipeline = this._renderPipelines[renderPipelineName];
  67537. if (!pipeline.isSupported) {
  67538. pipeline.dispose();
  67539. delete this._renderPipelines[renderPipelineName];
  67540. }
  67541. else {
  67542. pipeline._update();
  67543. }
  67544. }
  67545. }
  67546. };
  67547. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67548. for (var renderPipelineName in this._renderPipelines) {
  67549. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67550. var pipeline = this._renderPipelines[renderPipelineName];
  67551. pipeline._rebuild();
  67552. }
  67553. }
  67554. };
  67555. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67556. for (var renderPipelineName in this._renderPipelines) {
  67557. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67558. var pipeline = this._renderPipelines[renderPipelineName];
  67559. pipeline.dispose();
  67560. }
  67561. }
  67562. };
  67563. return PostProcessRenderPipelineManager;
  67564. }());
  67565. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67566. })(BABYLON || (BABYLON = {}));
  67567. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67568. "use strict";
  67569. var BABYLON;
  67570. (function (BABYLON) {
  67571. /**
  67572. * This represents a set of one or more post processes in Babylon.
  67573. * A post process can be used to apply a shader to a texture after it is rendered.
  67574. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67575. */
  67576. var PostProcessRenderEffect = /** @class */ (function () {
  67577. /**
  67578. * Instantiates a post process render effect.
  67579. * A post process can be used to apply a shader to a texture after it is rendered.
  67580. * @param engine The engine the effect is tied to
  67581. * @param name The name of the effect
  67582. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67583. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67584. */
  67585. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67586. this._name = name;
  67587. this._singleInstance = singleInstance || true;
  67588. this._getPostProcesses = getPostProcesses;
  67589. this._cameras = {};
  67590. this._indicesForCamera = {};
  67591. this._postProcesses = {};
  67592. }
  67593. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67594. /**
  67595. * Checks if all the post processes in the effect are supported.
  67596. */
  67597. get: function () {
  67598. for (var index in this._postProcesses) {
  67599. for (var ppIndex in this._postProcesses[index]) {
  67600. if (!this._postProcesses[index][ppIndex].isSupported) {
  67601. return false;
  67602. }
  67603. }
  67604. }
  67605. return true;
  67606. },
  67607. enumerable: true,
  67608. configurable: true
  67609. });
  67610. /**
  67611. * Updates the current state of the effect
  67612. */
  67613. PostProcessRenderEffect.prototype._update = function () {
  67614. };
  67615. /**
  67616. * Attaches the effect on cameras
  67617. * @param cameras The camera to attach to.
  67618. */
  67619. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67620. var _this = this;
  67621. var cameraKey;
  67622. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67623. if (!cams) {
  67624. return;
  67625. }
  67626. for (var i = 0; i < cams.length; i++) {
  67627. var camera = cams[i];
  67628. var cameraName = camera.name;
  67629. if (this._singleInstance) {
  67630. cameraKey = 0;
  67631. }
  67632. else {
  67633. cameraKey = cameraName;
  67634. }
  67635. if (!this._postProcesses[cameraKey]) {
  67636. var postProcess = this._getPostProcesses();
  67637. if (postProcess) {
  67638. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67639. }
  67640. }
  67641. if (!this._indicesForCamera[cameraName]) {
  67642. this._indicesForCamera[cameraName] = [];
  67643. }
  67644. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67645. var index = camera.attachPostProcess(postProcess);
  67646. _this._indicesForCamera[cameraName].push(index);
  67647. });
  67648. if (!this._cameras[cameraName]) {
  67649. this._cameras[cameraName] = camera;
  67650. }
  67651. }
  67652. };
  67653. /**
  67654. * Detatches the effect on cameras
  67655. * @param cameras The camera to detatch from.
  67656. */
  67657. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67658. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67659. if (!cams) {
  67660. return;
  67661. }
  67662. for (var i = 0; i < cams.length; i++) {
  67663. var camera = cams[i];
  67664. var cameraName = camera.name;
  67665. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67666. camera.detachPostProcess(postProcess);
  67667. });
  67668. if (this._cameras[cameraName]) {
  67669. //this._indicesForCamera.splice(index, 1);
  67670. this._cameras[cameraName] = null;
  67671. }
  67672. }
  67673. };
  67674. /**
  67675. * Enables the effect on given cameras
  67676. * @param cameras The camera to enable.
  67677. */
  67678. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67679. var _this = this;
  67680. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67681. if (!cams) {
  67682. return;
  67683. }
  67684. for (var i = 0; i < cams.length; i++) {
  67685. var camera = cams[i];
  67686. var cameraName = camera.name;
  67687. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67688. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67689. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67690. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67691. });
  67692. }
  67693. }
  67694. }
  67695. };
  67696. /**
  67697. * Disables the effect on the given cameras
  67698. * @param cameras The camera to disable.
  67699. */
  67700. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67701. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67702. if (!cams) {
  67703. return;
  67704. }
  67705. for (var i = 0; i < cams.length; i++) {
  67706. var camera = cams[i];
  67707. var cameraName = camera.name;
  67708. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67709. camera.detachPostProcess(postProcess);
  67710. });
  67711. }
  67712. };
  67713. /**
  67714. * Gets a list of the post processes contained in the effect.
  67715. * @param camera The camera to get the post processes on.
  67716. * @returns The list of the post processes in the effect.
  67717. */
  67718. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  67719. if (this._singleInstance) {
  67720. return this._postProcesses[0];
  67721. }
  67722. else {
  67723. if (!camera) {
  67724. return null;
  67725. }
  67726. return this._postProcesses[camera.name];
  67727. }
  67728. };
  67729. return PostProcessRenderEffect;
  67730. }());
  67731. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  67732. })(BABYLON || (BABYLON = {}));
  67733. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  67734. "use strict";
  67735. var BABYLON;
  67736. (function (BABYLON) {
  67737. var PostProcessRenderPipeline = /** @class */ (function () {
  67738. function PostProcessRenderPipeline(engine, name) {
  67739. this.engine = engine;
  67740. this._name = name;
  67741. this._renderEffects = {};
  67742. this._renderEffectsForIsolatedPass = new Array();
  67743. this._cameras = [];
  67744. }
  67745. PostProcessRenderPipeline.prototype.getClassName = function () {
  67746. return "PostProcessRenderPipeline";
  67747. };
  67748. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  67749. get: function () {
  67750. for (var renderEffectName in this._renderEffects) {
  67751. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67752. if (!this._renderEffects[renderEffectName].isSupported) {
  67753. return false;
  67754. }
  67755. }
  67756. }
  67757. return true;
  67758. },
  67759. enumerable: true,
  67760. configurable: true
  67761. });
  67762. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  67763. this._renderEffects[renderEffect._name] = renderEffect;
  67764. };
  67765. // private
  67766. PostProcessRenderPipeline.prototype._rebuild = function () {
  67767. };
  67768. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67769. var renderEffects = this._renderEffects[renderEffectName];
  67770. if (!renderEffects) {
  67771. return;
  67772. }
  67773. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67774. };
  67775. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67776. var renderEffects = this._renderEffects[renderEffectName];
  67777. if (!renderEffects) {
  67778. return;
  67779. }
  67780. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67781. };
  67782. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67783. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67784. if (!cams) {
  67785. return;
  67786. }
  67787. var indicesToDelete = [];
  67788. var i;
  67789. for (i = 0; i < cams.length; i++) {
  67790. var camera = cams[i];
  67791. var cameraName = camera.name;
  67792. if (this._cameras.indexOf(camera) === -1) {
  67793. this._cameras[cameraName] = camera;
  67794. }
  67795. else if (unique) {
  67796. indicesToDelete.push(i);
  67797. }
  67798. }
  67799. for (i = 0; i < indicesToDelete.length; i++) {
  67800. cameras.splice(indicesToDelete[i], 1);
  67801. }
  67802. for (var renderEffectName in this._renderEffects) {
  67803. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67804. this._renderEffects[renderEffectName]._attachCameras(cams);
  67805. }
  67806. }
  67807. };
  67808. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67809. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67810. if (!cams) {
  67811. return;
  67812. }
  67813. for (var renderEffectName in this._renderEffects) {
  67814. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67815. this._renderEffects[renderEffectName]._detachCameras(cams);
  67816. }
  67817. }
  67818. for (var i = 0; i < cams.length; i++) {
  67819. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  67820. }
  67821. };
  67822. PostProcessRenderPipeline.prototype._update = function () {
  67823. for (var renderEffectName in this._renderEffects) {
  67824. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67825. this._renderEffects[renderEffectName]._update();
  67826. }
  67827. }
  67828. for (var i = 0; i < this._cameras.length; i++) {
  67829. var cameraName = this._cameras[i].name;
  67830. if (this._renderEffectsForIsolatedPass[cameraName]) {
  67831. this._renderEffectsForIsolatedPass[cameraName]._update();
  67832. }
  67833. }
  67834. };
  67835. PostProcessRenderPipeline.prototype._reset = function () {
  67836. this._renderEffects = {};
  67837. this._renderEffectsForIsolatedPass = new Array();
  67838. };
  67839. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  67840. // 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)
  67841. var effectKeys = Object.keys(this._renderEffects);
  67842. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  67843. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  67844. if (postProcesses) {
  67845. postProcesses[0].samples = 4;
  67846. return true;
  67847. }
  67848. }
  67849. return false;
  67850. };
  67851. PostProcessRenderPipeline.prototype.dispose = function () {
  67852. // Must be implemented by children
  67853. };
  67854. __decorate([
  67855. BABYLON.serialize()
  67856. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  67857. return PostProcessRenderPipeline;
  67858. }());
  67859. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  67860. })(BABYLON || (BABYLON = {}));
  67861. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  67862. "use strict";
  67863. var BABYLON;
  67864. (function (BABYLON) {
  67865. /**
  67866. * This represents a depth renderer in Babylon.
  67867. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  67868. */
  67869. var DepthRenderer = /** @class */ (function () {
  67870. /**
  67871. * Instantiates a depth renderer
  67872. * @param scene The scene the renderer belongs to
  67873. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67874. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67875. */
  67876. function DepthRenderer(scene, type, camera) {
  67877. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67878. if (camera === void 0) { camera = null; }
  67879. var _this = this;
  67880. this._scene = scene;
  67881. this._camera = camera;
  67882. var engine = scene.getEngine();
  67883. // Render target
  67884. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67885. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67886. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67887. this._depthMap.refreshRate = 1;
  67888. this._depthMap.renderParticles = false;
  67889. this._depthMap.renderList = null;
  67890. // Camera to get depth map from to support multiple concurrent cameras
  67891. this._depthMap.activeCamera = this._camera;
  67892. this._depthMap.ignoreCameraViewport = true;
  67893. this._depthMap.useCameraPostProcesses = false;
  67894. // set default depth value to 1.0 (far away)
  67895. this._depthMap.onClearObservable.add(function (engine) {
  67896. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67897. });
  67898. // Custom render function
  67899. var renderSubMesh = function (subMesh) {
  67900. var mesh = subMesh.getRenderingMesh();
  67901. var scene = _this._scene;
  67902. var engine = scene.getEngine();
  67903. var material = subMesh.getMaterial();
  67904. if (!material) {
  67905. return;
  67906. }
  67907. // Culling and reverse (right handed system)
  67908. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67909. // Managing instances
  67910. var batch = mesh._getInstancesRenderList(subMesh._id);
  67911. if (batch.mustReturn) {
  67912. return;
  67913. }
  67914. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67915. var camera = _this._camera || scene.activeCamera;
  67916. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67917. engine.enableEffect(_this._effect);
  67918. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67919. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67920. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67921. // Alpha test
  67922. if (material && material.needAlphaTesting()) {
  67923. var alphaTexture = material.getAlphaTestTexture();
  67924. if (alphaTexture) {
  67925. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67926. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67927. }
  67928. }
  67929. // Bones
  67930. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67931. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67932. }
  67933. // Draw
  67934. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67935. }
  67936. };
  67937. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67938. var index;
  67939. if (depthOnlySubMeshes.length) {
  67940. engine.setColorWrite(false);
  67941. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67942. renderSubMesh(depthOnlySubMeshes.data[index]);
  67943. }
  67944. engine.setColorWrite(true);
  67945. }
  67946. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67947. renderSubMesh(opaqueSubMeshes.data[index]);
  67948. }
  67949. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67950. renderSubMesh(alphaTestSubMeshes.data[index]);
  67951. }
  67952. };
  67953. }
  67954. /**
  67955. * Creates the depth rendering effect and checks if the effect is ready.
  67956. * @param subMesh The submesh to be used to render the depth map of
  67957. * @param useInstances If multiple world instances should be used
  67958. * @returns if the depth renderer is ready to render the depth map
  67959. */
  67960. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67961. var material = subMesh.getMaterial();
  67962. if (material.disableDepthWrite) {
  67963. return false;
  67964. }
  67965. var defines = [];
  67966. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67967. var mesh = subMesh.getMesh();
  67968. // Alpha test
  67969. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67970. defines.push("#define ALPHATEST");
  67971. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67972. attribs.push(BABYLON.VertexBuffer.UVKind);
  67973. defines.push("#define UV1");
  67974. }
  67975. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67976. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67977. defines.push("#define UV2");
  67978. }
  67979. }
  67980. // Bones
  67981. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67982. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67983. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67984. if (mesh.numBoneInfluencers > 4) {
  67985. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67986. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67987. }
  67988. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67989. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67990. }
  67991. else {
  67992. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67993. }
  67994. // Instances
  67995. if (useInstances) {
  67996. defines.push("#define INSTANCES");
  67997. attribs.push("world0");
  67998. attribs.push("world1");
  67999. attribs.push("world2");
  68000. attribs.push("world3");
  68001. }
  68002. // Get correct effect
  68003. var join = defines.join("\n");
  68004. if (this._cachedDefines !== join) {
  68005. this._cachedDefines = join;
  68006. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  68007. }
  68008. return this._effect.isReady();
  68009. };
  68010. /**
  68011. * Gets the texture which the depth map will be written to.
  68012. * @returns The depth map texture
  68013. */
  68014. DepthRenderer.prototype.getDepthMap = function () {
  68015. return this._depthMap;
  68016. };
  68017. /**
  68018. * Disposes of the depth renderer.
  68019. */
  68020. DepthRenderer.prototype.dispose = function () {
  68021. this._depthMap.dispose();
  68022. };
  68023. return DepthRenderer;
  68024. }());
  68025. BABYLON.DepthRenderer = DepthRenderer;
  68026. })(BABYLON || (BABYLON = {}));
  68027. //# sourceMappingURL=babylon.depthRenderer.js.map
  68028. "use strict";
  68029. var BABYLON;
  68030. (function (BABYLON) {
  68031. var SSAORenderingPipeline = /** @class */ (function (_super) {
  68032. __extends(SSAORenderingPipeline, _super);
  68033. /**
  68034. * @constructor
  68035. * @param {string} name - The rendering pipeline name
  68036. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68037. * @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 }
  68038. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68039. */
  68040. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68041. var _this = _super.call(this, scene.getEngine(), name) || this;
  68042. // Members
  68043. /**
  68044. * The PassPostProcess id in the pipeline that contains the original scene color
  68045. * @type {string}
  68046. */
  68047. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68048. /**
  68049. * The SSAO PostProcess id in the pipeline
  68050. * @type {string}
  68051. */
  68052. _this.SSAORenderEffect = "SSAORenderEffect";
  68053. /**
  68054. * The horizontal blur PostProcess id in the pipeline
  68055. * @type {string}
  68056. */
  68057. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68058. /**
  68059. * The vertical blur PostProcess id in the pipeline
  68060. * @type {string}
  68061. */
  68062. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68063. /**
  68064. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68065. * @type {string}
  68066. */
  68067. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68068. /**
  68069. * The output strength of the SSAO post-process. Default value is 1.0.
  68070. * @type {number}
  68071. */
  68072. _this.totalStrength = 1.0;
  68073. /**
  68074. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68075. * @type {number}
  68076. */
  68077. _this.radius = 0.0001;
  68078. /**
  68079. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68080. * Must not be equal to fallOff and superior to fallOff.
  68081. * Default value is 0.975
  68082. * @type {number}
  68083. */
  68084. _this.area = 0.0075;
  68085. /**
  68086. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68087. * Must not be equal to area and inferior to area.
  68088. * Default value is 0.0
  68089. * @type {number}
  68090. */
  68091. _this.fallOff = 0.000001;
  68092. /**
  68093. * The base color of the SSAO post-process
  68094. * The final result is "base + ssao" between [0, 1]
  68095. * @type {number}
  68096. */
  68097. _this.base = 0.5;
  68098. _this._firstUpdate = true;
  68099. _this._scene = scene;
  68100. // Set up assets
  68101. _this._createRandomTexture();
  68102. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68103. var ssaoRatio = ratio.ssaoRatio || ratio;
  68104. var combineRatio = ratio.combineRatio || ratio;
  68105. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68106. _this._createSSAOPostProcess(ssaoRatio);
  68107. _this._createBlurPostProcess(ssaoRatio);
  68108. _this._createSSAOCombinePostProcess(combineRatio);
  68109. // Set up pipeline
  68110. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68111. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68112. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68113. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68114. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68115. // Finish
  68116. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68117. if (cameras)
  68118. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68119. return _this;
  68120. }
  68121. // Public Methods
  68122. /**
  68123. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68124. */
  68125. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68126. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68127. for (var i = 0; i < this._scene.cameras.length; i++) {
  68128. var camera = this._scene.cameras[i];
  68129. this._originalColorPostProcess.dispose(camera);
  68130. this._ssaoPostProcess.dispose(camera);
  68131. this._blurHPostProcess.dispose(camera);
  68132. this._blurVPostProcess.dispose(camera);
  68133. this._ssaoCombinePostProcess.dispose(camera);
  68134. }
  68135. this._randomTexture.dispose();
  68136. if (disableDepthRender)
  68137. this._scene.disableDepthRenderer();
  68138. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68139. _super.prototype.dispose.call(this);
  68140. };
  68141. // Private Methods
  68142. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68143. var _this = this;
  68144. var size = 16;
  68145. 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);
  68146. 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);
  68147. this._blurHPostProcess.onActivateObservable.add(function () {
  68148. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68149. _this._blurHPostProcess.kernel = size * dw;
  68150. });
  68151. this._blurVPostProcess.onActivateObservable.add(function () {
  68152. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68153. _this._blurVPostProcess.kernel = size * dw;
  68154. });
  68155. };
  68156. SSAORenderingPipeline.prototype._rebuild = function () {
  68157. this._firstUpdate = true;
  68158. _super.prototype._rebuild.call(this);
  68159. };
  68160. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68161. var _this = this;
  68162. var numSamples = 16;
  68163. var sampleSphere = [
  68164. 0.5381, 0.1856, -0.4319,
  68165. 0.1379, 0.2486, 0.4430,
  68166. 0.3371, 0.5679, -0.0057,
  68167. -0.6999, -0.0451, -0.0019,
  68168. 0.0689, -0.1598, -0.8547,
  68169. 0.0560, 0.0069, -0.1843,
  68170. -0.0146, 0.1402, 0.0762,
  68171. 0.0100, -0.1924, -0.0344,
  68172. -0.3577, -0.5301, -0.4358,
  68173. -0.3169, 0.1063, 0.0158,
  68174. 0.0103, -0.5869, 0.0046,
  68175. -0.0897, -0.4940, 0.3287,
  68176. 0.7119, -0.0154, -0.0918,
  68177. -0.0533, 0.0596, -0.5411,
  68178. 0.0352, -0.0631, 0.5460,
  68179. -0.4776, 0.2847, -0.0271
  68180. ];
  68181. var samplesFactor = 1.0 / numSamples;
  68182. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68183. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68184. "area", "fallOff", "base", "range", "viewport"
  68185. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68186. this._ssaoPostProcess.onApply = function (effect) {
  68187. if (_this._firstUpdate) {
  68188. effect.setArray3("sampleSphere", sampleSphere);
  68189. effect.setFloat("samplesFactor", samplesFactor);
  68190. effect.setFloat("randTextureTiles", 4.0);
  68191. }
  68192. effect.setFloat("totalStrength", _this.totalStrength);
  68193. effect.setFloat("radius", _this.radius);
  68194. effect.setFloat("area", _this.area);
  68195. effect.setFloat("fallOff", _this.fallOff);
  68196. effect.setFloat("base", _this.base);
  68197. effect.setTexture("textureSampler", _this._depthTexture);
  68198. effect.setTexture("randomSampler", _this._randomTexture);
  68199. };
  68200. };
  68201. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68202. var _this = this;
  68203. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68204. this._ssaoCombinePostProcess.onApply = function (effect) {
  68205. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68206. };
  68207. };
  68208. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68209. var size = 512;
  68210. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68211. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68212. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68213. var context = this._randomTexture.getContext();
  68214. var rand = function (min, max) {
  68215. return Math.random() * (max - min) + min;
  68216. };
  68217. var randVector = BABYLON.Vector3.Zero();
  68218. for (var x = 0; x < size; x++) {
  68219. for (var y = 0; y < size; y++) {
  68220. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68221. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68222. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68223. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68224. context.fillRect(x, y, 1, 1);
  68225. }
  68226. }
  68227. this._randomTexture.update(false);
  68228. };
  68229. __decorate([
  68230. BABYLON.serialize()
  68231. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68232. __decorate([
  68233. BABYLON.serialize()
  68234. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68235. __decorate([
  68236. BABYLON.serialize()
  68237. ], SSAORenderingPipeline.prototype, "area", void 0);
  68238. __decorate([
  68239. BABYLON.serialize()
  68240. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68241. __decorate([
  68242. BABYLON.serialize()
  68243. ], SSAORenderingPipeline.prototype, "base", void 0);
  68244. return SSAORenderingPipeline;
  68245. }(BABYLON.PostProcessRenderPipeline));
  68246. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68247. })(BABYLON || (BABYLON = {}));
  68248. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68249. "use strict";
  68250. var BABYLON;
  68251. (function (BABYLON) {
  68252. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68253. __extends(SSAO2RenderingPipeline, _super);
  68254. /**
  68255. * @constructor
  68256. * @param {string} name - The rendering pipeline name
  68257. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68258. * @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 }
  68259. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68260. */
  68261. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68262. var _this = _super.call(this, scene.getEngine(), name) || this;
  68263. // Members
  68264. /**
  68265. * The PassPostProcess id in the pipeline that contains the original scene color
  68266. * @type {string}
  68267. */
  68268. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68269. /**
  68270. * The SSAO PostProcess id in the pipeline
  68271. * @type {string}
  68272. */
  68273. _this.SSAORenderEffect = "SSAORenderEffect";
  68274. /**
  68275. * The horizontal blur PostProcess id in the pipeline
  68276. * @type {string}
  68277. */
  68278. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68279. /**
  68280. * The vertical blur PostProcess id in the pipeline
  68281. * @type {string}
  68282. */
  68283. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68284. /**
  68285. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68286. * @type {string}
  68287. */
  68288. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68289. /**
  68290. * The output strength of the SSAO post-process. Default value is 1.0.
  68291. * @type {number}
  68292. */
  68293. _this.totalStrength = 1.0;
  68294. /**
  68295. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68296. * @type {number}
  68297. */
  68298. _this.maxZ = 100.0;
  68299. /**
  68300. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68301. * @type {number}
  68302. */
  68303. _this.minZAspect = 0.2;
  68304. /**
  68305. * Number of samples used for the SSAO calculations. Default value is 8
  68306. * @type {number}
  68307. */
  68308. _this._samples = 8;
  68309. /**
  68310. * Are we using bilateral blur ?
  68311. * @type {boolean}
  68312. */
  68313. _this._expensiveBlur = true;
  68314. /**
  68315. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68316. * @type {number}
  68317. */
  68318. _this.radius = 2.0;
  68319. /**
  68320. * The base color of the SSAO post-process
  68321. * The final result is "base + ssao" between [0, 1]
  68322. * @type {number}
  68323. */
  68324. _this.base = 0.1;
  68325. _this._firstUpdate = true;
  68326. _this._scene = scene;
  68327. if (!_this.isSupported) {
  68328. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68329. return _this;
  68330. }
  68331. var ssaoRatio = ratio.ssaoRatio || ratio;
  68332. var blurRatio = ratio.blurRatio || ratio;
  68333. // Set up assets
  68334. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68335. _this._createRandomTexture();
  68336. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68337. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68338. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68339. _this._createSSAOPostProcess(1.0);
  68340. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68341. _this._createSSAOCombinePostProcess(blurRatio);
  68342. // Set up pipeline
  68343. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68345. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68346. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68347. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68348. // Finish
  68349. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68350. if (cameras)
  68351. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68352. return _this;
  68353. }
  68354. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68355. get: function () {
  68356. return this._samples;
  68357. },
  68358. set: function (n) {
  68359. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68360. this._samples = n;
  68361. this._sampleSphere = this._generateHemisphere();
  68362. this._firstUpdate = true;
  68363. },
  68364. enumerable: true,
  68365. configurable: true
  68366. });
  68367. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68368. get: function () {
  68369. return this._expensiveBlur;
  68370. },
  68371. set: function (b) {
  68372. 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"]);
  68373. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68374. this._expensiveBlur = b;
  68375. this._firstUpdate = true;
  68376. },
  68377. enumerable: true,
  68378. configurable: true
  68379. });
  68380. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68381. /**
  68382. * Support test.
  68383. * @type {boolean}
  68384. */
  68385. get: function () {
  68386. var engine = BABYLON.Engine.LastCreatedEngine;
  68387. if (!engine) {
  68388. return false;
  68389. }
  68390. return engine.getCaps().drawBuffersExtension;
  68391. },
  68392. enumerable: true,
  68393. configurable: true
  68394. });
  68395. // Public Methods
  68396. /**
  68397. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68398. */
  68399. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68400. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68401. for (var i = 0; i < this._scene.cameras.length; i++) {
  68402. var camera = this._scene.cameras[i];
  68403. this._originalColorPostProcess.dispose(camera);
  68404. this._ssaoPostProcess.dispose(camera);
  68405. this._blurHPostProcess.dispose(camera);
  68406. this._blurVPostProcess.dispose(camera);
  68407. this._ssaoCombinePostProcess.dispose(camera);
  68408. }
  68409. this._randomTexture.dispose();
  68410. if (disableGeometryBufferRenderer)
  68411. this._scene.disableGeometryBufferRenderer();
  68412. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68413. _super.prototype.dispose.call(this);
  68414. };
  68415. // Private Methods
  68416. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68417. var _this = this;
  68418. this._samplerOffsets = [];
  68419. var expensive = this.expensiveBlur;
  68420. for (var i = -8; i < 8; i++) {
  68421. this._samplerOffsets.push(i * 2 + 0.5);
  68422. }
  68423. 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");
  68424. this._blurHPostProcess.onApply = function (effect) {
  68425. if (!_this._scene.activeCamera) {
  68426. return;
  68427. }
  68428. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68429. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68430. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68431. effect.setFloat("radius", _this.radius);
  68432. effect.setTexture("depthSampler", _this._depthTexture);
  68433. if (_this._firstUpdate) {
  68434. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68435. }
  68436. };
  68437. 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");
  68438. this._blurVPostProcess.onApply = function (effect) {
  68439. if (!_this._scene.activeCamera) {
  68440. return;
  68441. }
  68442. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68443. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68444. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68445. effect.setFloat("radius", _this.radius);
  68446. effect.setTexture("depthSampler", _this._depthTexture);
  68447. if (_this._firstUpdate) {
  68448. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68449. _this._firstUpdate = false;
  68450. }
  68451. };
  68452. };
  68453. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68454. this._firstUpdate = true;
  68455. _super.prototype._rebuild.call(this);
  68456. };
  68457. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68458. var numSamples = this.samples;
  68459. var result = [];
  68460. var vector, scale;
  68461. var rand = function (min, max) {
  68462. return Math.random() * (max - min) + min;
  68463. };
  68464. var i = 0;
  68465. while (i < numSamples) {
  68466. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68467. vector.normalize();
  68468. scale = i / numSamples;
  68469. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68470. vector.scaleInPlace(scale);
  68471. result.push(vector.x, vector.y, vector.z);
  68472. i++;
  68473. }
  68474. return result;
  68475. };
  68476. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68477. var _this = this;
  68478. var numSamples = this.samples;
  68479. this._sampleSphere = this._generateHemisphere();
  68480. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68481. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68482. "base", "range", "projection", "near", "far", "texelSize",
  68483. "xViewport", "yViewport", "maxZ", "minZAspect"
  68484. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68485. this._ssaoPostProcess.onApply = function (effect) {
  68486. if (_this._firstUpdate) {
  68487. effect.setArray3("sampleSphere", _this._sampleSphere);
  68488. effect.setFloat("randTextureTiles", 4.0);
  68489. }
  68490. if (!_this._scene.activeCamera) {
  68491. return;
  68492. }
  68493. effect.setFloat("samplesFactor", 1 / _this.samples);
  68494. effect.setFloat("totalStrength", _this.totalStrength);
  68495. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68496. effect.setFloat("radius", _this.radius);
  68497. effect.setFloat("maxZ", _this.maxZ);
  68498. effect.setFloat("minZAspect", _this.minZAspect);
  68499. effect.setFloat("base", _this.base);
  68500. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68501. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68502. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68503. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68504. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68505. effect.setTexture("textureSampler", _this._depthTexture);
  68506. effect.setTexture("normalSampler", _this._normalTexture);
  68507. effect.setTexture("randomSampler", _this._randomTexture);
  68508. };
  68509. };
  68510. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68511. var _this = this;
  68512. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68513. this._ssaoCombinePostProcess.onApply = function (effect) {
  68514. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68515. };
  68516. };
  68517. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68518. var size = 512;
  68519. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68520. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68521. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68522. var context = this._randomTexture.getContext();
  68523. var rand = function (min, max) {
  68524. return Math.random() * (max - min) + min;
  68525. };
  68526. var randVector = BABYLON.Vector3.Zero();
  68527. for (var x = 0; x < size; x++) {
  68528. for (var y = 0; y < size; y++) {
  68529. randVector.x = rand(0.0, 1.0);
  68530. randVector.y = rand(0.0, 1.0);
  68531. randVector.z = 0.0;
  68532. randVector.normalize();
  68533. randVector.scaleInPlace(255);
  68534. randVector.x = Math.floor(randVector.x);
  68535. randVector.y = Math.floor(randVector.y);
  68536. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68537. context.fillRect(x, y, 1, 1);
  68538. }
  68539. }
  68540. this._randomTexture.update(false);
  68541. };
  68542. __decorate([
  68543. BABYLON.serialize()
  68544. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68545. __decorate([
  68546. BABYLON.serialize()
  68547. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68548. __decorate([
  68549. BABYLON.serialize()
  68550. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68551. __decorate([
  68552. BABYLON.serialize("samples")
  68553. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68554. __decorate([
  68555. BABYLON.serialize("expensiveBlur")
  68556. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68557. __decorate([
  68558. BABYLON.serialize()
  68559. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68560. __decorate([
  68561. BABYLON.serialize()
  68562. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68563. return SSAO2RenderingPipeline;
  68564. }(BABYLON.PostProcessRenderPipeline));
  68565. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68566. })(BABYLON || (BABYLON = {}));
  68567. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68568. "use strict";
  68569. // BABYLON.JS Chromatic Aberration GLSL Shader
  68570. // Author: Olivier Guyot
  68571. // Separates very slightly R, G and B colors on the edges of the screen
  68572. // Inspired by Francois Tarlier & Martins Upitis
  68573. var BABYLON;
  68574. (function (BABYLON) {
  68575. var LensRenderingPipeline = /** @class */ (function (_super) {
  68576. __extends(LensRenderingPipeline, _super);
  68577. /**
  68578. * @constructor
  68579. *
  68580. * Effect parameters are as follow:
  68581. * {
  68582. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68583. * edge_blur: number; // from 0 to x (1 for realism)
  68584. * distortion: number; // from 0 to x (1 for realism)
  68585. * grain_amount: number; // from 0 to 1
  68586. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68587. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68588. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68589. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68590. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68591. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68592. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68593. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68594. * }
  68595. * Note: if an effect parameter is unset, effect is disabled
  68596. *
  68597. * @param {string} name - The rendering pipeline name
  68598. * @param {object} parameters - An object containing all parameters (see above)
  68599. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68600. * @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)
  68601. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68602. */
  68603. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68604. if (ratio === void 0) { ratio = 1.0; }
  68605. var _this = _super.call(this, scene.getEngine(), name) || this;
  68606. // Lens effects can be of the following:
  68607. // - chromatic aberration (slight shift of RGB colors)
  68608. // - blur on the edge of the lens
  68609. // - lens distortion
  68610. // - depth-of-field blur & highlights enhancing
  68611. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68612. // - grain effect (noise or custom texture)
  68613. // Two additional texture samplers are needed:
  68614. // - depth map (for depth-of-field)
  68615. // - grain texture
  68616. /**
  68617. * The chromatic aberration PostProcess id in the pipeline
  68618. * @type {string}
  68619. */
  68620. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68621. /**
  68622. * The highlights enhancing PostProcess id in the pipeline
  68623. * @type {string}
  68624. */
  68625. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68626. /**
  68627. * The depth-of-field PostProcess id in the pipeline
  68628. * @type {string}
  68629. */
  68630. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68631. _this._scene = scene;
  68632. // Fetch texture samplers
  68633. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68634. if (parameters.grain_texture) {
  68635. _this._grainTexture = parameters.grain_texture;
  68636. }
  68637. else {
  68638. _this._createGrainTexture();
  68639. }
  68640. // save parameters
  68641. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68642. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68643. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68644. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68645. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68646. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68647. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68648. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68649. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68650. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68651. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68652. // Create effects
  68653. _this._createChromaticAberrationPostProcess(ratio);
  68654. _this._createHighlightsPostProcess(ratio);
  68655. _this._createDepthOfFieldPostProcess(ratio / 4);
  68656. // Set up pipeline
  68657. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68658. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68659. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68660. if (_this._highlightsGain === -1) {
  68661. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68662. }
  68663. // Finish
  68664. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68665. if (cameras) {
  68666. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68667. }
  68668. return _this;
  68669. }
  68670. // public methods (self explanatory)
  68671. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68672. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68673. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68674. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68675. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68676. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68677. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68678. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68679. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68680. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68681. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68682. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68683. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68684. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68685. };
  68686. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68687. this._highlightsPostProcess.updateEffect();
  68688. };
  68689. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68690. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68691. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68692. this._highlightsGain = amount;
  68693. };
  68694. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68695. if (this._highlightsGain === -1) {
  68696. this._highlightsGain = 1.0;
  68697. }
  68698. this._highlightsThreshold = amount;
  68699. };
  68700. LensRenderingPipeline.prototype.disableHighlights = function () {
  68701. this._highlightsGain = -1;
  68702. };
  68703. /**
  68704. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68705. */
  68706. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68707. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68708. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68709. this._chromaticAberrationPostProcess = null;
  68710. this._highlightsPostProcess = null;
  68711. this._depthOfFieldPostProcess = null;
  68712. this._grainTexture.dispose();
  68713. if (disableDepthRender)
  68714. this._scene.disableDepthRenderer();
  68715. };
  68716. // colors shifting and distortion
  68717. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68718. var _this = this;
  68719. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68720. [], // samplers
  68721. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68722. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68723. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68724. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68725. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68726. effect.setFloat('radialIntensity', 1);
  68727. effect.setFloat2('direction', 17, 17);
  68728. effect.setFloat2('centerPosition', 0.5, 0.5);
  68729. };
  68730. };
  68731. // highlights enhancing
  68732. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68733. var _this = this;
  68734. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68735. [], // samplers
  68736. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68737. this._highlightsPostProcess.onApply = function (effect) {
  68738. effect.setFloat('gain', _this._highlightsGain);
  68739. effect.setFloat('threshold', _this._highlightsThreshold);
  68740. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  68741. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68742. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68743. };
  68744. };
  68745. // colors shifting and distortion
  68746. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  68747. var _this = this;
  68748. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  68749. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  68750. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  68751. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68752. this._depthOfFieldPostProcess.onApply = function (effect) {
  68753. effect.setTexture("depthSampler", _this._depthTexture);
  68754. effect.setTexture("grainSampler", _this._grainTexture);
  68755. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  68756. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  68757. effect.setFloat('grain_amount', _this._grainAmount);
  68758. effect.setBool('blur_noise', _this._blurNoise);
  68759. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68760. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68761. effect.setFloat('distortion', _this._distortion);
  68762. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  68763. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  68764. effect.setFloat('aperture', _this._dofAperture);
  68765. effect.setFloat('darken', _this._dofDarken);
  68766. effect.setFloat('edge_blur', _this._edgeBlur);
  68767. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68768. if (_this._scene.activeCamera) {
  68769. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68770. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68771. }
  68772. };
  68773. };
  68774. // creates a black and white random noise texture, 512x512
  68775. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68776. var size = 512;
  68777. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68778. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68779. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68780. var context = this._grainTexture.getContext();
  68781. var rand = function (min, max) {
  68782. return Math.random() * (max - min) + min;
  68783. };
  68784. var value;
  68785. for (var x = 0; x < size; x++) {
  68786. for (var y = 0; y < size; y++) {
  68787. value = Math.floor(rand(0.42, 0.58) * 255);
  68788. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68789. context.fillRect(x, y, 1, 1);
  68790. }
  68791. }
  68792. this._grainTexture.update(false);
  68793. };
  68794. return LensRenderingPipeline;
  68795. }(BABYLON.PostProcessRenderPipeline));
  68796. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68797. })(BABYLON || (BABYLON = {}));
  68798. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68799. "use strict";
  68800. var BABYLON;
  68801. (function (BABYLON) {
  68802. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68803. __extends(StandardRenderingPipeline, _super);
  68804. /**
  68805. * @constructor
  68806. * @param {string} name - The rendering pipeline name
  68807. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68808. * @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)
  68809. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68810. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68811. */
  68812. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68813. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68814. var _this = _super.call(this, scene.getEngine(), name) || this;
  68815. _this.downSampleX4PostProcess = null;
  68816. _this.brightPassPostProcess = null;
  68817. _this.blurHPostProcesses = [];
  68818. _this.blurVPostProcesses = [];
  68819. _this.textureAdderPostProcess = null;
  68820. _this.volumetricLightPostProcess = null;
  68821. _this.volumetricLightSmoothXPostProcess = null;
  68822. _this.volumetricLightSmoothYPostProcess = null;
  68823. _this.volumetricLightMergePostProces = null;
  68824. _this.volumetricLightFinalPostProcess = null;
  68825. _this.luminancePostProcess = null;
  68826. _this.luminanceDownSamplePostProcesses = [];
  68827. _this.hdrPostProcess = null;
  68828. _this.textureAdderFinalPostProcess = null;
  68829. _this.lensFlareFinalPostProcess = null;
  68830. _this.hdrFinalPostProcess = null;
  68831. _this.lensFlarePostProcess = null;
  68832. _this.lensFlareComposePostProcess = null;
  68833. _this.motionBlurPostProcess = null;
  68834. _this.depthOfFieldPostProcess = null;
  68835. // Values
  68836. _this.brightThreshold = 1.0;
  68837. _this.blurWidth = 512.0;
  68838. _this.horizontalBlur = false;
  68839. _this.exposure = 1.0;
  68840. _this.lensTexture = null;
  68841. _this.volumetricLightCoefficient = 0.2;
  68842. _this.volumetricLightPower = 4.0;
  68843. _this.volumetricLightBlurScale = 64.0;
  68844. _this.sourceLight = null;
  68845. _this.hdrMinimumLuminance = 1.0;
  68846. _this.hdrDecreaseRate = 0.5;
  68847. _this.hdrIncreaseRate = 0.5;
  68848. _this.lensColorTexture = null;
  68849. _this.lensFlareStrength = 20.0;
  68850. _this.lensFlareGhostDispersal = 1.4;
  68851. _this.lensFlareHaloWidth = 0.7;
  68852. _this.lensFlareDistortionStrength = 16.0;
  68853. _this.lensStarTexture = null;
  68854. _this.lensFlareDirtTexture = null;
  68855. _this.depthOfFieldDistance = 10.0;
  68856. _this.depthOfFieldBlurWidth = 64.0;
  68857. _this.motionStrength = 1.0;
  68858. // IAnimatable
  68859. _this.animations = [];
  68860. _this._currentDepthOfFieldSource = null;
  68861. _this._hdrCurrentLuminance = 1.0;
  68862. // Getters and setters
  68863. _this._bloomEnabled = true;
  68864. _this._depthOfFieldEnabled = false;
  68865. _this._vlsEnabled = false;
  68866. _this._lensFlareEnabled = false;
  68867. _this._hdrEnabled = false;
  68868. _this._motionBlurEnabled = false;
  68869. _this._motionBlurSamples = 64.0;
  68870. _this._volumetricLightStepsCount = 50.0;
  68871. _this._cameras = cameras || [];
  68872. // Initialize
  68873. _this._scene = scene;
  68874. _this._basePostProcess = originalPostProcess;
  68875. _this._ratio = ratio;
  68876. // Misc
  68877. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68878. // Finish
  68879. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68880. _this._buildPipeline();
  68881. return _this;
  68882. }
  68883. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68884. get: function () {
  68885. return this._bloomEnabled;
  68886. },
  68887. set: function (enabled) {
  68888. if (this._bloomEnabled === enabled) {
  68889. return;
  68890. }
  68891. this._bloomEnabled = enabled;
  68892. this._buildPipeline();
  68893. },
  68894. enumerable: true,
  68895. configurable: true
  68896. });
  68897. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68898. get: function () {
  68899. return this._depthOfFieldEnabled;
  68900. },
  68901. set: function (enabled) {
  68902. if (this._depthOfFieldEnabled === enabled) {
  68903. return;
  68904. }
  68905. this._depthOfFieldEnabled = enabled;
  68906. this._buildPipeline();
  68907. },
  68908. enumerable: true,
  68909. configurable: true
  68910. });
  68911. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68912. get: function () {
  68913. return this._lensFlareEnabled;
  68914. },
  68915. set: function (enabled) {
  68916. if (this._lensFlareEnabled === enabled) {
  68917. return;
  68918. }
  68919. this._lensFlareEnabled = enabled;
  68920. this._buildPipeline();
  68921. },
  68922. enumerable: true,
  68923. configurable: true
  68924. });
  68925. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68926. get: function () {
  68927. return this._hdrEnabled;
  68928. },
  68929. set: function (enabled) {
  68930. if (this._hdrEnabled === enabled) {
  68931. return;
  68932. }
  68933. this._hdrEnabled = enabled;
  68934. this._buildPipeline();
  68935. },
  68936. enumerable: true,
  68937. configurable: true
  68938. });
  68939. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68940. get: function () {
  68941. return this._vlsEnabled;
  68942. },
  68943. set: function (enabled) {
  68944. if (this._vlsEnabled === enabled) {
  68945. return;
  68946. }
  68947. if (enabled) {
  68948. var geometry = this._scene.enableGeometryBufferRenderer();
  68949. if (!geometry) {
  68950. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68951. return;
  68952. }
  68953. }
  68954. this._vlsEnabled = enabled;
  68955. this._buildPipeline();
  68956. },
  68957. enumerable: true,
  68958. configurable: true
  68959. });
  68960. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68961. get: function () {
  68962. return this._motionBlurEnabled;
  68963. },
  68964. set: function (enabled) {
  68965. if (this._motionBlurEnabled === enabled) {
  68966. return;
  68967. }
  68968. this._motionBlurEnabled = enabled;
  68969. this._buildPipeline();
  68970. },
  68971. enumerable: true,
  68972. configurable: true
  68973. });
  68974. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68975. get: function () {
  68976. return this._volumetricLightStepsCount;
  68977. },
  68978. set: function (count) {
  68979. if (this.volumetricLightPostProcess) {
  68980. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68981. }
  68982. this._volumetricLightStepsCount = count;
  68983. },
  68984. enumerable: true,
  68985. configurable: true
  68986. });
  68987. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  68988. get: function () {
  68989. return this._motionBlurSamples;
  68990. },
  68991. set: function (samples) {
  68992. if (this.motionBlurPostProcess) {
  68993. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  68994. }
  68995. this._motionBlurSamples = samples;
  68996. },
  68997. enumerable: true,
  68998. configurable: true
  68999. });
  69000. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69001. var _this = this;
  69002. var ratio = this._ratio;
  69003. var scene = this._scene;
  69004. this._disposePostProcesses();
  69005. this._reset();
  69006. // Create pass post-process
  69007. if (!this._basePostProcess) {
  69008. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  69009. this.originalPostProcess.onApply = function (effect) {
  69010. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  69011. };
  69012. }
  69013. else {
  69014. this.originalPostProcess = this._basePostProcess;
  69015. }
  69016. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  69017. this._currentDepthOfFieldSource = this.originalPostProcess;
  69018. if (this._vlsEnabled) {
  69019. // Create volumetric light
  69020. this._createVolumetricLightPostProcess(scene, ratio);
  69021. // Create volumetric light final post-process
  69022. 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);
  69023. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  69024. }
  69025. if (this._bloomEnabled) {
  69026. // Create down sample X4 post-process
  69027. this._createDownSampleX4PostProcess(scene, ratio / 2);
  69028. // Create bright pass post-process
  69029. this._createBrightPassPostProcess(scene, ratio / 2);
  69030. // Create gaussian blur post-processes (down sampling blurs)
  69031. this._createBlurPostProcesses(scene, ratio / 4, 1);
  69032. // Create texture adder post-process
  69033. this._createTextureAdderPostProcess(scene, ratio);
  69034. // Create depth-of-field source post-process
  69035. 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);
  69036. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69037. }
  69038. if (this._lensFlareEnabled) {
  69039. // Create lens flare post-process
  69040. this._createLensFlarePostProcess(scene, ratio);
  69041. // Create depth-of-field source post-process post lens-flare and disable it now
  69042. 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);
  69043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69044. }
  69045. if (this._hdrEnabled) {
  69046. // Create luminance
  69047. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69048. // Create HDR
  69049. this._createHdrPostProcess(scene, ratio);
  69050. // Create depth-of-field source post-process post hdr and disable it now
  69051. 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);
  69052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69053. }
  69054. if (this._depthOfFieldEnabled) {
  69055. // Create gaussian blur used by depth-of-field
  69056. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69057. // Create depth-of-field post-process
  69058. this._createDepthOfFieldPostProcess(scene, ratio);
  69059. }
  69060. if (this._motionBlurEnabled) {
  69061. // Create motion blur post-process
  69062. this._createMotionBlurPostProcess(scene, ratio);
  69063. }
  69064. if (this._cameras !== null) {
  69065. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69066. }
  69067. };
  69068. // Down Sample X4 Post-Processs
  69069. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69070. var _this = this;
  69071. var downSampleX4Offsets = new Array(32);
  69072. 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);
  69073. this.downSampleX4PostProcess.onApply = function (effect) {
  69074. var id = 0;
  69075. var width = _this.downSampleX4PostProcess.width;
  69076. var height = _this.downSampleX4PostProcess.height;
  69077. for (var i = -2; i < 2; i++) {
  69078. for (var j = -2; j < 2; j++) {
  69079. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69080. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69081. id += 2;
  69082. }
  69083. }
  69084. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69085. };
  69086. // Add to pipeline
  69087. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69088. };
  69089. // Brightpass Post-Process
  69090. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69091. var _this = this;
  69092. var brightOffsets = new Array(8);
  69093. 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);
  69094. this.brightPassPostProcess.onApply = function (effect) {
  69095. var sU = (1.0 / _this.brightPassPostProcess.width);
  69096. var sV = (1.0 / _this.brightPassPostProcess.height);
  69097. brightOffsets[0] = -0.5 * sU;
  69098. brightOffsets[1] = 0.5 * sV;
  69099. brightOffsets[2] = 0.5 * sU;
  69100. brightOffsets[3] = 0.5 * sV;
  69101. brightOffsets[4] = -0.5 * sU;
  69102. brightOffsets[5] = -0.5 * sV;
  69103. brightOffsets[6] = 0.5 * sU;
  69104. brightOffsets[7] = -0.5 * sV;
  69105. effect.setArray2("dsOffsets", brightOffsets);
  69106. effect.setFloat("brightThreshold", _this.brightThreshold);
  69107. };
  69108. // Add to pipeline
  69109. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69110. };
  69111. // Create blur H&V post-processes
  69112. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69113. var _this = this;
  69114. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69115. var engine = scene.getEngine();
  69116. 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);
  69117. 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);
  69118. blurX.onActivateObservable.add(function () {
  69119. var dw = blurX.width / engine.getRenderWidth();
  69120. blurX.kernel = _this[blurWidthKey] * dw;
  69121. });
  69122. blurY.onActivateObservable.add(function () {
  69123. var dw = blurY.height / engine.getRenderHeight();
  69124. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69125. });
  69126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69127. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69128. this.blurHPostProcesses.push(blurX);
  69129. this.blurVPostProcesses.push(blurY);
  69130. };
  69131. // Create texture adder post-process
  69132. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69133. var _this = this;
  69134. 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);
  69135. this.textureAdderPostProcess.onApply = function (effect) {
  69136. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69137. effect.setTexture("lensSampler", _this.lensTexture);
  69138. effect.setFloat("exposure", _this.exposure);
  69139. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69140. };
  69141. // Add to pipeline
  69142. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69143. };
  69144. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69145. var _this = this;
  69146. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69147. geometryRenderer.enablePosition = true;
  69148. var geometry = geometryRenderer.getGBuffer();
  69149. // Base post-process
  69150. 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));
  69151. var depthValues = BABYLON.Vector2.Zero();
  69152. this.volumetricLightPostProcess.onApply = function (effect) {
  69153. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69154. var generator = _this.sourceLight.getShadowGenerator();
  69155. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69156. effect.setTexture("positionSampler", geometry.textures[2]);
  69157. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69158. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69159. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69160. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69161. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69162. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69163. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69164. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69165. effect.setVector2("depthValues", depthValues);
  69166. }
  69167. };
  69168. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69169. // Smooth
  69170. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69171. // Merge
  69172. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69173. this.volumetricLightMergePostProces.onApply = function (effect) {
  69174. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69175. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69176. };
  69177. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69178. };
  69179. // Create luminance
  69180. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69181. var _this = this;
  69182. // Create luminance
  69183. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69184. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69185. var offsets = [];
  69186. this.luminancePostProcess.onApply = function (effect) {
  69187. var sU = (1.0 / _this.luminancePostProcess.width);
  69188. var sV = (1.0 / _this.luminancePostProcess.height);
  69189. offsets[0] = -0.5 * sU;
  69190. offsets[1] = 0.5 * sV;
  69191. offsets[2] = 0.5 * sU;
  69192. offsets[3] = 0.5 * sV;
  69193. offsets[4] = -0.5 * sU;
  69194. offsets[5] = -0.5 * sV;
  69195. offsets[6] = 0.5 * sU;
  69196. offsets[7] = -0.5 * sV;
  69197. effect.setArray2("lumOffsets", offsets);
  69198. };
  69199. // Add to pipeline
  69200. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69201. // Create down sample luminance
  69202. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69203. var size = Math.pow(3, i);
  69204. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69205. if (i === 0) {
  69206. defines += "#define FINAL_DOWN_SAMPLER";
  69207. }
  69208. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69209. this.luminanceDownSamplePostProcesses.push(postProcess);
  69210. }
  69211. // Create callbacks and add effects
  69212. var lastLuminance = this.luminancePostProcess;
  69213. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69214. var downSampleOffsets = new Array(18);
  69215. pp.onApply = function (effect) {
  69216. if (!lastLuminance) {
  69217. return;
  69218. }
  69219. var id = 0;
  69220. for (var x = -1; x < 2; x++) {
  69221. for (var y = -1; y < 2; y++) {
  69222. downSampleOffsets[id] = x / lastLuminance.width;
  69223. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69224. id += 2;
  69225. }
  69226. }
  69227. effect.setArray2("dsOffsets", downSampleOffsets);
  69228. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69229. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69230. lastLuminance = _this.luminancePostProcess;
  69231. }
  69232. else {
  69233. lastLuminance = pp;
  69234. }
  69235. };
  69236. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69237. pp.onAfterRender = function (effect) {
  69238. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69239. 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);
  69240. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69241. };
  69242. }
  69243. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69244. });
  69245. };
  69246. // Create HDR post-process
  69247. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69248. var _this = this;
  69249. 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);
  69250. var outputLiminance = 1;
  69251. var time = 0;
  69252. var lastTime = 0;
  69253. this.hdrPostProcess.onApply = function (effect) {
  69254. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69255. time += scene.getEngine().getDeltaTime();
  69256. if (outputLiminance < 0) {
  69257. outputLiminance = _this._hdrCurrentLuminance;
  69258. }
  69259. else {
  69260. var dt = (lastTime - time) / 1000.0;
  69261. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69262. outputLiminance += _this.hdrDecreaseRate * dt;
  69263. }
  69264. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69265. outputLiminance -= _this.hdrIncreaseRate * dt;
  69266. }
  69267. else {
  69268. outputLiminance = _this._hdrCurrentLuminance;
  69269. }
  69270. }
  69271. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69272. effect.setFloat("averageLuminance", outputLiminance);
  69273. lastTime = time;
  69274. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69275. };
  69276. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69277. };
  69278. // Create lens flare post-process
  69279. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69280. var _this = this;
  69281. 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);
  69282. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69283. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69284. 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);
  69285. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69286. var resolution = new BABYLON.Vector2(0, 0);
  69287. // Lens flare
  69288. this.lensFlarePostProcess.onApply = function (effect) {
  69289. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69290. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69291. effect.setFloat("strength", _this.lensFlareStrength);
  69292. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69293. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69294. // Shift
  69295. resolution.x = _this.lensFlarePostProcess.width;
  69296. resolution.y = _this.lensFlarePostProcess.height;
  69297. effect.setVector2("resolution", resolution);
  69298. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69299. };
  69300. // Compose
  69301. 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);
  69302. 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);
  69303. this.lensFlareComposePostProcess.onApply = function (effect) {
  69304. if (!_this._scene.activeCamera) {
  69305. return;
  69306. }
  69307. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69308. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69309. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69310. // Lens start rotation matrix
  69311. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69312. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69313. 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));
  69314. camRot *= 4.0;
  69315. 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);
  69316. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69317. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69318. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69319. };
  69320. };
  69321. // Create depth-of-field post-process
  69322. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69323. var _this = this;
  69324. 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);
  69325. this.depthOfFieldPostProcess.onApply = function (effect) {
  69326. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69327. effect.setTexture("depthSampler", _this._getDepthTexture());
  69328. effect.setFloat("distance", _this.depthOfFieldDistance);
  69329. };
  69330. // Add to pipeline
  69331. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69332. };
  69333. // Create motion blur post-process
  69334. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69335. var _this = this;
  69336. 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);
  69337. var motionScale = 0;
  69338. var prevViewProjection = BABYLON.Matrix.Identity();
  69339. var invViewProjection = BABYLON.Matrix.Identity();
  69340. var viewProjection = BABYLON.Matrix.Identity();
  69341. var screenSize = BABYLON.Vector2.Zero();
  69342. this.motionBlurPostProcess.onApply = function (effect) {
  69343. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69344. viewProjection.invertToRef(invViewProjection);
  69345. effect.setMatrix("inverseViewProjection", invViewProjection);
  69346. effect.setMatrix("prevViewProjection", prevViewProjection);
  69347. prevViewProjection = viewProjection;
  69348. screenSize.x = _this.motionBlurPostProcess.width;
  69349. screenSize.y = _this.motionBlurPostProcess.height;
  69350. effect.setVector2("screenSize", screenSize);
  69351. motionScale = scene.getEngine().getFps() / 60.0;
  69352. effect.setFloat("motionScale", motionScale);
  69353. effect.setFloat("motionStrength", _this.motionStrength);
  69354. effect.setTexture("depthSampler", _this._getDepthTexture());
  69355. };
  69356. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69357. };
  69358. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69359. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69360. var renderer = this._scene.enableGeometryBufferRenderer();
  69361. return renderer.getGBuffer().textures[0];
  69362. }
  69363. return this._scene.enableDepthRenderer().getDepthMap();
  69364. };
  69365. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69366. for (var i = 0; i < this._cameras.length; i++) {
  69367. var camera = this._cameras[i];
  69368. if (this.originalPostProcess) {
  69369. this.originalPostProcess.dispose(camera);
  69370. }
  69371. if (this.downSampleX4PostProcess) {
  69372. this.downSampleX4PostProcess.dispose(camera);
  69373. }
  69374. if (this.brightPassPostProcess) {
  69375. this.brightPassPostProcess.dispose(camera);
  69376. }
  69377. if (this.textureAdderPostProcess) {
  69378. this.textureAdderPostProcess.dispose(camera);
  69379. }
  69380. if (this.textureAdderFinalPostProcess) {
  69381. this.textureAdderFinalPostProcess.dispose(camera);
  69382. }
  69383. if (this.volumetricLightPostProcess) {
  69384. this.volumetricLightPostProcess.dispose(camera);
  69385. }
  69386. if (this.volumetricLightSmoothXPostProcess) {
  69387. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69388. }
  69389. if (this.volumetricLightSmoothYPostProcess) {
  69390. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69391. }
  69392. if (this.volumetricLightMergePostProces) {
  69393. this.volumetricLightMergePostProces.dispose(camera);
  69394. }
  69395. if (this.volumetricLightFinalPostProcess) {
  69396. this.volumetricLightFinalPostProcess.dispose(camera);
  69397. }
  69398. if (this.lensFlarePostProcess) {
  69399. this.lensFlarePostProcess.dispose(camera);
  69400. }
  69401. if (this.lensFlareComposePostProcess) {
  69402. this.lensFlareComposePostProcess.dispose(camera);
  69403. }
  69404. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69405. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69406. }
  69407. if (this.luminancePostProcess) {
  69408. this.luminancePostProcess.dispose(camera);
  69409. }
  69410. if (this.hdrPostProcess) {
  69411. this.hdrPostProcess.dispose(camera);
  69412. }
  69413. if (this.hdrFinalPostProcess) {
  69414. this.hdrFinalPostProcess.dispose(camera);
  69415. }
  69416. if (this.depthOfFieldPostProcess) {
  69417. this.depthOfFieldPostProcess.dispose(camera);
  69418. }
  69419. if (this.motionBlurPostProcess) {
  69420. this.motionBlurPostProcess.dispose(camera);
  69421. }
  69422. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69423. this.blurHPostProcesses[j].dispose(camera);
  69424. }
  69425. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69426. this.blurVPostProcesses[j].dispose(camera);
  69427. }
  69428. }
  69429. this.originalPostProcess = null;
  69430. this.downSampleX4PostProcess = null;
  69431. this.brightPassPostProcess = null;
  69432. this.textureAdderPostProcess = null;
  69433. this.textureAdderFinalPostProcess = null;
  69434. this.volumetricLightPostProcess = null;
  69435. this.volumetricLightSmoothXPostProcess = null;
  69436. this.volumetricLightSmoothYPostProcess = null;
  69437. this.volumetricLightMergePostProces = null;
  69438. this.volumetricLightFinalPostProcess = null;
  69439. this.lensFlarePostProcess = null;
  69440. this.lensFlareComposePostProcess = null;
  69441. this.luminancePostProcess = null;
  69442. this.hdrPostProcess = null;
  69443. this.hdrFinalPostProcess = null;
  69444. this.depthOfFieldPostProcess = null;
  69445. this.motionBlurPostProcess = null;
  69446. this.luminanceDownSamplePostProcesses = [];
  69447. this.blurHPostProcesses = [];
  69448. this.blurVPostProcesses = [];
  69449. };
  69450. // Dispose
  69451. StandardRenderingPipeline.prototype.dispose = function () {
  69452. this._disposePostProcesses();
  69453. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69454. _super.prototype.dispose.call(this);
  69455. };
  69456. // Serialize rendering pipeline
  69457. StandardRenderingPipeline.prototype.serialize = function () {
  69458. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69459. serializationObject.customType = "StandardRenderingPipeline";
  69460. return serializationObject;
  69461. };
  69462. /**
  69463. * Static members
  69464. */
  69465. // Parse serialized pipeline
  69466. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69467. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69468. };
  69469. // Luminance steps
  69470. StandardRenderingPipeline.LuminanceSteps = 6;
  69471. __decorate([
  69472. BABYLON.serialize()
  69473. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69474. __decorate([
  69475. BABYLON.serialize()
  69476. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69477. __decorate([
  69478. BABYLON.serialize()
  69479. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69480. __decorate([
  69481. BABYLON.serialize()
  69482. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69483. __decorate([
  69484. BABYLON.serializeAsTexture("lensTexture")
  69485. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69486. __decorate([
  69487. BABYLON.serialize()
  69488. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69489. __decorate([
  69490. BABYLON.serialize()
  69491. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69492. __decorate([
  69493. BABYLON.serialize()
  69494. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69495. __decorate([
  69496. BABYLON.serialize()
  69497. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69498. __decorate([
  69499. BABYLON.serialize()
  69500. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69501. __decorate([
  69502. BABYLON.serialize()
  69503. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69504. __decorate([
  69505. BABYLON.serializeAsTexture("lensColorTexture")
  69506. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69507. __decorate([
  69508. BABYLON.serialize()
  69509. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69510. __decorate([
  69511. BABYLON.serialize()
  69512. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69513. __decorate([
  69514. BABYLON.serialize()
  69515. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69516. __decorate([
  69517. BABYLON.serialize()
  69518. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69519. __decorate([
  69520. BABYLON.serializeAsTexture("lensStarTexture")
  69521. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69522. __decorate([
  69523. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69524. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69525. __decorate([
  69526. BABYLON.serialize()
  69527. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69528. __decorate([
  69529. BABYLON.serialize()
  69530. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69531. __decorate([
  69532. BABYLON.serialize()
  69533. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69534. __decorate([
  69535. BABYLON.serialize()
  69536. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69537. __decorate([
  69538. BABYLON.serialize()
  69539. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69540. __decorate([
  69541. BABYLON.serialize()
  69542. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69543. __decorate([
  69544. BABYLON.serialize()
  69545. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69546. __decorate([
  69547. BABYLON.serialize()
  69548. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69549. __decorate([
  69550. BABYLON.serialize()
  69551. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69552. __decorate([
  69553. BABYLON.serialize()
  69554. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69555. __decorate([
  69556. BABYLON.serialize()
  69557. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69558. __decorate([
  69559. BABYLON.serialize()
  69560. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69561. return StandardRenderingPipeline;
  69562. }(BABYLON.PostProcessRenderPipeline));
  69563. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69564. })(BABYLON || (BABYLON = {}));
  69565. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69566. "use strict";
  69567. var BABYLON;
  69568. (function (BABYLON) {
  69569. var FxaaPostProcess = /** @class */ (function (_super) {
  69570. __extends(FxaaPostProcess, _super);
  69571. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69572. if (camera === void 0) { camera = null; }
  69573. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69574. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69575. _this.onApplyObservable.add(function (effect) {
  69576. var texelSize = _this.texelSize;
  69577. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69578. });
  69579. return _this;
  69580. }
  69581. return FxaaPostProcess;
  69582. }(BABYLON.PostProcess));
  69583. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69584. })(BABYLON || (BABYLON = {}));
  69585. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69586. "use strict";
  69587. var BABYLON;
  69588. (function (BABYLON) {
  69589. /**
  69590. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69591. */
  69592. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69593. __extends(ChromaticAberrationPostProcess, _super);
  69594. /**
  69595. * Creates a new instance of @see ChromaticAberrationPostProcess
  69596. * @param name The name of the effect.
  69597. * @param screenWidth The width of the screen to apply the effect on.
  69598. * @param screenHeight The height of the screen to apply the effect on.
  69599. * @param options The required width/height ratio to downsize to before computing the render pass.
  69600. * @param camera The camera to apply the render pass to.
  69601. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69602. * @param engine The engine which the post process will be applied. (default: current engine)
  69603. * @param reusable If the post process can be reused on the same frame. (default: false)
  69604. * @param textureType Type of textures used when performing the post process. (default: 0)
  69605. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69606. */
  69607. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69608. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69609. if (blockCompilation === void 0) { blockCompilation = false; }
  69610. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69611. /**
  69612. * The amount of seperation of rgb channels (default: 30)
  69613. */
  69614. _this.aberrationAmount = 30;
  69615. /**
  69616. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69617. */
  69618. _this.radialIntensity = 0;
  69619. /**
  69620. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  69621. */
  69622. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69623. /**
  69624. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  69625. */
  69626. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69627. _this.onApplyObservable.add(function (effect) {
  69628. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69629. effect.setFloat('screen_width', screenWidth);
  69630. effect.setFloat('screen_height', screenHeight);
  69631. effect.setFloat('radialIntensity', _this.radialIntensity);
  69632. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69633. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69634. });
  69635. return _this;
  69636. }
  69637. return ChromaticAberrationPostProcess;
  69638. }(BABYLON.PostProcess));
  69639. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69640. })(BABYLON || (BABYLON = {}));
  69641. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69642. "use strict";
  69643. var BABYLON;
  69644. (function (BABYLON) {
  69645. /**
  69646. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69647. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69648. */
  69649. var SharpenPostProcess = /** @class */ (function (_super) {
  69650. __extends(SharpenPostProcess, _super);
  69651. /**
  69652. * Creates a new instance of @see ConvolutionPostProcess
  69653. * @param name The name of the effect.
  69654. * @param options The required width/height ratio to downsize to before computing the render pass.
  69655. * @param camera The camera to apply the render pass to.
  69656. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69657. * @param engine The engine which the post process will be applied. (default: current engine)
  69658. * @param reusable If the post process can be reused on the same frame. (default: false)
  69659. * @param textureType Type of textures used when performing the post process. (default: 0)
  69660. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69661. */
  69662. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69663. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69664. if (blockCompilation === void 0) { blockCompilation = false; }
  69665. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69666. /**
  69667. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69668. */
  69669. _this.colorAmount = 1.0;
  69670. /**
  69671. * How much sharpness should be applied (default: 0.3)
  69672. */
  69673. _this.edgeAmount = 0.3;
  69674. _this.onApply = function (effect) {
  69675. effect.setFloat2("screenSize", _this.width, _this.height);
  69676. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69677. };
  69678. return _this;
  69679. }
  69680. return SharpenPostProcess;
  69681. }(BABYLON.PostProcess));
  69682. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69683. })(BABYLON || (BABYLON = {}));
  69684. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69685. "use strict";
  69686. var BABYLON;
  69687. (function (BABYLON) {
  69688. /**
  69689. * The Blur Post Process which blurs an image based on a kernel and direction.
  69690. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69691. */
  69692. var BlurPostProcess = /** @class */ (function (_super) {
  69693. __extends(BlurPostProcess, _super);
  69694. /**
  69695. * Creates a new instance of @see BlurPostProcess
  69696. * @param name The name of the effect.
  69697. * @param direction The direction in which to blur the image.
  69698. * @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.
  69699. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69700. * @param camera The camera to apply the render pass to.
  69701. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69702. * @param engine The engine which the post process will be applied. (default: current engine)
  69703. * @param reusable If the post process can be reused on the same frame. (default: false)
  69704. * @param textureType Type of textures used when performing the post process. (default: 0)
  69705. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69706. */
  69707. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  69708. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69709. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69710. if (defines === void 0) { defines = ""; }
  69711. if (blockCompilation === void 0) { blockCompilation = false; }
  69712. 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;
  69713. _this.direction = direction;
  69714. _this.blockCompilation = blockCompilation;
  69715. _this._packedFloat = false;
  69716. _this._staticDefines = "";
  69717. _this._staticDefines = defines;
  69718. _this.onApplyObservable.add(function (effect) {
  69719. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69720. });
  69721. _this.kernel = kernel;
  69722. return _this;
  69723. }
  69724. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69725. /**
  69726. * Gets the length in pixels of the blur sample region
  69727. */
  69728. get: function () {
  69729. return this._idealKernel;
  69730. },
  69731. /**
  69732. * Sets the length in pixels of the blur sample region
  69733. */
  69734. set: function (v) {
  69735. if (this._idealKernel === v) {
  69736. return;
  69737. }
  69738. v = Math.max(v, 1);
  69739. this._idealKernel = v;
  69740. this._kernel = this._nearestBestKernel(v);
  69741. if (!this.blockCompilation) {
  69742. this._updateParameters();
  69743. }
  69744. },
  69745. enumerable: true,
  69746. configurable: true
  69747. });
  69748. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69749. /**
  69750. * Gets wether or not the blur is unpacking/repacking floats
  69751. */
  69752. get: function () {
  69753. return this._packedFloat;
  69754. },
  69755. /**
  69756. * Sets wether or not the blur needs to unpack/repack floats
  69757. */
  69758. set: function (v) {
  69759. if (this._packedFloat === v) {
  69760. return;
  69761. }
  69762. this._packedFloat = v;
  69763. if (!this.blockCompilation) {
  69764. this._updateParameters();
  69765. }
  69766. },
  69767. enumerable: true,
  69768. configurable: true
  69769. });
  69770. /**
  69771. * Updates the effect with the current post process compile time values and recompiles the shader.
  69772. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69773. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69774. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69775. * @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
  69776. * @param onCompiled Called when the shader has been compiled.
  69777. * @param onError Called if there is an error when compiling a shader.
  69778. */
  69779. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69780. if (defines === void 0) { defines = null; }
  69781. if (uniforms === void 0) { uniforms = null; }
  69782. if (samplers === void 0) { samplers = null; }
  69783. this._updateParameters(onCompiled, onError);
  69784. };
  69785. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69786. // Generate sampling offsets and weights
  69787. var N = this._kernel;
  69788. var centerIndex = (N - 1) / 2;
  69789. // Generate Gaussian sampling weights over kernel
  69790. var offsets = [];
  69791. var weights = [];
  69792. var totalWeight = 0;
  69793. for (var i = 0; i < N; i++) {
  69794. var u = i / (N - 1);
  69795. var w = this._gaussianWeight(u * 2.0 - 1);
  69796. offsets[i] = (i - centerIndex);
  69797. weights[i] = w;
  69798. totalWeight += w;
  69799. }
  69800. // Normalize weights
  69801. for (var i = 0; i < weights.length; i++) {
  69802. weights[i] /= totalWeight;
  69803. }
  69804. // Optimize: combine samples to take advantage of hardware linear sampling
  69805. // Walk from left to center, combining pairs (symmetrically)
  69806. var linearSamplingWeights = [];
  69807. var linearSamplingOffsets = [];
  69808. var linearSamplingMap = [];
  69809. for (var i = 0; i <= centerIndex; i += 2) {
  69810. var j = Math.min(i + 1, Math.floor(centerIndex));
  69811. var singleCenterSample = i === j;
  69812. if (singleCenterSample) {
  69813. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69814. }
  69815. else {
  69816. var sharedCell = j === centerIndex;
  69817. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69818. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69819. if (offsetLinear === 0) {
  69820. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69821. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69822. }
  69823. else {
  69824. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69825. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69826. }
  69827. }
  69828. }
  69829. for (var i = 0; i < linearSamplingMap.length; i++) {
  69830. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69831. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69832. }
  69833. // Replace with optimized
  69834. offsets = linearSamplingOffsets;
  69835. weights = linearSamplingWeights;
  69836. // Generate shaders
  69837. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69838. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69839. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69840. var defines = "";
  69841. defines += this._staticDefines;
  69842. for (var i = 0; i < varyingCount; i++) {
  69843. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69844. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69845. }
  69846. var depCount = 0;
  69847. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69848. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69849. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69850. depCount++;
  69851. }
  69852. if (this.packedFloat) {
  69853. defines += "#define PACKEDFLOAT 1";
  69854. }
  69855. _super.prototype.updateEffect.call(this, defines, null, null, {
  69856. varyingCount: varyingCount,
  69857. depCount: depCount
  69858. }, onCompiled, onError);
  69859. };
  69860. /**
  69861. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69862. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69863. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69864. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69865. * The gaps between physical kernels are compensated for in the weighting of the samples
  69866. * @param idealKernel Ideal blur kernel.
  69867. * @return Nearest best kernel.
  69868. */
  69869. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69870. var v = Math.round(idealKernel);
  69871. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69872. var k = _a[_i];
  69873. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69874. return Math.max(k, 3);
  69875. }
  69876. }
  69877. return Math.max(v, 3);
  69878. };
  69879. /**
  69880. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69881. * @param x The point on the Gaussian distribution to sample.
  69882. * @return the value of the Gaussian function at x.
  69883. */
  69884. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69885. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69886. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69887. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69888. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69889. // truncated at around 1.3% of peak strength.
  69890. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69891. var sigma = (1 / 3);
  69892. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69893. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69894. var weight = (1.0 / denominator) * Math.exp(exponent);
  69895. return weight;
  69896. };
  69897. /**
  69898. * Generates a string that can be used as a floating point number in GLSL.
  69899. * @param x Value to print.
  69900. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69901. * @return GLSL float string.
  69902. */
  69903. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69904. if (decimalFigures === void 0) { decimalFigures = 8; }
  69905. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69906. };
  69907. return BlurPostProcess;
  69908. }(BABYLON.PostProcess));
  69909. BABYLON.BlurPostProcess = BlurPostProcess;
  69910. })(BABYLON || (BABYLON = {}));
  69911. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69912. "use strict";
  69913. var BABYLON;
  69914. (function (BABYLON) {
  69915. /**
  69916. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69917. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69918. * based on samples that have a large difference in distance than the center pixel.
  69919. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69920. */
  69921. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69922. __extends(DepthOfFieldBlurPostProcess, _super);
  69923. /**
  69924. * Creates a new instance of @see CircleOfConfusionPostProcess
  69925. * @param name The name of the effect.
  69926. * @param scene The scene the effect belongs to.
  69927. * @param direction The direction the blur should be applied.
  69928. * @param kernel The size of the kernel used to blur.
  69929. * @param options The required width/height ratio to downsize to before computing the render pass.
  69930. * @param camera The camera to apply the render pass to.
  69931. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69932. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69933. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69934. * @param engine The engine which the post process will be applied. (default: current engine)
  69935. * @param reusable If the post process can be reused on the same frame. (default: false)
  69936. * @param textureType Type of textures used when performing the post process. (default: 0)
  69937. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69938. */
  69939. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69940. if (imageToBlur === void 0) { imageToBlur = null; }
  69941. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69942. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69943. if (blockCompilation === void 0) { blockCompilation = false; }
  69944. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  69945. _this.direction = direction;
  69946. _this.onApplyObservable.add(function (effect) {
  69947. if (imageToBlur != null) {
  69948. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69949. }
  69950. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69951. if (scene.activeCamera) {
  69952. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69953. }
  69954. });
  69955. return _this;
  69956. }
  69957. return DepthOfFieldBlurPostProcess;
  69958. }(BABYLON.BlurPostProcess));
  69959. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69960. })(BABYLON || (BABYLON = {}));
  69961. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69962. "use strict";
  69963. var BABYLON;
  69964. (function (BABYLON) {
  69965. /**
  69966. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69967. */
  69968. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69969. __extends(DepthOfFieldMergePostProcess, _super);
  69970. /**
  69971. * Creates a new instance of @see CircleOfConfusionPostProcess
  69972. * @param name The name of the effect.
  69973. * @param original The non-blurred image to be modified
  69974. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69975. * @param blurSteps Incrimental bluring post processes.
  69976. * @param options The required width/height ratio to downsize to before computing the render pass.
  69977. * @param camera The camera to apply the render pass to.
  69978. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69979. * @param engine The engine which the post process will be applied. (default: current engine)
  69980. * @param reusable If the post process can be reused on the same frame. (default: false)
  69981. * @param textureType Type of textures used when performing the post process. (default: 0)
  69982. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69983. */
  69984. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69985. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69986. if (blockCompilation === void 0) { blockCompilation = false; }
  69987. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  69988. _this.blurSteps = blurSteps;
  69989. _this.onApplyObservable.add(function (effect) {
  69990. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69991. effect.setTextureFromPostProcess("textureSampler", original);
  69992. blurSteps.forEach(function (step, index) {
  69993. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  69994. });
  69995. });
  69996. if (!blockCompilation) {
  69997. _this.updateEffect();
  69998. }
  69999. return _this;
  70000. }
  70001. /**
  70002. * Updates the effect with the current post process compile time values and recompiles the shader.
  70003. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70004. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70005. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70006. * @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
  70007. * @param onCompiled Called when the shader has been compiled.
  70008. * @param onError Called if there is an error when compiling a shader.
  70009. */
  70010. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70011. if (defines === void 0) { defines = null; }
  70012. if (uniforms === void 0) { uniforms = null; }
  70013. if (samplers === void 0) { samplers = null; }
  70014. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  70015. };
  70016. return DepthOfFieldMergePostProcess;
  70017. }(BABYLON.PostProcess));
  70018. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  70019. })(BABYLON || (BABYLON = {}));
  70020. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  70021. "use strict";
  70022. var BABYLON;
  70023. (function (BABYLON) {
  70024. /**
  70025. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  70026. */
  70027. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  70028. __extends(CircleOfConfusionPostProcess, _super);
  70029. /**
  70030. * Creates a new instance of @see CircleOfConfusionPostProcess
  70031. * @param name The name of the effect.
  70032. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  70033. * @param options The required width/height ratio to downsize to before computing the render pass.
  70034. * @param camera The camera to apply the render pass to.
  70035. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70036. * @param engine The engine which the post process will be applied. (default: current engine)
  70037. * @param reusable If the post process can be reused on the same frame. (default: false)
  70038. * @param textureType Type of textures used when performing the post process. (default: 0)
  70039. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70040. */
  70041. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70042. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70043. if (blockCompilation === void 0) { blockCompilation = false; }
  70044. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70045. /**
  70046. * 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.
  70047. */
  70048. _this.lensSize = 50;
  70049. /**
  70050. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70051. */
  70052. _this.fStop = 1.4;
  70053. /**
  70054. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70055. */
  70056. _this.focusDistance = 2000;
  70057. /**
  70058. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70059. */
  70060. _this.focalLength = 50;
  70061. _this._depthTexture = null;
  70062. _this._depthTexture = depthTexture;
  70063. _this.onApplyObservable.add(function (effect) {
  70064. if (!_this._depthTexture) {
  70065. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70066. return;
  70067. }
  70068. effect.setTexture("depthSampler", _this._depthTexture);
  70069. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70070. var aperture = _this.lensSize / _this.fStop;
  70071. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70072. effect.setFloat('focusDistance', _this.focusDistance);
  70073. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70074. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70075. });
  70076. return _this;
  70077. }
  70078. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70079. /**
  70080. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  70081. */
  70082. set: function (value) {
  70083. this._depthTexture = value;
  70084. },
  70085. enumerable: true,
  70086. configurable: true
  70087. });
  70088. return CircleOfConfusionPostProcess;
  70089. }(BABYLON.PostProcess));
  70090. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70091. })(BABYLON || (BABYLON = {}));
  70092. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70093. "use strict";
  70094. var BABYLON;
  70095. (function (BABYLON) {
  70096. /**
  70097. * Specifies the level of max blur that should be applied when using the depth of field effect
  70098. */
  70099. var DepthOfFieldEffectBlurLevel;
  70100. (function (DepthOfFieldEffectBlurLevel) {
  70101. /**
  70102. * Subtle blur
  70103. */
  70104. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70105. /**
  70106. * Medium blur
  70107. */
  70108. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70109. /**
  70110. * Large blur
  70111. */
  70112. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70113. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70114. ;
  70115. /**
  70116. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70117. */
  70118. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70119. __extends(DepthOfFieldEffect, _super);
  70120. /**
  70121. * Creates a new instance of @see DepthOfFieldEffect
  70122. * @param scene The scene the effect belongs to.
  70123. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  70124. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70125. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70126. */
  70127. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70128. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70129. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70130. if (blockCompilation === void 0) { blockCompilation = false; }
  70131. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70132. return _this._effects;
  70133. }, true) || this;
  70134. _this._effects = [];
  70135. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70136. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70137. // 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)
  70138. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70139. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70140. _this._depthOfFieldBlurY = [];
  70141. _this._depthOfFieldBlurX = [];
  70142. var blurCount = 1;
  70143. var kernelSize = 15;
  70144. switch (blurLevel) {
  70145. case DepthOfFieldEffectBlurLevel.High: {
  70146. blurCount = 3;
  70147. kernelSize = 51;
  70148. break;
  70149. }
  70150. case DepthOfFieldEffectBlurLevel.Medium: {
  70151. blurCount = 2;
  70152. kernelSize = 31;
  70153. break;
  70154. }
  70155. default: {
  70156. kernelSize = 15;
  70157. blurCount = 1;
  70158. break;
  70159. }
  70160. }
  70161. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70162. for (var i = 0; i < blurCount; i++) {
  70163. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70164. blurY.autoClear = false;
  70165. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70166. blurX.autoClear = false;
  70167. _this._depthOfFieldBlurY.push(blurY);
  70168. _this._depthOfFieldBlurX.push(blurX);
  70169. }
  70170. // Merge blurred images with original image based on circleOfConfusion
  70171. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70172. _this._depthOfFieldMerge.autoClear = false;
  70173. // Set all post processes on the effect.
  70174. _this._effects = [_this._circleOfConfusion];
  70175. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70176. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70177. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70178. }
  70179. _this._effects.push(_this._depthOfFieldMerge);
  70180. return _this;
  70181. }
  70182. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70183. get: function () {
  70184. return this._circleOfConfusion.focalLength;
  70185. },
  70186. /**
  70187. * The focal the length of the camera used in the effect
  70188. */
  70189. set: function (value) {
  70190. this._circleOfConfusion.focalLength = value;
  70191. },
  70192. enumerable: true,
  70193. configurable: true
  70194. });
  70195. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70196. get: function () {
  70197. return this._circleOfConfusion.fStop;
  70198. },
  70199. /**
  70200. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70201. */
  70202. set: function (value) {
  70203. this._circleOfConfusion.fStop = value;
  70204. },
  70205. enumerable: true,
  70206. configurable: true
  70207. });
  70208. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70209. get: function () {
  70210. return this._circleOfConfusion.focusDistance;
  70211. },
  70212. /**
  70213. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70214. */
  70215. set: function (value) {
  70216. this._circleOfConfusion.focusDistance = value;
  70217. },
  70218. enumerable: true,
  70219. configurable: true
  70220. });
  70221. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70222. get: function () {
  70223. return this._circleOfConfusion.lensSize;
  70224. },
  70225. /**
  70226. * 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.
  70227. */
  70228. set: function (value) {
  70229. this._circleOfConfusion.lensSize = value;
  70230. },
  70231. enumerable: true,
  70232. configurable: true
  70233. });
  70234. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70235. /**
  70236. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  70237. */
  70238. set: function (value) {
  70239. this._circleOfConfusion.depthTexture = value;
  70240. },
  70241. enumerable: true,
  70242. configurable: true
  70243. });
  70244. /**
  70245. * Disposes each of the internal effects for a given camera.
  70246. * @param camera The camera to dispose the effect on.
  70247. */
  70248. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70249. this._circleOfConfusion.dispose(camera);
  70250. this._depthOfFieldBlurX.forEach(function (element) {
  70251. element.dispose(camera);
  70252. });
  70253. this._depthOfFieldBlurY.forEach(function (element) {
  70254. element.dispose(camera);
  70255. });
  70256. this._depthOfFieldMerge.dispose(camera);
  70257. };
  70258. /**
  70259. * Internal
  70260. */
  70261. DepthOfFieldEffect.prototype._updateEffects = function () {
  70262. for (var effect in this._effects) {
  70263. this._effects[effect].updateEffect();
  70264. }
  70265. };
  70266. /**
  70267. * Internal
  70268. * @returns if all the contained post processes are ready.
  70269. */
  70270. DepthOfFieldEffect.prototype._isReady = function () {
  70271. for (var effect in this._effects) {
  70272. if (!this._effects[effect].isReady()) {
  70273. return false;
  70274. }
  70275. }
  70276. return true;
  70277. };
  70278. return DepthOfFieldEffect;
  70279. }(BABYLON.PostProcessRenderEffect));
  70280. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70281. })(BABYLON || (BABYLON = {}));
  70282. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70283. "use strict";
  70284. var BABYLON;
  70285. (function (BABYLON) {
  70286. /**
  70287. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70288. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70289. */
  70290. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70291. __extends(DefaultRenderingPipeline, _super);
  70292. /**
  70293. * @constructor
  70294. * @param {string} name - The rendering pipeline name
  70295. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70296. * @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)
  70297. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70298. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70299. */
  70300. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70301. if (automaticBuild === void 0) { automaticBuild = true; }
  70302. var _this = _super.call(this, scene.getEngine(), name) || this;
  70303. _this._originalCameras = [];
  70304. /**
  70305. * ID of the sharpen post process,
  70306. */
  70307. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70308. /**
  70309. * ID of the pass post process used for bloom,
  70310. */
  70311. _this.PassPostProcessId = "PassPostProcessEffect";
  70312. /**
  70313. * ID of the highlight post process used for bloom,
  70314. */
  70315. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  70316. /**
  70317. * ID of the blurX post process used for bloom,
  70318. */
  70319. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  70320. /**
  70321. * ID of the blurY post process used for bloom,
  70322. */
  70323. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  70324. /**
  70325. * ID of the copy back post process used for bloom,
  70326. */
  70327. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  70328. /**
  70329. * ID of the image processing post process;
  70330. */
  70331. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70332. /**
  70333. * ID of the Fast Approximate Anti-Aliasing post process;
  70334. */
  70335. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70336. /**
  70337. * ID of the final merge post process;
  70338. */
  70339. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  70340. /**
  70341. * ID of the chromatic aberration post process,
  70342. */
  70343. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70344. /**
  70345. * Animations which can be used to tweak settings over a period of time
  70346. */
  70347. _this.animations = [];
  70348. // Values
  70349. _this._sharpenEnabled = false;
  70350. _this._bloomEnabled = false;
  70351. _this._depthOfFieldEnabled = false;
  70352. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70353. _this._fxaaEnabled = false;
  70354. _this._msaaEnabled = false;
  70355. _this._imageProcessingEnabled = true;
  70356. _this._bloomScale = 0.6;
  70357. _this._chromaticAberrationEnabled = false;
  70358. _this._buildAllowed = true;
  70359. /**
  70360. * Specifies the size of the bloom blur kernel, relative to the final output size
  70361. */
  70362. _this.bloomKernel = 64;
  70363. /**
  70364. * Specifies the weight of the bloom in the final rendering
  70365. */
  70366. _this._bloomWeight = 0.15;
  70367. _this._prevPostProcess = null;
  70368. _this._prevPrevPostProcess = null;
  70369. _this._cameras = cameras || [];
  70370. _this._originalCameras = _this._cameras.slice();
  70371. _this._buildAllowed = automaticBuild;
  70372. // Initialize
  70373. _this._scene = scene;
  70374. var caps = _this._scene.getEngine().getCaps();
  70375. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70376. // Misc
  70377. if (_this._hdr) {
  70378. if (caps.textureHalfFloatRender) {
  70379. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70380. }
  70381. else if (caps.textureFloatRender) {
  70382. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70383. }
  70384. }
  70385. else {
  70386. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70387. }
  70388. // Attach
  70389. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70390. var engine = _this._scene.getEngine();
  70391. // Create post processes before hand so they can be modified before enabled.
  70392. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70393. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70394. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70395. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70396. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70397. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70398. _this._buildPipeline();
  70399. return _this;
  70400. }
  70401. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70402. get: function () {
  70403. return this._sharpenEnabled;
  70404. },
  70405. /**
  70406. * Enable or disable the sharpen process from the pipeline
  70407. */
  70408. set: function (enabled) {
  70409. if (this._sharpenEnabled === enabled) {
  70410. return;
  70411. }
  70412. this._sharpenEnabled = enabled;
  70413. this._buildPipeline();
  70414. },
  70415. enumerable: true,
  70416. configurable: true
  70417. });
  70418. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70419. get: function () {
  70420. return this._bloomWeight;
  70421. },
  70422. /**
  70423. * The strength of the bloom.
  70424. */
  70425. set: function (value) {
  70426. if (this._bloomWeight === value) {
  70427. return;
  70428. }
  70429. this._bloomWeight = value;
  70430. if (this._hdr && this.copyBack) {
  70431. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  70432. }
  70433. },
  70434. enumerable: true,
  70435. configurable: true
  70436. });
  70437. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70438. get: function () {
  70439. return this._bloomScale;
  70440. },
  70441. /**
  70442. * The scale of the bloom, lower value will provide better performance.
  70443. */
  70444. set: function (value) {
  70445. if (this._bloomScale === value) {
  70446. return;
  70447. }
  70448. this._bloomScale = value;
  70449. this._buildPipeline();
  70450. },
  70451. enumerable: true,
  70452. configurable: true
  70453. });
  70454. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70455. get: function () {
  70456. return this._bloomEnabled;
  70457. },
  70458. /**
  70459. * Enable or disable the bloom from the pipeline
  70460. */
  70461. set: function (enabled) {
  70462. if (this._bloomEnabled === enabled) {
  70463. return;
  70464. }
  70465. this._bloomEnabled = enabled;
  70466. this._buildPipeline();
  70467. },
  70468. enumerable: true,
  70469. configurable: true
  70470. });
  70471. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  70472. /**
  70473. * If the depth of field is enabled.
  70474. */
  70475. get: function () {
  70476. return this._depthOfFieldEnabled;
  70477. },
  70478. set: function (enabled) {
  70479. if (this._depthOfFieldEnabled === enabled) {
  70480. return;
  70481. }
  70482. this._depthOfFieldEnabled = enabled;
  70483. this._buildPipeline();
  70484. },
  70485. enumerable: true,
  70486. configurable: true
  70487. });
  70488. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  70489. /**
  70490. * Blur level of the depth of field effect. (Higher blur will effect performance)
  70491. */
  70492. get: function () {
  70493. return this._depthOfFieldBlurLevel;
  70494. },
  70495. set: function (value) {
  70496. if (this._depthOfFieldBlurLevel === value) {
  70497. return;
  70498. }
  70499. this._depthOfFieldBlurLevel = value;
  70500. // recreate dof and dispose old as this setting is not dynamic
  70501. var oldDof = this.depthOfField;
  70502. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  70503. this.depthOfField.focalLength = oldDof.focalLength;
  70504. this.depthOfField.focusDistance = oldDof.focusDistance;
  70505. this.depthOfField.fStop = oldDof.fStop;
  70506. this.depthOfField.lensSize = oldDof.lensSize;
  70507. for (var i = 0; i < this._cameras.length; i++) {
  70508. oldDof.disposeEffects(this._cameras[i]);
  70509. }
  70510. this._buildPipeline();
  70511. },
  70512. enumerable: true,
  70513. configurable: true
  70514. });
  70515. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  70516. get: function () {
  70517. return this._fxaaEnabled;
  70518. },
  70519. /**
  70520. * If the anti aliasing is enabled.
  70521. */
  70522. set: function (enabled) {
  70523. if (this._fxaaEnabled === enabled) {
  70524. return;
  70525. }
  70526. this._fxaaEnabled = enabled;
  70527. this._buildPipeline();
  70528. },
  70529. enumerable: true,
  70530. configurable: true
  70531. });
  70532. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  70533. get: function () {
  70534. return this._msaaEnabled;
  70535. },
  70536. /**
  70537. * If the multisample anti-aliasing is enabled.
  70538. */
  70539. set: function (enabled) {
  70540. if (this._msaaEnabled === enabled) {
  70541. return;
  70542. }
  70543. this._msaaEnabled = enabled;
  70544. this._buildPipeline();
  70545. },
  70546. enumerable: true,
  70547. configurable: true
  70548. });
  70549. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  70550. get: function () {
  70551. return this._imageProcessingEnabled;
  70552. },
  70553. /**
  70554. * If image processing is enabled.
  70555. */
  70556. set: function (enabled) {
  70557. if (this._imageProcessingEnabled === enabled) {
  70558. return;
  70559. }
  70560. this._imageProcessingEnabled = enabled;
  70561. this._buildPipeline();
  70562. },
  70563. enumerable: true,
  70564. configurable: true
  70565. });
  70566. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  70567. get: function () {
  70568. return this._chromaticAberrationEnabled;
  70569. },
  70570. /**
  70571. * Enable or disable the chromaticAberration process from the pipeline
  70572. */
  70573. set: function (enabled) {
  70574. if (this._chromaticAberrationEnabled === enabled) {
  70575. return;
  70576. }
  70577. this._chromaticAberrationEnabled = enabled;
  70578. this._buildPipeline();
  70579. },
  70580. enumerable: true,
  70581. configurable: true
  70582. });
  70583. /**
  70584. * Force the compilation of the entire pipeline.
  70585. */
  70586. DefaultRenderingPipeline.prototype.prepare = function () {
  70587. var previousState = this._buildAllowed;
  70588. this._buildAllowed = true;
  70589. this._buildPipeline();
  70590. this._buildAllowed = previousState;
  70591. };
  70592. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  70593. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  70594. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  70595. postProcess.autoClear = false;
  70596. }
  70597. else {
  70598. postProcess.autoClear = true;
  70599. }
  70600. if (!skipTextureSharing) {
  70601. if (this._prevPrevPostProcess) {
  70602. postProcess.shareOutputWith(this._prevPrevPostProcess);
  70603. }
  70604. else {
  70605. postProcess.useOwnOutput();
  70606. }
  70607. if (this._prevPostProcess) {
  70608. this._prevPrevPostProcess = this._prevPostProcess;
  70609. }
  70610. this._prevPostProcess = postProcess;
  70611. }
  70612. };
  70613. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  70614. var _this = this;
  70615. if (!this._buildAllowed) {
  70616. return;
  70617. }
  70618. var engine = this._scene.getEngine();
  70619. this._disposePostProcesses();
  70620. if (this._cameras !== null) {
  70621. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70622. // get back cameras to be used to reattach pipeline
  70623. this._cameras = this._originalCameras.slice();
  70624. }
  70625. this._reset();
  70626. this._prevPostProcess = null;
  70627. this._prevPrevPostProcess = null;
  70628. if (this.sharpenEnabled) {
  70629. if (!this.sharpen.isReady()) {
  70630. this.sharpen.updateEffect();
  70631. }
  70632. this.addEffect(this._sharpenEffect);
  70633. this._setAutoClearAndTextureSharing(this.sharpen);
  70634. }
  70635. if (this.depthOfFieldEnabled) {
  70636. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  70637. this.depthOfField.depthTexture = depthTexture;
  70638. if (!this.depthOfField._isReady()) {
  70639. this.depthOfField._updateEffects();
  70640. }
  70641. this.addEffect(this.depthOfField);
  70642. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  70643. }
  70644. if (this.bloomEnabled) {
  70645. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70646. this._setAutoClearAndTextureSharing(this.pass, true);
  70647. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  70648. if (!this._hdr) {
  70649. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70650. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  70651. this.highlights.autoClear = false;
  70652. this.highlights.alwaysForcePOT = true;
  70653. }
  70654. 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);
  70655. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  70656. this.blurX.alwaysForcePOT = true;
  70657. this.blurX.autoClear = false;
  70658. this.blurX.onActivateObservable.add(function () {
  70659. var dw = _this.blurX.width / engine.getRenderWidth(true);
  70660. _this.blurX.kernel = _this.bloomKernel * dw;
  70661. });
  70662. 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);
  70663. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  70664. this.blurY.alwaysForcePOT = true;
  70665. this.blurY.autoClear = false;
  70666. this.blurY.onActivateObservable.add(function () {
  70667. var dh = _this.blurY.height / engine.getRenderHeight(true);
  70668. _this.blurY.kernel = _this.bloomKernel * dh;
  70669. });
  70670. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70671. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  70672. this.copyBack.alwaysForcePOT = true;
  70673. if (this._hdr) {
  70674. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  70675. var w = this.bloomWeight;
  70676. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  70677. }
  70678. else {
  70679. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  70680. }
  70681. this.copyBack.autoClear = false;
  70682. }
  70683. if (this._imageProcessingEnabled) {
  70684. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70685. if (this._hdr) {
  70686. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  70687. }
  70688. else {
  70689. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  70690. }
  70691. }
  70692. if (this._hdr && this.imageProcessing) {
  70693. this.finalMerge = this.imageProcessing;
  70694. }
  70695. else {
  70696. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70697. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  70698. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  70699. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  70700. }
  70701. if (this.bloomEnabled) {
  70702. if (this._hdr) {
  70703. this.copyBack.shareOutputWith(this.blurX);
  70704. if (this.imageProcessing) {
  70705. this.imageProcessing.shareOutputWith(this.pass);
  70706. this.imageProcessing.autoClear = false;
  70707. }
  70708. else {
  70709. this.finalMerge.shareOutputWith(this.pass);
  70710. }
  70711. }
  70712. else {
  70713. this.finalMerge.shareOutputWith(this.pass);
  70714. }
  70715. }
  70716. if (this.fxaaEnabled) {
  70717. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70718. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  70719. this._setAutoClearAndTextureSharing(this.fxaa);
  70720. }
  70721. if (this.chromaticAberrationEnabled) {
  70722. if (!this.chromaticAberration.isReady()) {
  70723. this.chromaticAberration.updateEffect();
  70724. }
  70725. this.addEffect(this._chromaticAberrationEffect);
  70726. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  70727. }
  70728. if (this._cameras !== null) {
  70729. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  70730. }
  70731. if (this.msaaEnabled) {
  70732. if (!this._enableMSAAOnFirstPostProcess()) {
  70733. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  70734. }
  70735. }
  70736. };
  70737. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  70738. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  70739. for (var i = 0; i < this._cameras.length; i++) {
  70740. var camera = this._cameras[i];
  70741. if (this.pass) {
  70742. this.pass.dispose(camera);
  70743. }
  70744. if (this.highlights) {
  70745. this.highlights.dispose(camera);
  70746. }
  70747. if (this.blurX) {
  70748. this.blurX.dispose(camera);
  70749. }
  70750. if (this.blurY) {
  70751. this.blurY.dispose(camera);
  70752. }
  70753. if (this.copyBack) {
  70754. this.copyBack.dispose(camera);
  70755. }
  70756. if (this.imageProcessing) {
  70757. this.imageProcessing.dispose(camera);
  70758. }
  70759. if (this.fxaa) {
  70760. this.fxaa.dispose(camera);
  70761. }
  70762. if (this.finalMerge) {
  70763. this.finalMerge.dispose(camera);
  70764. }
  70765. // These are created in the constructor and should not be disposed on every pipeline change
  70766. if (disposeNonRecreated) {
  70767. if (this.sharpen) {
  70768. this.sharpen.dispose(camera);
  70769. }
  70770. if (this.depthOfField) {
  70771. this.depthOfField.disposeEffects(camera);
  70772. }
  70773. if (this.chromaticAberration) {
  70774. this.chromaticAberration.dispose(camera);
  70775. }
  70776. }
  70777. }
  70778. this.pass = null;
  70779. this.highlights = null;
  70780. this.blurX = null;
  70781. this.blurY = null;
  70782. this.copyBack = null;
  70783. this.imageProcessing = null;
  70784. this.fxaa = null;
  70785. this.finalMerge = null;
  70786. if (disposeNonRecreated) {
  70787. this.sharpen = null;
  70788. this.depthOfField = null;
  70789. this.chromaticAberration = null;
  70790. }
  70791. };
  70792. /**
  70793. * Dispose of the pipeline and stop all post processes
  70794. */
  70795. DefaultRenderingPipeline.prototype.dispose = function () {
  70796. this._disposePostProcesses(true);
  70797. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70798. _super.prototype.dispose.call(this);
  70799. };
  70800. /**
  70801. * Serialize the rendering pipeline (Used when exporting)
  70802. * @returns the serialized object
  70803. */
  70804. DefaultRenderingPipeline.prototype.serialize = function () {
  70805. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70806. serializationObject.customType = "DefaultRenderingPipeline";
  70807. return serializationObject;
  70808. };
  70809. /**
  70810. * Parse the serialized pipeline
  70811. * @param source Source pipeline.
  70812. * @param scene The scene to load the pipeline to.
  70813. * @param rootUrl The URL of the serialized pipeline.
  70814. * @returns An instantiated pipeline from the serialized object.
  70815. */
  70816. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70817. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  70818. };
  70819. __decorate([
  70820. BABYLON.serialize()
  70821. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  70822. __decorate([
  70823. BABYLON.serialize()
  70824. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  70825. __decorate([
  70826. BABYLON.serialize()
  70827. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  70828. __decorate([
  70829. BABYLON.serialize()
  70830. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  70831. __decorate([
  70832. BABYLON.serialize()
  70833. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  70834. __decorate([
  70835. BABYLON.serialize()
  70836. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  70837. __decorate([
  70838. BABYLON.serialize()
  70839. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  70840. __decorate([
  70841. BABYLON.serialize()
  70842. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  70843. __decorate([
  70844. BABYLON.serialize()
  70845. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  70846. __decorate([
  70847. BABYLON.serialize()
  70848. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  70849. __decorate([
  70850. BABYLON.serialize()
  70851. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  70852. __decorate([
  70853. BABYLON.serialize()
  70854. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  70855. __decorate([
  70856. BABYLON.serialize()
  70857. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  70858. return DefaultRenderingPipeline;
  70859. }(BABYLON.PostProcessRenderPipeline));
  70860. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  70861. })(BABYLON || (BABYLON = {}));
  70862. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  70863. "use strict";
  70864. var BABYLON;
  70865. (function (BABYLON) {
  70866. /**
  70867. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  70868. */
  70869. var GeometryBufferRenderer = /** @class */ (function () {
  70870. /**
  70871. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  70872. * @param scene The scene the buffer belongs to
  70873. * @param ratio How big is the buffer related to the main canvas.
  70874. */
  70875. function GeometryBufferRenderer(scene, ratio) {
  70876. if (ratio === void 0) { ratio = 1; }
  70877. this._enablePosition = false;
  70878. this._scene = scene;
  70879. this._ratio = ratio;
  70880. // Render target
  70881. this._createRenderTargets();
  70882. }
  70883. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70884. /**
  70885. * Set the render list (meshes to be rendered) used in the G buffer.
  70886. */
  70887. set: function (meshes) {
  70888. this._multiRenderTarget.renderList = meshes;
  70889. },
  70890. enumerable: true,
  70891. configurable: true
  70892. });
  70893. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70894. /**
  70895. * Gets wether or not G buffer are supported by the running hardware.
  70896. * This requires draw buffer supports
  70897. */
  70898. get: function () {
  70899. return this._multiRenderTarget.isSupported;
  70900. },
  70901. enumerable: true,
  70902. configurable: true
  70903. });
  70904. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70905. /**
  70906. * Gets wether or not position are enabled for the G buffer.
  70907. */
  70908. get: function () {
  70909. return this._enablePosition;
  70910. },
  70911. /**
  70912. * Sets wether or not position are enabled for the G buffer.
  70913. */
  70914. set: function (enable) {
  70915. this._enablePosition = enable;
  70916. this.dispose();
  70917. this._createRenderTargets();
  70918. },
  70919. enumerable: true,
  70920. configurable: true
  70921. });
  70922. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70923. /**
  70924. * Gets the scene associated with the buffer.
  70925. */
  70926. get: function () {
  70927. return this._scene;
  70928. },
  70929. enumerable: true,
  70930. configurable: true
  70931. });
  70932. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70933. /**
  70934. * Gets the ratio used by the buffer during its creation.
  70935. * How big is the buffer related to the main canvas.
  70936. */
  70937. get: function () {
  70938. return this._ratio;
  70939. },
  70940. enumerable: true,
  70941. configurable: true
  70942. });
  70943. /**
  70944. * Checks wether everything is ready to render a submesh to the G buffer.
  70945. * @param subMesh the submesh to check readiness for
  70946. * @param useInstances is the mesh drawn using instance or not
  70947. * @returns true if ready otherwise false
  70948. */
  70949. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70950. var material = subMesh.getMaterial();
  70951. if (material && material.disableDepthWrite) {
  70952. return false;
  70953. }
  70954. var defines = [];
  70955. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70956. var mesh = subMesh.getMesh();
  70957. // Alpha test
  70958. if (material && material.needAlphaTesting()) {
  70959. defines.push("#define ALPHATEST");
  70960. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70961. attribs.push(BABYLON.VertexBuffer.UVKind);
  70962. defines.push("#define UV1");
  70963. }
  70964. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70965. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70966. defines.push("#define UV2");
  70967. }
  70968. }
  70969. // Buffers
  70970. if (this._enablePosition) {
  70971. defines.push("#define POSITION");
  70972. }
  70973. // Bones
  70974. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70975. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70976. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70977. if (mesh.numBoneInfluencers > 4) {
  70978. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70979. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70980. }
  70981. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70982. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70983. }
  70984. else {
  70985. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70986. }
  70987. // Instances
  70988. if (useInstances) {
  70989. defines.push("#define INSTANCES");
  70990. attribs.push("world0");
  70991. attribs.push("world1");
  70992. attribs.push("world2");
  70993. attribs.push("world3");
  70994. }
  70995. // Get correct effect
  70996. var join = defines.join("\n");
  70997. if (this._cachedDefines !== join) {
  70998. this._cachedDefines = join;
  70999. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  71000. }
  71001. return this._effect.isReady();
  71002. };
  71003. /**
  71004. * Gets the current underlying G Buffer.
  71005. * @returns the buffer
  71006. */
  71007. GeometryBufferRenderer.prototype.getGBuffer = function () {
  71008. return this._multiRenderTarget;
  71009. };
  71010. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  71011. /**
  71012. * Gets the number of samples used to render the buffer (anti aliasing).
  71013. */
  71014. get: function () {
  71015. return this._multiRenderTarget.samples;
  71016. },
  71017. /**
  71018. * Sets the number of samples used to render the buffer (anti aliasing).
  71019. */
  71020. set: function (value) {
  71021. this._multiRenderTarget.samples = value;
  71022. },
  71023. enumerable: true,
  71024. configurable: true
  71025. });
  71026. /**
  71027. * Disposes the renderer and frees up associated resources.
  71028. */
  71029. GeometryBufferRenderer.prototype.dispose = function () {
  71030. this.getGBuffer().dispose();
  71031. };
  71032. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71033. var _this = this;
  71034. var engine = this._scene.getEngine();
  71035. var count = this._enablePosition ? 3 : 2;
  71036. 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 });
  71037. if (!this.isSupported) {
  71038. return;
  71039. }
  71040. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71041. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71042. this._multiRenderTarget.refreshRate = 1;
  71043. this._multiRenderTarget.renderParticles = false;
  71044. this._multiRenderTarget.renderList = null;
  71045. // set default depth value to 1.0 (far away)
  71046. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71047. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71048. });
  71049. // Custom render function
  71050. var renderSubMesh = function (subMesh) {
  71051. var mesh = subMesh.getRenderingMesh();
  71052. var scene = _this._scene;
  71053. var engine = scene.getEngine();
  71054. var material = subMesh.getMaterial();
  71055. if (!material) {
  71056. return;
  71057. }
  71058. // Culling
  71059. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71060. // Managing instances
  71061. var batch = mesh._getInstancesRenderList(subMesh._id);
  71062. if (batch.mustReturn) {
  71063. return;
  71064. }
  71065. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71066. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71067. engine.enableEffect(_this._effect);
  71068. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71069. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71070. _this._effect.setMatrix("view", scene.getViewMatrix());
  71071. // Alpha test
  71072. if (material && material.needAlphaTesting()) {
  71073. var alphaTexture = material.getAlphaTestTexture();
  71074. if (alphaTexture) {
  71075. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71076. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71077. }
  71078. }
  71079. // Bones
  71080. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71081. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71082. }
  71083. // Draw
  71084. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71085. }
  71086. };
  71087. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71088. var index;
  71089. if (depthOnlySubMeshes.length) {
  71090. engine.setColorWrite(false);
  71091. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71092. renderSubMesh(depthOnlySubMeshes.data[index]);
  71093. }
  71094. engine.setColorWrite(true);
  71095. }
  71096. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71097. renderSubMesh(opaqueSubMeshes.data[index]);
  71098. }
  71099. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71100. renderSubMesh(alphaTestSubMeshes.data[index]);
  71101. }
  71102. };
  71103. };
  71104. return GeometryBufferRenderer;
  71105. }());
  71106. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71107. })(BABYLON || (BABYLON = {}));
  71108. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71109. "use strict";
  71110. var BABYLON;
  71111. (function (BABYLON) {
  71112. var RefractionPostProcess = /** @class */ (function (_super) {
  71113. __extends(RefractionPostProcess, _super);
  71114. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71115. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71116. _this.color = color;
  71117. _this.depth = depth;
  71118. _this.colorLevel = colorLevel;
  71119. _this._ownRefractionTexture = true;
  71120. _this.onActivateObservable.add(function (cam) {
  71121. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71122. });
  71123. _this.onApplyObservable.add(function (effect) {
  71124. effect.setColor3("baseColor", _this.color);
  71125. effect.setFloat("depth", _this.depth);
  71126. effect.setFloat("colorLevel", _this.colorLevel);
  71127. effect.setTexture("refractionSampler", _this._refTexture);
  71128. });
  71129. return _this;
  71130. }
  71131. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71132. /**
  71133. * Gets or sets the refraction texture
  71134. * Please note that you are responsible for disposing the texture if you set it manually
  71135. */
  71136. get: function () {
  71137. return this._refTexture;
  71138. },
  71139. set: function (value) {
  71140. if (this._refTexture && this._ownRefractionTexture) {
  71141. this._refTexture.dispose();
  71142. }
  71143. this._refTexture = value;
  71144. this._ownRefractionTexture = false;
  71145. },
  71146. enumerable: true,
  71147. configurable: true
  71148. });
  71149. // Methods
  71150. RefractionPostProcess.prototype.dispose = function (camera) {
  71151. if (this._refTexture && this._ownRefractionTexture) {
  71152. this._refTexture.dispose();
  71153. this._refTexture = null;
  71154. }
  71155. _super.prototype.dispose.call(this, camera);
  71156. };
  71157. return RefractionPostProcess;
  71158. }(BABYLON.PostProcess));
  71159. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71160. })(BABYLON || (BABYLON = {}));
  71161. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71162. "use strict";
  71163. var BABYLON;
  71164. (function (BABYLON) {
  71165. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71166. __extends(BlackAndWhitePostProcess, _super);
  71167. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71168. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71169. _this.degree = 1;
  71170. _this.onApplyObservable.add(function (effect) {
  71171. effect.setFloat("degree", _this.degree);
  71172. });
  71173. return _this;
  71174. }
  71175. return BlackAndWhitePostProcess;
  71176. }(BABYLON.PostProcess));
  71177. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71178. })(BABYLON || (BABYLON = {}));
  71179. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71180. "use strict";
  71181. var BABYLON;
  71182. (function (BABYLON) {
  71183. /**
  71184. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71185. * input texture to perform effects such as edge detection or sharpening
  71186. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71187. */
  71188. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71189. __extends(ConvolutionPostProcess, _super);
  71190. /**
  71191. * Creates a new instance of @see ConvolutionPostProcess
  71192. * @param name The name of the effect.
  71193. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71194. * @param options The required width/height ratio to downsize to before computing the render pass.
  71195. * @param camera The camera to apply the render pass to.
  71196. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71197. * @param engine The engine which the post process will be applied. (default: current engine)
  71198. * @param reusable If the post process can be reused on the same frame. (default: false)
  71199. * @param textureType Type of textures used when performing the post process. (default: 0)
  71200. */
  71201. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71202. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71203. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71204. _this.kernel = kernel;
  71205. _this.onApply = function (effect) {
  71206. effect.setFloat2("screenSize", _this.width, _this.height);
  71207. effect.setArray("kernel", _this.kernel);
  71208. };
  71209. return _this;
  71210. }
  71211. // Statics
  71212. /**
  71213. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71214. */
  71215. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71216. /**
  71217. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71218. */
  71219. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71220. /**
  71221. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71222. */
  71223. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71224. /**
  71225. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71226. */
  71227. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71228. /**
  71229. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71230. */
  71231. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71232. /**
  71233. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71234. */
  71235. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71236. return ConvolutionPostProcess;
  71237. }(BABYLON.PostProcess));
  71238. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71239. })(BABYLON || (BABYLON = {}));
  71240. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71241. "use strict";
  71242. var BABYLON;
  71243. (function (BABYLON) {
  71244. var FilterPostProcess = /** @class */ (function (_super) {
  71245. __extends(FilterPostProcess, _super);
  71246. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71247. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71248. _this.kernelMatrix = kernelMatrix;
  71249. _this.onApply = function (effect) {
  71250. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71251. };
  71252. return _this;
  71253. }
  71254. return FilterPostProcess;
  71255. }(BABYLON.PostProcess));
  71256. BABYLON.FilterPostProcess = FilterPostProcess;
  71257. })(BABYLON || (BABYLON = {}));
  71258. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71259. "use strict";
  71260. var BABYLON;
  71261. (function (BABYLON) {
  71262. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71263. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71264. __extends(VolumetricLightScatteringPostProcess, _super);
  71265. /**
  71266. * @constructor
  71267. * @param {string} name - The post-process name
  71268. * @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)
  71269. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71270. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71271. * @param {number} samples - The post-process quality, default 100
  71272. * @param {number} samplingMode - The post-process filtering mode
  71273. * @param {BABYLON.Engine} engine - The babylon engine
  71274. * @param {boolean} reusable - If the post-process is reusable
  71275. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71276. */
  71277. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71278. if (samples === void 0) { samples = 100; }
  71279. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71280. 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;
  71281. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71282. /**
  71283. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71284. * @type {Vector3}
  71285. */
  71286. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71287. /**
  71288. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71289. * @type {boolean}
  71290. */
  71291. _this.useCustomMeshPosition = false;
  71292. /**
  71293. * If the post-process should inverse the light scattering direction
  71294. * @type {boolean}
  71295. */
  71296. _this.invert = true;
  71297. /**
  71298. * Array containing the excluded meshes not rendered in the internal pass
  71299. */
  71300. _this.excludedMeshes = new Array();
  71301. /**
  71302. * Controls the overall intensity of the post-process
  71303. * @type {number}
  71304. */
  71305. _this.exposure = 0.3;
  71306. /**
  71307. * Dissipates each sample's contribution in range [0, 1]
  71308. * @type {number}
  71309. */
  71310. _this.decay = 0.96815;
  71311. /**
  71312. * Controls the overall intensity of each sample
  71313. * @type {number}
  71314. */
  71315. _this.weight = 0.58767;
  71316. /**
  71317. * Controls the density of each sample
  71318. * @type {number}
  71319. */
  71320. _this.density = 0.926;
  71321. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71322. engine = scene.getEngine();
  71323. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71324. // Configure mesh
  71325. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71326. // Configure
  71327. _this._createPass(scene, ratio.passRatio || ratio);
  71328. _this.onActivate = function (camera) {
  71329. if (!_this.isSupported) {
  71330. _this.dispose(camera);
  71331. }
  71332. _this.onActivate = null;
  71333. };
  71334. _this.onApplyObservable.add(function (effect) {
  71335. _this._updateMeshScreenCoordinates(scene);
  71336. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71337. effect.setFloat("exposure", _this.exposure);
  71338. effect.setFloat("decay", _this.decay);
  71339. effect.setFloat("weight", _this.weight);
  71340. effect.setFloat("density", _this.density);
  71341. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71342. });
  71343. return _this;
  71344. }
  71345. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71346. get: function () {
  71347. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71348. return false;
  71349. },
  71350. set: function (useDiffuseColor) {
  71351. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71352. },
  71353. enumerable: true,
  71354. configurable: true
  71355. });
  71356. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71357. return "VolumetricLightScatteringPostProcess";
  71358. };
  71359. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71360. var mesh = subMesh.getMesh();
  71361. // Render this.mesh as default
  71362. if (mesh === this.mesh && mesh.material) {
  71363. return mesh.material.isReady(mesh);
  71364. }
  71365. var defines = [];
  71366. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71367. var material = subMesh.getMaterial();
  71368. // Alpha test
  71369. if (material) {
  71370. if (material.needAlphaTesting()) {
  71371. defines.push("#define ALPHATEST");
  71372. }
  71373. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71374. attribs.push(BABYLON.VertexBuffer.UVKind);
  71375. defines.push("#define UV1");
  71376. }
  71377. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71378. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71379. defines.push("#define UV2");
  71380. }
  71381. }
  71382. // Bones
  71383. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71384. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71385. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71386. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71387. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71388. }
  71389. else {
  71390. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71391. }
  71392. // Instances
  71393. if (useInstances) {
  71394. defines.push("#define INSTANCES");
  71395. attribs.push("world0");
  71396. attribs.push("world1");
  71397. attribs.push("world2");
  71398. attribs.push("world3");
  71399. }
  71400. // Get correct effect
  71401. var join = defines.join("\n");
  71402. if (this._cachedDefines !== join) {
  71403. this._cachedDefines = join;
  71404. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71405. }
  71406. return this._volumetricLightScatteringPass.isReady();
  71407. };
  71408. /**
  71409. * Sets the new light position for light scattering effect
  71410. * @param {BABYLON.Vector3} The new custom light position
  71411. */
  71412. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71413. this.customMeshPosition = position;
  71414. };
  71415. /**
  71416. * Returns the light position for light scattering effect
  71417. * @return {BABYLON.Vector3} The custom light position
  71418. */
  71419. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71420. return this.customMeshPosition;
  71421. };
  71422. /**
  71423. * Disposes the internal assets and detaches the post-process from the camera
  71424. */
  71425. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71426. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71427. if (rttIndex !== -1) {
  71428. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71429. }
  71430. this._volumetricLightScatteringRTT.dispose();
  71431. _super.prototype.dispose.call(this, camera);
  71432. };
  71433. /**
  71434. * Returns the render target texture used by the post-process
  71435. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71436. */
  71437. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71438. return this._volumetricLightScatteringRTT;
  71439. };
  71440. // Private methods
  71441. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71442. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71443. return true;
  71444. }
  71445. return false;
  71446. };
  71447. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71448. var _this = this;
  71449. var engine = scene.getEngine();
  71450. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71451. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71452. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71453. this._volumetricLightScatteringRTT.renderList = null;
  71454. this._volumetricLightScatteringRTT.renderParticles = false;
  71455. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71456. var camera = this.getCamera();
  71457. if (camera) {
  71458. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71459. }
  71460. else {
  71461. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71462. }
  71463. // Custom render function for submeshes
  71464. var renderSubMesh = function (subMesh) {
  71465. var mesh = subMesh.getRenderingMesh();
  71466. if (_this._meshExcluded(mesh)) {
  71467. return;
  71468. }
  71469. var material = subMesh.getMaterial();
  71470. if (!material) {
  71471. return;
  71472. }
  71473. var scene = mesh.getScene();
  71474. var engine = scene.getEngine();
  71475. // Culling
  71476. engine.setState(material.backFaceCulling);
  71477. // Managing instances
  71478. var batch = mesh._getInstancesRenderList(subMesh._id);
  71479. if (batch.mustReturn) {
  71480. return;
  71481. }
  71482. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71483. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71484. var effect = _this._volumetricLightScatteringPass;
  71485. if (mesh === _this.mesh) {
  71486. if (subMesh.effect) {
  71487. effect = subMesh.effect;
  71488. }
  71489. else {
  71490. effect = material.getEffect();
  71491. }
  71492. }
  71493. engine.enableEffect(effect);
  71494. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  71495. if (mesh === _this.mesh) {
  71496. material.bind(mesh.getWorldMatrix(), mesh);
  71497. }
  71498. else {
  71499. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  71500. // Alpha test
  71501. if (material && material.needAlphaTesting()) {
  71502. var alphaTexture = material.getAlphaTestTexture();
  71503. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  71504. if (alphaTexture) {
  71505. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71506. }
  71507. }
  71508. // Bones
  71509. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71510. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71511. }
  71512. }
  71513. // Draw
  71514. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  71515. }
  71516. };
  71517. // Render target texture callbacks
  71518. var savedSceneClearColor;
  71519. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  71520. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  71521. savedSceneClearColor = scene.clearColor;
  71522. scene.clearColor = sceneClearColor;
  71523. });
  71524. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  71525. scene.clearColor = savedSceneClearColor;
  71526. });
  71527. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71528. var engine = scene.getEngine();
  71529. var index;
  71530. if (depthOnlySubMeshes.length) {
  71531. engine.setColorWrite(false);
  71532. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71533. renderSubMesh(depthOnlySubMeshes.data[index]);
  71534. }
  71535. engine.setColorWrite(true);
  71536. }
  71537. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71538. renderSubMesh(opaqueSubMeshes.data[index]);
  71539. }
  71540. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71541. renderSubMesh(alphaTestSubMeshes.data[index]);
  71542. }
  71543. if (transparentSubMeshes.length) {
  71544. // Sort sub meshes
  71545. for (index = 0; index < transparentSubMeshes.length; index++) {
  71546. var submesh = transparentSubMeshes.data[index];
  71547. var boundingInfo = submesh.getBoundingInfo();
  71548. if (boundingInfo && scene.activeCamera) {
  71549. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  71550. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  71551. }
  71552. }
  71553. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  71554. sortedArray.sort(function (a, b) {
  71555. // Alpha index first
  71556. if (a._alphaIndex > b._alphaIndex) {
  71557. return 1;
  71558. }
  71559. if (a._alphaIndex < b._alphaIndex) {
  71560. return -1;
  71561. }
  71562. // Then distance to camera
  71563. if (a._distanceToCamera < b._distanceToCamera) {
  71564. return 1;
  71565. }
  71566. if (a._distanceToCamera > b._distanceToCamera) {
  71567. return -1;
  71568. }
  71569. return 0;
  71570. });
  71571. // Render sub meshes
  71572. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  71573. for (index = 0; index < sortedArray.length; index++) {
  71574. renderSubMesh(sortedArray[index]);
  71575. }
  71576. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71577. }
  71578. };
  71579. };
  71580. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  71581. var transform = scene.getTransformMatrix();
  71582. var meshPosition;
  71583. if (this.useCustomMeshPosition) {
  71584. meshPosition = this.customMeshPosition;
  71585. }
  71586. else if (this.attachedNode) {
  71587. meshPosition = this.attachedNode.position;
  71588. }
  71589. else {
  71590. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  71591. }
  71592. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  71593. this._screenCoordinates.x = pos.x / this._viewPort.width;
  71594. this._screenCoordinates.y = pos.y / this._viewPort.height;
  71595. if (this.invert)
  71596. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  71597. };
  71598. // Static methods
  71599. /**
  71600. * Creates a default mesh for the Volumeric Light Scattering post-process
  71601. * @param {string} The mesh name
  71602. * @param {BABYLON.Scene} The scene where to create the mesh
  71603. * @return {BABYLON.Mesh} the default mesh
  71604. */
  71605. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  71606. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  71607. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  71608. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  71609. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  71610. mesh.material = material;
  71611. return mesh;
  71612. };
  71613. __decorate([
  71614. BABYLON.serializeAsVector3()
  71615. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  71616. __decorate([
  71617. BABYLON.serialize()
  71618. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  71619. __decorate([
  71620. BABYLON.serialize()
  71621. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  71622. __decorate([
  71623. BABYLON.serializeAsMeshReference()
  71624. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  71625. __decorate([
  71626. BABYLON.serialize()
  71627. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  71628. __decorate([
  71629. BABYLON.serialize()
  71630. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  71631. __decorate([
  71632. BABYLON.serialize()
  71633. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  71634. __decorate([
  71635. BABYLON.serialize()
  71636. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  71637. __decorate([
  71638. BABYLON.serialize()
  71639. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  71640. return VolumetricLightScatteringPostProcess;
  71641. }(BABYLON.PostProcess));
  71642. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  71643. })(BABYLON || (BABYLON = {}));
  71644. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  71645. "use strict";
  71646. //
  71647. // This post-process allows the modification of rendered colors by using
  71648. // a 'look-up table' (LUT). This effect is also called Color Grading.
  71649. //
  71650. // The object needs to be provided an url to a texture containing the color
  71651. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  71652. // Use an image editing software to tweak the LUT to match your needs.
  71653. //
  71654. // For an example of a color LUT, see here:
  71655. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  71656. // For explanations on color grading, see here:
  71657. // http://udn.epicgames.com/Three/ColorGrading.html
  71658. //
  71659. var BABYLON;
  71660. (function (BABYLON) {
  71661. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  71662. __extends(ColorCorrectionPostProcess, _super);
  71663. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  71664. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  71665. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71666. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  71667. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71668. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71669. _this.onApply = function (effect) {
  71670. effect.setTexture("colorTable", _this._colorTableTexture);
  71671. };
  71672. return _this;
  71673. }
  71674. return ColorCorrectionPostProcess;
  71675. }(BABYLON.PostProcess));
  71676. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  71677. })(BABYLON || (BABYLON = {}));
  71678. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  71679. "use strict";
  71680. var BABYLON;
  71681. (function (BABYLON) {
  71682. var TonemappingOperator;
  71683. (function (TonemappingOperator) {
  71684. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  71685. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  71686. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  71687. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  71688. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  71689. ;
  71690. var TonemapPostProcess = /** @class */ (function (_super) {
  71691. __extends(TonemapPostProcess, _super);
  71692. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  71693. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71694. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71695. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  71696. _this._operator = _operator;
  71697. _this.exposureAdjustment = exposureAdjustment;
  71698. var defines = "#define ";
  71699. if (_this._operator === TonemappingOperator.Hable)
  71700. defines += "HABLE_TONEMAPPING";
  71701. else if (_this._operator === TonemappingOperator.Reinhard)
  71702. defines += "REINHARD_TONEMAPPING";
  71703. else if (_this._operator === TonemappingOperator.HejiDawson)
  71704. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  71705. else if (_this._operator === TonemappingOperator.Photographic)
  71706. defines += "PHOTOGRAPHIC_TONEMAPPING";
  71707. //sadly a second call to create the effect.
  71708. _this.updateEffect(defines);
  71709. _this.onApply = function (effect) {
  71710. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  71711. };
  71712. return _this;
  71713. }
  71714. return TonemapPostProcess;
  71715. }(BABYLON.PostProcess));
  71716. BABYLON.TonemapPostProcess = TonemapPostProcess;
  71717. })(BABYLON || (BABYLON = {}));
  71718. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  71719. "use strict";
  71720. var BABYLON;
  71721. (function (BABYLON) {
  71722. var DisplayPassPostProcess = /** @class */ (function (_super) {
  71723. __extends(DisplayPassPostProcess, _super);
  71724. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  71725. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  71726. }
  71727. return DisplayPassPostProcess;
  71728. }(BABYLON.PostProcess));
  71729. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  71730. })(BABYLON || (BABYLON = {}));
  71731. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  71732. "use strict";
  71733. var BABYLON;
  71734. (function (BABYLON) {
  71735. var HighlightsPostProcess = /** @class */ (function (_super) {
  71736. __extends(HighlightsPostProcess, _super);
  71737. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  71738. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71739. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71740. }
  71741. return HighlightsPostProcess;
  71742. }(BABYLON.PostProcess));
  71743. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  71744. })(BABYLON || (BABYLON = {}));
  71745. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  71746. "use strict";
  71747. var BABYLON;
  71748. (function (BABYLON) {
  71749. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  71750. __extends(ImageProcessingPostProcess, _super);
  71751. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  71752. if (camera === void 0) { camera = null; }
  71753. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71754. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  71755. _this._fromLinearSpace = true;
  71756. /**
  71757. * Defines cache preventing GC.
  71758. */
  71759. _this._defines = {
  71760. IMAGEPROCESSING: false,
  71761. VIGNETTE: false,
  71762. VIGNETTEBLENDMODEMULTIPLY: false,
  71763. VIGNETTEBLENDMODEOPAQUE: false,
  71764. TONEMAPPING: false,
  71765. CONTRAST: false,
  71766. COLORCURVES: false,
  71767. COLORGRADING: false,
  71768. COLORGRADING3D: false,
  71769. FROMLINEARSPACE: false,
  71770. SAMPLER3DGREENDEPTH: false,
  71771. SAMPLER3DBGRMAP: false,
  71772. IMAGEPROCESSINGPOSTPROCESS: false,
  71773. EXPOSURE: false,
  71774. GRAIN: false,
  71775. };
  71776. // Setup the configuration as forced by the constructor. This would then not force the
  71777. // scene materials output in linear space and let untouched the default forward pass.
  71778. if (imageProcessingConfiguration) {
  71779. imageProcessingConfiguration.applyByPostProcess = true;
  71780. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  71781. // This will cause the shader to be compiled
  71782. _this.fromLinearSpace = false;
  71783. }
  71784. else {
  71785. _this._attachImageProcessingConfiguration(null, true);
  71786. _this.imageProcessingConfiguration.applyByPostProcess = true;
  71787. }
  71788. _this.onApply = function (effect) {
  71789. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  71790. };
  71791. return _this;
  71792. }
  71793. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  71794. /**
  71795. * Gets the image processing configuration used either in this material.
  71796. */
  71797. get: function () {
  71798. return this._imageProcessingConfiguration;
  71799. },
  71800. /**
  71801. * Sets the Default image processing configuration used either in the this material.
  71802. *
  71803. * If sets to null, the scene one is in use.
  71804. */
  71805. set: function (value) {
  71806. this._attachImageProcessingConfiguration(value);
  71807. },
  71808. enumerable: true,
  71809. configurable: true
  71810. });
  71811. /**
  71812. * Attaches a new image processing configuration to the PBR Material.
  71813. * @param configuration
  71814. */
  71815. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  71816. var _this = this;
  71817. if (doNotBuild === void 0) { doNotBuild = false; }
  71818. if (configuration === this._imageProcessingConfiguration) {
  71819. return;
  71820. }
  71821. // Detaches observer.
  71822. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71823. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71824. }
  71825. // Pick the scene configuration if needed.
  71826. if (!configuration) {
  71827. var scene = null;
  71828. var engine = this.getEngine();
  71829. var camera = this.getCamera();
  71830. if (camera) {
  71831. scene = camera.getScene();
  71832. }
  71833. else if (engine && engine.scenes) {
  71834. var scenes = engine.scenes;
  71835. scene = scenes[scenes.length - 1];
  71836. }
  71837. else {
  71838. scene = BABYLON.Engine.LastCreatedScene;
  71839. }
  71840. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  71841. }
  71842. else {
  71843. this._imageProcessingConfiguration = configuration;
  71844. }
  71845. // Attaches observer.
  71846. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  71847. _this._updateParameters();
  71848. });
  71849. // Ensure the effect will be rebuilt.
  71850. if (!doNotBuild) {
  71851. this._updateParameters();
  71852. }
  71853. };
  71854. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  71855. /**
  71856. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71857. */
  71858. get: function () {
  71859. return this.imageProcessingConfiguration.colorCurves;
  71860. },
  71861. /**
  71862. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71863. */
  71864. set: function (value) {
  71865. this.imageProcessingConfiguration.colorCurves = value;
  71866. },
  71867. enumerable: true,
  71868. configurable: true
  71869. });
  71870. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  71871. /**
  71872. * Gets wether the color curves effect is enabled.
  71873. */
  71874. get: function () {
  71875. return this.imageProcessingConfiguration.colorCurvesEnabled;
  71876. },
  71877. /**
  71878. * Sets wether the color curves effect is enabled.
  71879. */
  71880. set: function (value) {
  71881. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  71882. },
  71883. enumerable: true,
  71884. configurable: true
  71885. });
  71886. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  71887. /**
  71888. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71889. */
  71890. get: function () {
  71891. return this.imageProcessingConfiguration.colorGradingTexture;
  71892. },
  71893. /**
  71894. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71895. */
  71896. set: function (value) {
  71897. this.imageProcessingConfiguration.colorGradingTexture = value;
  71898. },
  71899. enumerable: true,
  71900. configurable: true
  71901. });
  71902. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71903. /**
  71904. * Gets wether the color grading effect is enabled.
  71905. */
  71906. get: function () {
  71907. return this.imageProcessingConfiguration.colorGradingEnabled;
  71908. },
  71909. /**
  71910. * Gets wether the color grading effect is enabled.
  71911. */
  71912. set: function (value) {
  71913. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71914. },
  71915. enumerable: true,
  71916. configurable: true
  71917. });
  71918. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71919. /**
  71920. * Gets exposure used in the effect.
  71921. */
  71922. get: function () {
  71923. return this.imageProcessingConfiguration.exposure;
  71924. },
  71925. /**
  71926. * Sets exposure used in the effect.
  71927. */
  71928. set: function (value) {
  71929. this.imageProcessingConfiguration.exposure = value;
  71930. },
  71931. enumerable: true,
  71932. configurable: true
  71933. });
  71934. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71935. /**
  71936. * Gets wether tonemapping is enabled or not.
  71937. */
  71938. get: function () {
  71939. return this._imageProcessingConfiguration.toneMappingEnabled;
  71940. },
  71941. /**
  71942. * Sets wether tonemapping is enabled or not
  71943. */
  71944. set: function (value) {
  71945. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71946. },
  71947. enumerable: true,
  71948. configurable: true
  71949. });
  71950. ;
  71951. ;
  71952. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71953. /**
  71954. * Gets contrast used in the effect.
  71955. */
  71956. get: function () {
  71957. return this.imageProcessingConfiguration.contrast;
  71958. },
  71959. /**
  71960. * Sets contrast used in the effect.
  71961. */
  71962. set: function (value) {
  71963. this.imageProcessingConfiguration.contrast = value;
  71964. },
  71965. enumerable: true,
  71966. configurable: true
  71967. });
  71968. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71969. /**
  71970. * Gets Vignette stretch size.
  71971. */
  71972. get: function () {
  71973. return this.imageProcessingConfiguration.vignetteStretch;
  71974. },
  71975. /**
  71976. * Sets Vignette stretch size.
  71977. */
  71978. set: function (value) {
  71979. this.imageProcessingConfiguration.vignetteStretch = value;
  71980. },
  71981. enumerable: true,
  71982. configurable: true
  71983. });
  71984. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71985. /**
  71986. * Gets Vignette centre X Offset.
  71987. */
  71988. get: function () {
  71989. return this.imageProcessingConfiguration.vignetteCentreX;
  71990. },
  71991. /**
  71992. * Sets Vignette centre X Offset.
  71993. */
  71994. set: function (value) {
  71995. this.imageProcessingConfiguration.vignetteCentreX = value;
  71996. },
  71997. enumerable: true,
  71998. configurable: true
  71999. });
  72000. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  72001. /**
  72002. * Gets Vignette centre Y Offset.
  72003. */
  72004. get: function () {
  72005. return this.imageProcessingConfiguration.vignetteCentreY;
  72006. },
  72007. /**
  72008. * Sets Vignette centre Y Offset.
  72009. */
  72010. set: function (value) {
  72011. this.imageProcessingConfiguration.vignetteCentreY = value;
  72012. },
  72013. enumerable: true,
  72014. configurable: true
  72015. });
  72016. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  72017. /**
  72018. * Gets Vignette weight or intensity of the vignette effect.
  72019. */
  72020. get: function () {
  72021. return this.imageProcessingConfiguration.vignetteWeight;
  72022. },
  72023. /**
  72024. * Sets Vignette weight or intensity of the vignette effect.
  72025. */
  72026. set: function (value) {
  72027. this.imageProcessingConfiguration.vignetteWeight = value;
  72028. },
  72029. enumerable: true,
  72030. configurable: true
  72031. });
  72032. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72033. /**
  72034. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72035. * if vignetteEnabled is set to true.
  72036. */
  72037. get: function () {
  72038. return this.imageProcessingConfiguration.vignetteColor;
  72039. },
  72040. /**
  72041. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72042. * if vignetteEnabled is set to true.
  72043. */
  72044. set: function (value) {
  72045. this.imageProcessingConfiguration.vignetteColor = value;
  72046. },
  72047. enumerable: true,
  72048. configurable: true
  72049. });
  72050. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72051. /**
  72052. * Gets Camera field of view used by the Vignette effect.
  72053. */
  72054. get: function () {
  72055. return this.imageProcessingConfiguration.vignetteCameraFov;
  72056. },
  72057. /**
  72058. * Sets Camera field of view used by the Vignette effect.
  72059. */
  72060. set: function (value) {
  72061. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72062. },
  72063. enumerable: true,
  72064. configurable: true
  72065. });
  72066. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72067. /**
  72068. * Gets the vignette blend mode allowing different kind of effect.
  72069. */
  72070. get: function () {
  72071. return this.imageProcessingConfiguration.vignetteBlendMode;
  72072. },
  72073. /**
  72074. * Sets the vignette blend mode allowing different kind of effect.
  72075. */
  72076. set: function (value) {
  72077. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72078. },
  72079. enumerable: true,
  72080. configurable: true
  72081. });
  72082. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72083. /**
  72084. * Gets wether the vignette effect is enabled.
  72085. */
  72086. get: function () {
  72087. return this.imageProcessingConfiguration.vignetteEnabled;
  72088. },
  72089. /**
  72090. * Sets wether the vignette effect is enabled.
  72091. */
  72092. set: function (value) {
  72093. this.imageProcessingConfiguration.vignetteEnabled = value;
  72094. },
  72095. enumerable: true,
  72096. configurable: true
  72097. });
  72098. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  72099. /**
  72100. * Gets wether the grain effect is enabled.
  72101. */
  72102. get: function () {
  72103. return this.imageProcessingConfiguration.grainEnabled;
  72104. },
  72105. /**
  72106. * Sets wether the grain effect is enabled.
  72107. */
  72108. set: function (value) {
  72109. this.imageProcessingConfiguration.grainEnabled = value;
  72110. },
  72111. enumerable: true,
  72112. configurable: true
  72113. });
  72114. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  72115. /**
  72116. * Gets the grain effect's intensity.
  72117. */
  72118. get: function () {
  72119. return this.imageProcessingConfiguration.grainIntensity;
  72120. },
  72121. /**
  72122. * Sets the grain effect's intensity.
  72123. */
  72124. set: function (value) {
  72125. this.imageProcessingConfiguration.grainIntensity = value;
  72126. },
  72127. enumerable: true,
  72128. configurable: true
  72129. });
  72130. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  72131. /**
  72132. * Gets wether the grain effect is animated.
  72133. */
  72134. get: function () {
  72135. return this.imageProcessingConfiguration.grainAnimated;
  72136. },
  72137. /**
  72138. * Sets wether the grain effect is animated.
  72139. */
  72140. set: function (value) {
  72141. this.imageProcessingConfiguration.grainAnimated = value;
  72142. },
  72143. enumerable: true,
  72144. configurable: true
  72145. });
  72146. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72147. /**
  72148. * Gets wether the input of the processing is in Gamma or Linear Space.
  72149. */
  72150. get: function () {
  72151. return this._fromLinearSpace;
  72152. },
  72153. /**
  72154. * Sets wether the input of the processing is in Gamma or Linear Space.
  72155. */
  72156. set: function (value) {
  72157. if (this._fromLinearSpace === value) {
  72158. return;
  72159. }
  72160. this._fromLinearSpace = value;
  72161. this._updateParameters();
  72162. },
  72163. enumerable: true,
  72164. configurable: true
  72165. });
  72166. ImageProcessingPostProcess.prototype.getClassName = function () {
  72167. return "ImageProcessingPostProcess";
  72168. };
  72169. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72170. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72171. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72172. var defines = "";
  72173. for (var define in this._defines) {
  72174. if (this._defines[define]) {
  72175. defines += "#define " + define + ";\r\n";
  72176. }
  72177. }
  72178. var samplers = ["textureSampler"];
  72179. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72180. var uniforms = ["scale"];
  72181. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72182. this.updateEffect(defines, uniforms, samplers);
  72183. };
  72184. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72185. _super.prototype.dispose.call(this, camera);
  72186. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72187. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72188. }
  72189. this.imageProcessingConfiguration.applyByPostProcess = false;
  72190. };
  72191. __decorate([
  72192. BABYLON.serialize()
  72193. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72194. return ImageProcessingPostProcess;
  72195. }(BABYLON.PostProcess));
  72196. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72197. })(BABYLON || (BABYLON = {}));
  72198. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72199. "use strict";
  72200. var BABYLON;
  72201. (function (BABYLON) {
  72202. var Bone = /** @class */ (function (_super) {
  72203. __extends(Bone, _super);
  72204. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72205. if (parentBone === void 0) { parentBone = null; }
  72206. if (localMatrix === void 0) { localMatrix = null; }
  72207. if (restPose === void 0) { restPose = null; }
  72208. if (baseMatrix === void 0) { baseMatrix = null; }
  72209. if (index === void 0) { index = null; }
  72210. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72211. _this.name = name;
  72212. _this.children = new Array();
  72213. _this.animations = new Array();
  72214. // Set this value to map this bone to a different index in the transform matrices.
  72215. // Set this value to -1 to exclude the bone from the transform matrices.
  72216. _this._index = null;
  72217. _this._worldTransform = new BABYLON.Matrix();
  72218. _this._absoluteTransform = new BABYLON.Matrix();
  72219. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72220. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72221. _this._scaleVector = BABYLON.Vector3.One();
  72222. _this._negateScaleChildren = BABYLON.Vector3.One();
  72223. _this._scalingDeterminant = 1;
  72224. _this._skeleton = skeleton;
  72225. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72226. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72227. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72228. _this._index = index;
  72229. skeleton.bones.push(_this);
  72230. _this.setParent(parentBone, false);
  72231. _this._updateDifferenceMatrix();
  72232. return _this;
  72233. }
  72234. Object.defineProperty(Bone.prototype, "_matrix", {
  72235. get: function () {
  72236. return this._localMatrix;
  72237. },
  72238. set: function (val) {
  72239. if (this._localMatrix) {
  72240. this._localMatrix.copyFrom(val);
  72241. }
  72242. else {
  72243. this._localMatrix = val;
  72244. }
  72245. },
  72246. enumerable: true,
  72247. configurable: true
  72248. });
  72249. // Members
  72250. Bone.prototype.getSkeleton = function () {
  72251. return this._skeleton;
  72252. };
  72253. Bone.prototype.getParent = function () {
  72254. return this._parent;
  72255. };
  72256. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72257. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72258. if (this._parent === parent) {
  72259. return;
  72260. }
  72261. if (this._parent) {
  72262. var index = this._parent.children.indexOf(this);
  72263. if (index !== -1) {
  72264. this._parent.children.splice(index, 1);
  72265. }
  72266. }
  72267. this._parent = parent;
  72268. if (this._parent) {
  72269. this._parent.children.push(this);
  72270. }
  72271. if (updateDifferenceMatrix) {
  72272. this._updateDifferenceMatrix();
  72273. }
  72274. };
  72275. Bone.prototype.getLocalMatrix = function () {
  72276. return this._localMatrix;
  72277. };
  72278. Bone.prototype.getBaseMatrix = function () {
  72279. return this._baseMatrix;
  72280. };
  72281. Bone.prototype.getRestPose = function () {
  72282. return this._restPose;
  72283. };
  72284. Bone.prototype.returnToRest = function () {
  72285. this.updateMatrix(this._restPose.clone());
  72286. };
  72287. Bone.prototype.getWorldMatrix = function () {
  72288. return this._worldTransform;
  72289. };
  72290. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72291. return this._invertedAbsoluteTransform;
  72292. };
  72293. Bone.prototype.getAbsoluteTransform = function () {
  72294. return this._absoluteTransform;
  72295. };
  72296. Object.defineProperty(Bone.prototype, "position", {
  72297. // Properties (matches AbstractMesh properties)
  72298. get: function () {
  72299. return this.getPosition();
  72300. },
  72301. set: function (newPosition) {
  72302. this.setPosition(newPosition);
  72303. },
  72304. enumerable: true,
  72305. configurable: true
  72306. });
  72307. Object.defineProperty(Bone.prototype, "rotation", {
  72308. get: function () {
  72309. return this.getRotation();
  72310. },
  72311. set: function (newRotation) {
  72312. this.setRotation(newRotation);
  72313. },
  72314. enumerable: true,
  72315. configurable: true
  72316. });
  72317. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72318. get: function () {
  72319. return this.getRotationQuaternion();
  72320. },
  72321. set: function (newRotation) {
  72322. this.setRotationQuaternion(newRotation);
  72323. },
  72324. enumerable: true,
  72325. configurable: true
  72326. });
  72327. Object.defineProperty(Bone.prototype, "scaling", {
  72328. get: function () {
  72329. return this.getScale();
  72330. },
  72331. set: function (newScaling) {
  72332. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72333. },
  72334. enumerable: true,
  72335. configurable: true
  72336. });
  72337. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72338. /**
  72339. * Gets the animation properties override
  72340. */
  72341. get: function () {
  72342. return this._skeleton.animationPropertiesOverride;
  72343. },
  72344. enumerable: true,
  72345. configurable: true
  72346. });
  72347. // Methods
  72348. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72349. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72350. this._baseMatrix = matrix.clone();
  72351. this._localMatrix = matrix.clone();
  72352. this._skeleton._markAsDirty();
  72353. if (updateDifferenceMatrix) {
  72354. this._updateDifferenceMatrix();
  72355. }
  72356. };
  72357. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72358. if (!rootMatrix) {
  72359. rootMatrix = this._baseMatrix;
  72360. }
  72361. if (this._parent) {
  72362. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72363. }
  72364. else {
  72365. this._absoluteTransform.copyFrom(rootMatrix);
  72366. }
  72367. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72368. for (var index = 0; index < this.children.length; index++) {
  72369. this.children[index]._updateDifferenceMatrix();
  72370. }
  72371. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72372. };
  72373. Bone.prototype.markAsDirty = function () {
  72374. this._currentRenderId++;
  72375. this._skeleton._markAsDirty();
  72376. };
  72377. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72378. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72379. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72380. // all animation may be coming from a library skeleton, so may need to create animation
  72381. if (this.animations.length === 0) {
  72382. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72383. this.animations[0].setKeys([]);
  72384. }
  72385. // get animation info / verify there is such a range from the source bone
  72386. var sourceRange = source.animations[0].getRange(rangeName);
  72387. if (!sourceRange) {
  72388. return false;
  72389. }
  72390. var from = sourceRange.from;
  72391. var to = sourceRange.to;
  72392. var sourceKeys = source.animations[0].getKeys();
  72393. // rescaling prep
  72394. var sourceBoneLength = source.length;
  72395. var sourceParent = source.getParent();
  72396. var parent = this.getParent();
  72397. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72398. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72399. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72400. var destKeys = this.animations[0].getKeys();
  72401. // loop vars declaration
  72402. var orig;
  72403. var origTranslation;
  72404. var mat;
  72405. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72406. orig = sourceKeys[key];
  72407. if (orig.frame >= from && orig.frame <= to) {
  72408. if (rescaleAsRequired) {
  72409. mat = orig.value.clone();
  72410. // scale based on parent ratio, when bone has parent
  72411. if (parentScalingReqd) {
  72412. origTranslation = mat.getTranslation();
  72413. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72414. // scale based on skeleton dimension ratio when root bone, and value is passed
  72415. }
  72416. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72417. origTranslation = mat.getTranslation();
  72418. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72419. // use original when root bone, and no data for skelDimensionsRatio
  72420. }
  72421. else {
  72422. mat = orig.value;
  72423. }
  72424. }
  72425. else {
  72426. mat = orig.value;
  72427. }
  72428. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72429. }
  72430. }
  72431. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72432. return true;
  72433. };
  72434. /**
  72435. * Translate the bone in local or world space.
  72436. * @param vec The amount to translate the bone.
  72437. * @param space The space that the translation is in.
  72438. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72439. */
  72440. Bone.prototype.translate = function (vec, space, mesh) {
  72441. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72442. var lm = this.getLocalMatrix();
  72443. if (space == BABYLON.Space.LOCAL) {
  72444. lm.m[12] += vec.x;
  72445. lm.m[13] += vec.y;
  72446. lm.m[14] += vec.z;
  72447. }
  72448. else {
  72449. var wm = null;
  72450. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72451. if (mesh) {
  72452. wm = mesh.getWorldMatrix();
  72453. }
  72454. this._skeleton.computeAbsoluteTransforms();
  72455. var tmat = Bone._tmpMats[0];
  72456. var tvec = Bone._tmpVecs[0];
  72457. if (this._parent) {
  72458. if (mesh && wm) {
  72459. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72460. tmat.multiplyToRef(wm, tmat);
  72461. }
  72462. else {
  72463. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72464. }
  72465. }
  72466. tmat.m[12] = 0;
  72467. tmat.m[13] = 0;
  72468. tmat.m[14] = 0;
  72469. tmat.invert();
  72470. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72471. lm.m[12] += tvec.x;
  72472. lm.m[13] += tvec.y;
  72473. lm.m[14] += tvec.z;
  72474. }
  72475. this.markAsDirty();
  72476. };
  72477. /**
  72478. * Set the postion of the bone in local or world space.
  72479. * @param position The position to set the bone.
  72480. * @param space The space that the position is in.
  72481. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72482. */
  72483. Bone.prototype.setPosition = function (position, space, mesh) {
  72484. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72485. var lm = this.getLocalMatrix();
  72486. if (space == BABYLON.Space.LOCAL) {
  72487. lm.m[12] = position.x;
  72488. lm.m[13] = position.y;
  72489. lm.m[14] = position.z;
  72490. }
  72491. else {
  72492. var wm = null;
  72493. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72494. if (mesh) {
  72495. wm = mesh.getWorldMatrix();
  72496. }
  72497. this._skeleton.computeAbsoluteTransforms();
  72498. var tmat = Bone._tmpMats[0];
  72499. var vec = Bone._tmpVecs[0];
  72500. if (this._parent) {
  72501. if (mesh && wm) {
  72502. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72503. tmat.multiplyToRef(wm, tmat);
  72504. }
  72505. else {
  72506. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72507. }
  72508. }
  72509. tmat.invert();
  72510. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72511. lm.m[12] = vec.x;
  72512. lm.m[13] = vec.y;
  72513. lm.m[14] = vec.z;
  72514. }
  72515. this.markAsDirty();
  72516. };
  72517. /**
  72518. * Set the absolute postion of the bone (world space).
  72519. * @param position The position to set the bone.
  72520. * @param mesh The mesh that this bone is attached to.
  72521. */
  72522. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72523. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72524. };
  72525. /**
  72526. * Set the scale of the bone on the x, y and z axes.
  72527. * @param x The scale of the bone on the x axis.
  72528. * @param x The scale of the bone on the y axis.
  72529. * @param z The scale of the bone on the z axis.
  72530. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72531. */
  72532. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72533. if (scaleChildren === void 0) { scaleChildren = false; }
  72534. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72535. if (!scaleChildren) {
  72536. this._negateScaleChildren.x = 1 / x;
  72537. this._negateScaleChildren.y = 1 / y;
  72538. this._negateScaleChildren.z = 1 / z;
  72539. }
  72540. this._syncScaleVector();
  72541. }
  72542. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  72543. };
  72544. /**
  72545. * Scale the bone on the x, y and z axes.
  72546. * @param x The amount to scale the bone on the x axis.
  72547. * @param x The amount to scale the bone on the y axis.
  72548. * @param z The amount to scale the bone on the z axis.
  72549. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72550. */
  72551. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  72552. if (scaleChildren === void 0) { scaleChildren = false; }
  72553. var locMat = this.getLocalMatrix();
  72554. var origLocMat = Bone._tmpMats[0];
  72555. origLocMat.copyFrom(locMat);
  72556. var origLocMatInv = Bone._tmpMats[1];
  72557. origLocMatInv.copyFrom(origLocMat);
  72558. origLocMatInv.invert();
  72559. var scaleMat = Bone._tmpMats[2];
  72560. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  72561. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  72562. this._scaleVector.x *= x;
  72563. this._scaleVector.y *= y;
  72564. this._scaleVector.z *= z;
  72565. locMat.multiplyToRef(origLocMatInv, locMat);
  72566. locMat.multiplyToRef(scaleMat, locMat);
  72567. locMat.multiplyToRef(origLocMat, locMat);
  72568. var parent = this.getParent();
  72569. if (parent) {
  72570. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  72571. }
  72572. else {
  72573. this.getAbsoluteTransform().copyFrom(locMat);
  72574. }
  72575. var len = this.children.length;
  72576. scaleMat.invert();
  72577. for (var i = 0; i < len; i++) {
  72578. var child = this.children[i];
  72579. var cm = child.getLocalMatrix();
  72580. cm.multiplyToRef(scaleMat, cm);
  72581. var lm = child.getLocalMatrix();
  72582. lm.m[12] *= x;
  72583. lm.m[13] *= y;
  72584. lm.m[14] *= z;
  72585. }
  72586. this.computeAbsoluteTransforms();
  72587. if (scaleChildren) {
  72588. for (var i = 0; i < len; i++) {
  72589. this.children[i].scale(x, y, z, scaleChildren);
  72590. }
  72591. }
  72592. this.markAsDirty();
  72593. };
  72594. /**
  72595. * Set the yaw, pitch, and roll of the bone in local or world space.
  72596. * @param yaw The rotation of the bone on the y axis.
  72597. * @param pitch The rotation of the bone on the x axis.
  72598. * @param roll The rotation of the bone on the z axis.
  72599. * @param space The space that the axes of rotation are in.
  72600. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72601. */
  72602. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  72603. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72604. var rotMat = Bone._tmpMats[0];
  72605. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72606. var rotMatInv = Bone._tmpMats[1];
  72607. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72608. rotMatInv.multiplyToRef(rotMat, rotMat);
  72609. this._rotateWithMatrix(rotMat, space, mesh);
  72610. };
  72611. /**
  72612. * Rotate the bone on an axis in local or world space.
  72613. * @param axis The axis to rotate the bone on.
  72614. * @param amount The amount to rotate the bone.
  72615. * @param space The space that the axis is in.
  72616. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72617. */
  72618. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72619. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72620. var rmat = Bone._tmpMats[0];
  72621. rmat.m[12] = 0;
  72622. rmat.m[13] = 0;
  72623. rmat.m[14] = 0;
  72624. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72625. this._rotateWithMatrix(rmat, space, mesh);
  72626. };
  72627. /**
  72628. * Set the rotation of the bone to a particular axis angle in local or world space.
  72629. * @param axis The axis to rotate the bone on.
  72630. * @param angle The angle that the bone should be rotated to.
  72631. * @param space The space that the axis is in.
  72632. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72633. */
  72634. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  72635. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72636. var rotMat = Bone._tmpMats[0];
  72637. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  72638. var rotMatInv = Bone._tmpMats[1];
  72639. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72640. rotMatInv.multiplyToRef(rotMat, rotMat);
  72641. this._rotateWithMatrix(rotMat, space, mesh);
  72642. };
  72643. /**
  72644. * Set the euler rotation of the bone in local of world space.
  72645. * @param rotation The euler rotation that the bone should be set to.
  72646. * @param space The space that the rotation is in.
  72647. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72648. */
  72649. Bone.prototype.setRotation = function (rotation, space, mesh) {
  72650. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72651. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  72652. };
  72653. /**
  72654. * Set the quaternion rotation of the bone in local of world space.
  72655. * @param quat The quaternion rotation that the bone should be set to.
  72656. * @param space The space that the rotation is in.
  72657. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72658. */
  72659. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  72660. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72661. var rotMatInv = Bone._tmpMats[0];
  72662. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72663. var rotMat = Bone._tmpMats[1];
  72664. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  72665. rotMatInv.multiplyToRef(rotMat, rotMat);
  72666. this._rotateWithMatrix(rotMat, space, mesh);
  72667. };
  72668. /**
  72669. * Set the rotation matrix of the bone in local of world space.
  72670. * @param rotMat The rotation matrix that the bone should be set to.
  72671. * @param space The space that the rotation is in.
  72672. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72673. */
  72674. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  72675. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72676. var rotMatInv = Bone._tmpMats[0];
  72677. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72678. var rotMat2 = Bone._tmpMats[1];
  72679. rotMat2.copyFrom(rotMat);
  72680. rotMatInv.multiplyToRef(rotMat, rotMat2);
  72681. this._rotateWithMatrix(rotMat2, space, mesh);
  72682. };
  72683. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  72684. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72685. var lmat = this.getLocalMatrix();
  72686. var lx = lmat.m[12];
  72687. var ly = lmat.m[13];
  72688. var lz = lmat.m[14];
  72689. var parent = this.getParent();
  72690. var parentScale = Bone._tmpMats[3];
  72691. var parentScaleInv = Bone._tmpMats[4];
  72692. if (parent) {
  72693. if (space == BABYLON.Space.WORLD) {
  72694. if (mesh) {
  72695. parentScale.copyFrom(mesh.getWorldMatrix());
  72696. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  72697. }
  72698. else {
  72699. parentScale.copyFrom(parent.getAbsoluteTransform());
  72700. }
  72701. }
  72702. else {
  72703. parentScale = parent._scaleMatrix;
  72704. }
  72705. parentScaleInv.copyFrom(parentScale);
  72706. parentScaleInv.invert();
  72707. lmat.multiplyToRef(parentScale, lmat);
  72708. lmat.multiplyToRef(rmat, lmat);
  72709. lmat.multiplyToRef(parentScaleInv, lmat);
  72710. }
  72711. else {
  72712. if (space == BABYLON.Space.WORLD && mesh) {
  72713. parentScale.copyFrom(mesh.getWorldMatrix());
  72714. parentScaleInv.copyFrom(parentScale);
  72715. parentScaleInv.invert();
  72716. lmat.multiplyToRef(parentScale, lmat);
  72717. lmat.multiplyToRef(rmat, lmat);
  72718. lmat.multiplyToRef(parentScaleInv, lmat);
  72719. }
  72720. else {
  72721. lmat.multiplyToRef(rmat, lmat);
  72722. }
  72723. }
  72724. lmat.m[12] = lx;
  72725. lmat.m[13] = ly;
  72726. lmat.m[14] = lz;
  72727. this.computeAbsoluteTransforms();
  72728. this.markAsDirty();
  72729. };
  72730. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  72731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72732. if (space == BABYLON.Space.WORLD) {
  72733. var scaleMatrix = Bone._tmpMats[2];
  72734. scaleMatrix.copyFrom(this._scaleMatrix);
  72735. rotMatInv.copyFrom(this.getAbsoluteTransform());
  72736. if (mesh) {
  72737. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  72738. var meshScale = Bone._tmpMats[3];
  72739. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  72740. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  72741. }
  72742. rotMatInv.invert();
  72743. scaleMatrix.m[0] *= this._scalingDeterminant;
  72744. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72745. }
  72746. else {
  72747. rotMatInv.copyFrom(this.getLocalMatrix());
  72748. rotMatInv.invert();
  72749. var scaleMatrix = Bone._tmpMats[2];
  72750. scaleMatrix.copyFrom(this._scaleMatrix);
  72751. if (this._parent) {
  72752. var pscaleMatrix = Bone._tmpMats[3];
  72753. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  72754. pscaleMatrix.invert();
  72755. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  72756. }
  72757. else {
  72758. scaleMatrix.m[0] *= this._scalingDeterminant;
  72759. }
  72760. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72761. }
  72762. };
  72763. /**
  72764. * Get the scale of the bone
  72765. * @returns the scale of the bone
  72766. */
  72767. Bone.prototype.getScale = function () {
  72768. return this._scaleVector.clone();
  72769. };
  72770. /**
  72771. * Copy the scale of the bone to a vector3.
  72772. * @param result The vector3 to copy the scale to
  72773. */
  72774. Bone.prototype.getScaleToRef = function (result) {
  72775. result.copyFrom(this._scaleVector);
  72776. };
  72777. /**
  72778. * Get the position of the bone in local or world space.
  72779. * @param space The space that the returned position is in.
  72780. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72781. * @returns The position of the bone
  72782. */
  72783. Bone.prototype.getPosition = function (space, mesh) {
  72784. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72785. if (mesh === void 0) { mesh = null; }
  72786. var pos = BABYLON.Vector3.Zero();
  72787. this.getPositionToRef(space, mesh, pos);
  72788. return pos;
  72789. };
  72790. /**
  72791. * Copy the position of the bone to a vector3 in local or world space.
  72792. * @param space The space that the returned position is in.
  72793. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72794. * @param result The vector3 to copy the position to.
  72795. */
  72796. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  72797. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72798. if (space == BABYLON.Space.LOCAL) {
  72799. var lm = this.getLocalMatrix();
  72800. result.x = lm.m[12];
  72801. result.y = lm.m[13];
  72802. result.z = lm.m[14];
  72803. }
  72804. else {
  72805. var wm = null;
  72806. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72807. if (mesh) {
  72808. wm = mesh.getWorldMatrix();
  72809. }
  72810. this._skeleton.computeAbsoluteTransforms();
  72811. var tmat = Bone._tmpMats[0];
  72812. if (mesh && wm) {
  72813. tmat.copyFrom(this.getAbsoluteTransform());
  72814. tmat.multiplyToRef(wm, tmat);
  72815. }
  72816. else {
  72817. tmat = this.getAbsoluteTransform();
  72818. }
  72819. result.x = tmat.m[12];
  72820. result.y = tmat.m[13];
  72821. result.z = tmat.m[14];
  72822. }
  72823. };
  72824. /**
  72825. * Get the absolute position of the bone (world space).
  72826. * @param mesh The mesh that this bone is attached to.
  72827. * @returns The absolute position of the bone
  72828. */
  72829. Bone.prototype.getAbsolutePosition = function (mesh) {
  72830. if (mesh === void 0) { mesh = null; }
  72831. var pos = BABYLON.Vector3.Zero();
  72832. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  72833. return pos;
  72834. };
  72835. /**
  72836. * Copy the absolute position of the bone (world space) to the result param.
  72837. * @param mesh The mesh that this bone is attached to.
  72838. * @param result The vector3 to copy the absolute position to.
  72839. */
  72840. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  72841. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  72842. };
  72843. /**
  72844. * Compute the absolute transforms of this bone and its children.
  72845. */
  72846. Bone.prototype.computeAbsoluteTransforms = function () {
  72847. if (this._parent) {
  72848. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72849. }
  72850. else {
  72851. this._absoluteTransform.copyFrom(this._localMatrix);
  72852. var poseMatrix = this._skeleton.getPoseMatrix();
  72853. if (poseMatrix) {
  72854. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  72855. }
  72856. }
  72857. var children = this.children;
  72858. var len = children.length;
  72859. for (var i = 0; i < len; i++) {
  72860. children[i].computeAbsoluteTransforms();
  72861. }
  72862. };
  72863. Bone.prototype._syncScaleVector = function () {
  72864. var lm = this.getLocalMatrix();
  72865. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  72866. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  72867. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  72868. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  72869. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  72870. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  72871. this._scaleVector.x = xs * Math.sqrt(xsq);
  72872. this._scaleVector.y = ys * Math.sqrt(ysq);
  72873. this._scaleVector.z = zs * Math.sqrt(zsq);
  72874. if (this._parent) {
  72875. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  72876. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  72877. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  72878. }
  72879. 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);
  72880. };
  72881. /**
  72882. * Get the world direction from an axis that is in the local space of the bone.
  72883. * @param localAxis The local direction that is used to compute the world direction.
  72884. * @param mesh The mesh that this bone is attached to.
  72885. * @returns The world direction
  72886. */
  72887. Bone.prototype.getDirection = function (localAxis, mesh) {
  72888. if (mesh === void 0) { mesh = null; }
  72889. var result = BABYLON.Vector3.Zero();
  72890. this.getDirectionToRef(localAxis, mesh, result);
  72891. return result;
  72892. };
  72893. /**
  72894. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72895. * @param localAxis The local direction that is used to compute the world direction.
  72896. * @param mesh The mesh that this bone is attached to.
  72897. * @param result The vector3 that the world direction will be copied to.
  72898. */
  72899. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72900. if (mesh === void 0) { mesh = null; }
  72901. var wm = null;
  72902. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72903. if (mesh) {
  72904. wm = mesh.getWorldMatrix();
  72905. }
  72906. this._skeleton.computeAbsoluteTransforms();
  72907. var mat = Bone._tmpMats[0];
  72908. mat.copyFrom(this.getAbsoluteTransform());
  72909. if (mesh && wm) {
  72910. mat.multiplyToRef(wm, mat);
  72911. }
  72912. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72913. result.normalize();
  72914. };
  72915. /**
  72916. * Get the euler rotation of the bone in local or world space.
  72917. * @param space The space that the rotation should be in.
  72918. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72919. * @returns The euler rotation
  72920. */
  72921. Bone.prototype.getRotation = function (space, mesh) {
  72922. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72923. if (mesh === void 0) { mesh = null; }
  72924. var result = BABYLON.Vector3.Zero();
  72925. this.getRotationToRef(space, mesh, result);
  72926. return result;
  72927. };
  72928. /**
  72929. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72930. * @param space The space that the rotation should be in.
  72931. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72932. * @param result The vector3 that the rotation should be copied to.
  72933. */
  72934. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72935. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72936. if (mesh === void 0) { mesh = null; }
  72937. var quat = Bone._tmpQuat;
  72938. this.getRotationQuaternionToRef(space, mesh, quat);
  72939. quat.toEulerAnglesToRef(result);
  72940. };
  72941. /**
  72942. * Get the quaternion rotation of the bone in either local or world space.
  72943. * @param space The space that the rotation should be in.
  72944. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72945. * @returns The quaternion rotation
  72946. */
  72947. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72948. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72949. if (mesh === void 0) { mesh = null; }
  72950. var result = BABYLON.Quaternion.Identity();
  72951. this.getRotationQuaternionToRef(space, mesh, result);
  72952. return result;
  72953. };
  72954. /**
  72955. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72956. * @param space The space that the rotation should be in.
  72957. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72958. * @param result The quaternion that the rotation should be copied to.
  72959. */
  72960. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72961. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72962. if (mesh === void 0) { mesh = null; }
  72963. if (space == BABYLON.Space.LOCAL) {
  72964. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72965. }
  72966. else {
  72967. var mat = Bone._tmpMats[0];
  72968. var amat = this.getAbsoluteTransform();
  72969. if (mesh) {
  72970. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72971. }
  72972. else {
  72973. mat.copyFrom(amat);
  72974. }
  72975. mat.m[0] *= this._scalingDeterminant;
  72976. mat.m[1] *= this._scalingDeterminant;
  72977. mat.m[2] *= this._scalingDeterminant;
  72978. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72979. }
  72980. };
  72981. /**
  72982. * Get the rotation matrix of the bone in local or world space.
  72983. * @param space The space that the rotation should be in.
  72984. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72985. * @returns The rotation matrix
  72986. */
  72987. Bone.prototype.getRotationMatrix = function (space, mesh) {
  72988. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72989. var result = BABYLON.Matrix.Identity();
  72990. this.getRotationMatrixToRef(space, mesh, result);
  72991. return result;
  72992. };
  72993. /**
  72994. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  72995. * @param space The space that the rotation should be in.
  72996. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72997. * @param result The quaternion that the rotation should be copied to.
  72998. */
  72999. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  73000. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73001. if (space == BABYLON.Space.LOCAL) {
  73002. this.getLocalMatrix().getRotationMatrixToRef(result);
  73003. }
  73004. else {
  73005. var mat = Bone._tmpMats[0];
  73006. var amat = this.getAbsoluteTransform();
  73007. if (mesh) {
  73008. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73009. }
  73010. else {
  73011. mat.copyFrom(amat);
  73012. }
  73013. mat.m[0] *= this._scalingDeterminant;
  73014. mat.m[1] *= this._scalingDeterminant;
  73015. mat.m[2] *= this._scalingDeterminant;
  73016. mat.getRotationMatrixToRef(result);
  73017. }
  73018. };
  73019. /**
  73020. * Get the world position of a point that is in the local space of the bone.
  73021. * @param position The local position
  73022. * @param mesh The mesh that this bone is attached to.
  73023. * @returns The world position
  73024. */
  73025. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  73026. if (mesh === void 0) { mesh = null; }
  73027. var result = BABYLON.Vector3.Zero();
  73028. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  73029. return result;
  73030. };
  73031. /**
  73032. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73033. * @param position The local position
  73034. * @param mesh The mesh that this bone is attached to.
  73035. * @param result The vector3 that the world position should be copied to.
  73036. */
  73037. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73038. if (mesh === void 0) { mesh = null; }
  73039. var wm = null;
  73040. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73041. if (mesh) {
  73042. wm = mesh.getWorldMatrix();
  73043. }
  73044. this._skeleton.computeAbsoluteTransforms();
  73045. var tmat = Bone._tmpMats[0];
  73046. if (mesh && wm) {
  73047. tmat.copyFrom(this.getAbsoluteTransform());
  73048. tmat.multiplyToRef(wm, tmat);
  73049. }
  73050. else {
  73051. tmat = this.getAbsoluteTransform();
  73052. }
  73053. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73054. };
  73055. /**
  73056. * Get the local position of a point that is in world space.
  73057. * @param position The world position
  73058. * @param mesh The mesh that this bone is attached to.
  73059. * @returns The local position
  73060. */
  73061. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73062. if (mesh === void 0) { mesh = null; }
  73063. var result = BABYLON.Vector3.Zero();
  73064. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73065. return result;
  73066. };
  73067. /**
  73068. * Get the local position of a point that is in world space and copy it to the result param.
  73069. * @param position The world position
  73070. * @param mesh The mesh that this bone is attached to.
  73071. * @param result The vector3 that the local position should be copied to.
  73072. */
  73073. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73074. if (mesh === void 0) { mesh = null; }
  73075. var wm = null;
  73076. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73077. if (mesh) {
  73078. wm = mesh.getWorldMatrix();
  73079. }
  73080. this._skeleton.computeAbsoluteTransforms();
  73081. var tmat = Bone._tmpMats[0];
  73082. tmat.copyFrom(this.getAbsoluteTransform());
  73083. if (mesh && wm) {
  73084. tmat.multiplyToRef(wm, tmat);
  73085. }
  73086. tmat.invert();
  73087. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73088. };
  73089. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73090. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73091. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73092. return Bone;
  73093. }(BABYLON.Node));
  73094. BABYLON.Bone = Bone;
  73095. })(BABYLON || (BABYLON = {}));
  73096. //# sourceMappingURL=babylon.bone.js.map
  73097. "use strict";
  73098. var BABYLON;
  73099. (function (BABYLON) {
  73100. var BoneIKController = /** @class */ (function () {
  73101. function BoneIKController(mesh, bone, options) {
  73102. this.targetPosition = BABYLON.Vector3.Zero();
  73103. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73104. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73105. this.poleAngle = 0;
  73106. this.slerpAmount = 1;
  73107. this._bone1Quat = BABYLON.Quaternion.Identity();
  73108. this._bone1Mat = BABYLON.Matrix.Identity();
  73109. this._bone2Ang = Math.PI;
  73110. this._maxAngle = Math.PI;
  73111. this._rightHandedSystem = false;
  73112. this._bendAxis = BABYLON.Vector3.Right();
  73113. this._slerping = false;
  73114. this._adjustRoll = 0;
  73115. this._bone2 = bone;
  73116. this._bone1 = bone.getParent();
  73117. if (!this._bone1) {
  73118. return;
  73119. }
  73120. this.mesh = mesh;
  73121. var bonePos = bone.getPosition();
  73122. if (bone.getAbsoluteTransform().determinant() > 0) {
  73123. this._rightHandedSystem = true;
  73124. this._bendAxis.x = 0;
  73125. this._bendAxis.y = 0;
  73126. this._bendAxis.z = -1;
  73127. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73128. this._adjustRoll = Math.PI * .5;
  73129. this._bendAxis.z = 1;
  73130. }
  73131. }
  73132. if (this._bone1.length) {
  73133. var boneScale1 = this._bone1.getScale();
  73134. var boneScale2 = this._bone2.getScale();
  73135. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73136. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73137. }
  73138. else if (this._bone1.children[0]) {
  73139. mesh.computeWorldMatrix(true);
  73140. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73141. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73142. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73143. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73144. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73145. }
  73146. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73147. this.maxAngle = Math.PI;
  73148. if (options) {
  73149. if (options.targetMesh) {
  73150. this.targetMesh = options.targetMesh;
  73151. this.targetMesh.computeWorldMatrix(true);
  73152. }
  73153. if (options.poleTargetMesh) {
  73154. this.poleTargetMesh = options.poleTargetMesh;
  73155. this.poleTargetMesh.computeWorldMatrix(true);
  73156. }
  73157. else if (options.poleTargetBone) {
  73158. this.poleTargetBone = options.poleTargetBone;
  73159. }
  73160. else if (this._bone1.getParent()) {
  73161. this.poleTargetBone = this._bone1.getParent();
  73162. }
  73163. if (options.poleTargetLocalOffset) {
  73164. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73165. }
  73166. if (options.poleAngle) {
  73167. this.poleAngle = options.poleAngle;
  73168. }
  73169. if (options.bendAxis) {
  73170. this._bendAxis.copyFrom(options.bendAxis);
  73171. }
  73172. if (options.maxAngle) {
  73173. this.maxAngle = options.maxAngle;
  73174. }
  73175. if (options.slerpAmount) {
  73176. this.slerpAmount = options.slerpAmount;
  73177. }
  73178. }
  73179. }
  73180. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73181. get: function () {
  73182. return this._maxAngle;
  73183. },
  73184. set: function (value) {
  73185. this._setMaxAngle(value);
  73186. },
  73187. enumerable: true,
  73188. configurable: true
  73189. });
  73190. BoneIKController.prototype._setMaxAngle = function (ang) {
  73191. if (ang < 0) {
  73192. ang = 0;
  73193. }
  73194. if (ang > Math.PI || ang == undefined) {
  73195. ang = Math.PI;
  73196. }
  73197. this._maxAngle = ang;
  73198. var a = this._bone1Length;
  73199. var b = this._bone2Length;
  73200. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73201. };
  73202. BoneIKController.prototype.update = function () {
  73203. var bone1 = this._bone1;
  73204. if (!bone1) {
  73205. return;
  73206. }
  73207. var target = this.targetPosition;
  73208. var poleTarget = this.poleTargetPosition;
  73209. var mat1 = BoneIKController._tmpMats[0];
  73210. var mat2 = BoneIKController._tmpMats[1];
  73211. if (this.targetMesh) {
  73212. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73213. }
  73214. if (this.poleTargetBone) {
  73215. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73216. }
  73217. else if (this.poleTargetMesh) {
  73218. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73219. }
  73220. var bonePos = BoneIKController._tmpVecs[0];
  73221. var zaxis = BoneIKController._tmpVecs[1];
  73222. var xaxis = BoneIKController._tmpVecs[2];
  73223. var yaxis = BoneIKController._tmpVecs[3];
  73224. var upAxis = BoneIKController._tmpVecs[4];
  73225. var _tmpQuat = BoneIKController._tmpQuat;
  73226. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73227. poleTarget.subtractToRef(bonePos, upAxis);
  73228. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73229. upAxis.y = 1;
  73230. }
  73231. else {
  73232. upAxis.normalize();
  73233. }
  73234. target.subtractToRef(bonePos, yaxis);
  73235. yaxis.normalize();
  73236. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73237. zaxis.normalize();
  73238. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73239. xaxis.normalize();
  73240. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73241. var a = this._bone1Length;
  73242. var b = this._bone2Length;
  73243. var c = BABYLON.Vector3.Distance(bonePos, target);
  73244. if (this._maxReach > 0) {
  73245. c = Math.min(this._maxReach, c);
  73246. }
  73247. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73248. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73249. if (acosa > 1) {
  73250. acosa = 1;
  73251. }
  73252. if (acosb > 1) {
  73253. acosb = 1;
  73254. }
  73255. if (acosa < -1) {
  73256. acosa = -1;
  73257. }
  73258. if (acosb < -1) {
  73259. acosb = -1;
  73260. }
  73261. var angA = Math.acos(acosa);
  73262. var angB = Math.acos(acosb);
  73263. var angC = -angA - angB;
  73264. if (this._rightHandedSystem) {
  73265. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73266. mat2.multiplyToRef(mat1, mat1);
  73267. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73268. mat2.multiplyToRef(mat1, mat1);
  73269. }
  73270. else {
  73271. var _tmpVec = BoneIKController._tmpVecs[5];
  73272. _tmpVec.copyFrom(this._bendAxis);
  73273. _tmpVec.x *= -1;
  73274. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73275. mat2.multiplyToRef(mat1, mat1);
  73276. }
  73277. if (this.poleAngle) {
  73278. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73279. mat1.multiplyToRef(mat2, mat1);
  73280. }
  73281. if (this._bone1) {
  73282. if (this.slerpAmount < 1) {
  73283. if (!this._slerping) {
  73284. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73285. }
  73286. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73287. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73288. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73289. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73290. this._slerping = true;
  73291. }
  73292. else {
  73293. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73294. this._bone1Mat.copyFrom(mat1);
  73295. this._slerping = false;
  73296. }
  73297. }
  73298. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73299. this._bone2Ang = angC;
  73300. };
  73301. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73302. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73303. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73304. return BoneIKController;
  73305. }());
  73306. BABYLON.BoneIKController = BoneIKController;
  73307. })(BABYLON || (BABYLON = {}));
  73308. //# sourceMappingURL=babylon.boneIKController.js.map
  73309. "use strict";
  73310. var BABYLON;
  73311. (function (BABYLON) {
  73312. var BoneLookController = /** @class */ (function () {
  73313. /**
  73314. * Create a BoneLookController
  73315. * @param mesh the mesh that the bone belongs to
  73316. * @param bone the bone that will be looking to the target
  73317. * @param target the target Vector3 to look at
  73318. * @param settings optional settings:
  73319. * - maxYaw: the maximum angle the bone will yaw to
  73320. * - minYaw: the minimum angle the bone will yaw to
  73321. * - maxPitch: the maximum angle the bone will pitch to
  73322. * - minPitch: the minimum angle the bone will yaw to
  73323. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73324. * - upAxis: the up axis of the coordinate system
  73325. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73326. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73327. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73328. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73329. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73330. * - adjustRoll: used to make an adjustment to the roll of the bone
  73331. **/
  73332. function BoneLookController(mesh, bone, target, options) {
  73333. /**
  73334. * The up axis of the coordinate system that is used when the bone is rotated.
  73335. */
  73336. this.upAxis = BABYLON.Vector3.Up();
  73337. /**
  73338. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73339. */
  73340. this.upAxisSpace = BABYLON.Space.LOCAL;
  73341. /**
  73342. * Used to make an adjustment to the yaw of the bone.
  73343. */
  73344. this.adjustYaw = 0;
  73345. /**
  73346. * Used to make an adjustment to the pitch of the bone.
  73347. */
  73348. this.adjustPitch = 0;
  73349. /**
  73350. * Used to make an adjustment to the roll of the bone.
  73351. */
  73352. this.adjustRoll = 0;
  73353. /**
  73354. * 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).
  73355. */
  73356. this.slerpAmount = 1;
  73357. this._boneQuat = BABYLON.Quaternion.Identity();
  73358. this._slerping = false;
  73359. this._firstFrameSkipped = false;
  73360. this._fowardAxis = BABYLON.Vector3.Forward();
  73361. this.mesh = mesh;
  73362. this.bone = bone;
  73363. this.target = target;
  73364. if (options) {
  73365. if (options.adjustYaw) {
  73366. this.adjustYaw = options.adjustYaw;
  73367. }
  73368. if (options.adjustPitch) {
  73369. this.adjustPitch = options.adjustPitch;
  73370. }
  73371. if (options.adjustRoll) {
  73372. this.adjustRoll = options.adjustRoll;
  73373. }
  73374. if (options.maxYaw != null) {
  73375. this.maxYaw = options.maxYaw;
  73376. }
  73377. else {
  73378. this.maxYaw = Math.PI;
  73379. }
  73380. if (options.minYaw != null) {
  73381. this.minYaw = options.minYaw;
  73382. }
  73383. else {
  73384. this.minYaw = -Math.PI;
  73385. }
  73386. if (options.maxPitch != null) {
  73387. this.maxPitch = options.maxPitch;
  73388. }
  73389. else {
  73390. this.maxPitch = Math.PI;
  73391. }
  73392. if (options.minPitch != null) {
  73393. this.minPitch = options.minPitch;
  73394. }
  73395. else {
  73396. this.minPitch = -Math.PI;
  73397. }
  73398. if (options.slerpAmount != null) {
  73399. this.slerpAmount = options.slerpAmount;
  73400. }
  73401. if (options.upAxis != null) {
  73402. this.upAxis = options.upAxis;
  73403. }
  73404. if (options.upAxisSpace != null) {
  73405. this.upAxisSpace = options.upAxisSpace;
  73406. }
  73407. if (options.yawAxis != null || options.pitchAxis != null) {
  73408. var newYawAxis = BABYLON.Axis.Y;
  73409. var newPitchAxis = BABYLON.Axis.X;
  73410. if (options.yawAxis != null) {
  73411. newYawAxis = options.yawAxis.clone();
  73412. newYawAxis.normalize();
  73413. }
  73414. if (options.pitchAxis != null) {
  73415. newPitchAxis = options.pitchAxis.clone();
  73416. newPitchAxis.normalize();
  73417. }
  73418. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73419. this._transformYawPitch = BABYLON.Matrix.Identity();
  73420. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73421. this._transformYawPitchInv = this._transformYawPitch.clone();
  73422. this._transformYawPitch.invert();
  73423. }
  73424. }
  73425. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73426. this.upAxisSpace = BABYLON.Space.LOCAL;
  73427. }
  73428. }
  73429. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73430. /**
  73431. * Get/set the minimum yaw angle that the bone can look to.
  73432. */
  73433. get: function () {
  73434. return this._minYaw;
  73435. },
  73436. set: function (value) {
  73437. this._minYaw = value;
  73438. this._minYawSin = Math.sin(value);
  73439. this._minYawCos = Math.cos(value);
  73440. if (this._maxYaw != null) {
  73441. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73442. this._yawRange = this._maxYaw - this._minYaw;
  73443. }
  73444. },
  73445. enumerable: true,
  73446. configurable: true
  73447. });
  73448. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73449. /**
  73450. * Get/set the maximum yaw angle that the bone can look to.
  73451. */
  73452. get: function () {
  73453. return this._maxYaw;
  73454. },
  73455. set: function (value) {
  73456. this._maxYaw = value;
  73457. this._maxYawSin = Math.sin(value);
  73458. this._maxYawCos = Math.cos(value);
  73459. if (this._minYaw != null) {
  73460. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73461. this._yawRange = this._maxYaw - this._minYaw;
  73462. }
  73463. },
  73464. enumerable: true,
  73465. configurable: true
  73466. });
  73467. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73468. /**
  73469. * Get/set the minimum pitch angle that the bone can look to.
  73470. */
  73471. get: function () {
  73472. return this._minPitch;
  73473. },
  73474. set: function (value) {
  73475. this._minPitch = value;
  73476. this._minPitchTan = Math.tan(value);
  73477. },
  73478. enumerable: true,
  73479. configurable: true
  73480. });
  73481. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73482. /**
  73483. * Get/set the maximum pitch angle that the bone can look to.
  73484. */
  73485. get: function () {
  73486. return this._maxPitch;
  73487. },
  73488. set: function (value) {
  73489. this._maxPitch = value;
  73490. this._maxPitchTan = Math.tan(value);
  73491. },
  73492. enumerable: true,
  73493. configurable: true
  73494. });
  73495. /**
  73496. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73497. */
  73498. BoneLookController.prototype.update = function () {
  73499. //skip the first frame when slerping so that the mesh rotation is correct
  73500. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73501. this._firstFrameSkipped = true;
  73502. return;
  73503. }
  73504. var bone = this.bone;
  73505. var bonePos = BoneLookController._tmpVecs[0];
  73506. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73507. var target = this.target;
  73508. var _tmpMat1 = BoneLookController._tmpMats[0];
  73509. var _tmpMat2 = BoneLookController._tmpMats[1];
  73510. var mesh = this.mesh;
  73511. var parentBone = bone.getParent();
  73512. var upAxis = BoneLookController._tmpVecs[1];
  73513. upAxis.copyFrom(this.upAxis);
  73514. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73515. if (this._transformYawPitch) {
  73516. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73517. }
  73518. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73519. }
  73520. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73521. mesh.getDirectionToRef(upAxis, upAxis);
  73522. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73523. upAxis.normalize();
  73524. }
  73525. }
  73526. var checkYaw = false;
  73527. var checkPitch = false;
  73528. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73529. checkYaw = true;
  73530. }
  73531. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73532. checkPitch = true;
  73533. }
  73534. if (checkYaw || checkPitch) {
  73535. var spaceMat = BoneLookController._tmpMats[2];
  73536. var spaceMatInv = BoneLookController._tmpMats[3];
  73537. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  73538. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  73539. }
  73540. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  73541. spaceMat.copyFrom(mesh.getWorldMatrix());
  73542. }
  73543. else {
  73544. var forwardAxis = BoneLookController._tmpVecs[2];
  73545. forwardAxis.copyFrom(this._fowardAxis);
  73546. if (this._transformYawPitch) {
  73547. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  73548. }
  73549. if (parentBone) {
  73550. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  73551. }
  73552. else {
  73553. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  73554. }
  73555. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  73556. rightAxis.normalize();
  73557. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  73558. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  73559. }
  73560. spaceMat.invertToRef(spaceMatInv);
  73561. var xzlen = null;
  73562. if (checkPitch) {
  73563. var localTarget = BoneLookController._tmpVecs[3];
  73564. target.subtractToRef(bonePos, localTarget);
  73565. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73566. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73567. var pitch = Math.atan2(localTarget.y, xzlen);
  73568. var newPitch = pitch;
  73569. if (pitch > this._maxPitch) {
  73570. localTarget.y = this._maxPitchTan * xzlen;
  73571. newPitch = this._maxPitch;
  73572. }
  73573. else if (pitch < this._minPitch) {
  73574. localTarget.y = this._minPitchTan * xzlen;
  73575. newPitch = this._minPitch;
  73576. }
  73577. if (pitch != newPitch) {
  73578. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73579. localTarget.addInPlace(bonePos);
  73580. target = localTarget;
  73581. }
  73582. }
  73583. if (checkYaw) {
  73584. var localTarget = BoneLookController._tmpVecs[4];
  73585. target.subtractToRef(bonePos, localTarget);
  73586. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73587. var yaw = Math.atan2(localTarget.x, localTarget.z);
  73588. var newYaw = yaw;
  73589. if (yaw > this._maxYaw || yaw < this._minYaw) {
  73590. if (xzlen == null) {
  73591. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73592. }
  73593. if (this._yawRange > Math.PI) {
  73594. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  73595. localTarget.z = this._maxYawCos * xzlen;
  73596. localTarget.x = this._maxYawSin * xzlen;
  73597. newYaw = this._maxYaw;
  73598. }
  73599. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  73600. localTarget.z = this._minYawCos * xzlen;
  73601. localTarget.x = this._minYawSin * xzlen;
  73602. newYaw = this._minYaw;
  73603. }
  73604. }
  73605. else {
  73606. if (yaw > this._maxYaw) {
  73607. localTarget.z = this._maxYawCos * xzlen;
  73608. localTarget.x = this._maxYawSin * xzlen;
  73609. newYaw = this._maxYaw;
  73610. }
  73611. else if (yaw < this._minYaw) {
  73612. localTarget.z = this._minYawCos * xzlen;
  73613. localTarget.x = this._minYawSin * xzlen;
  73614. newYaw = this._minYaw;
  73615. }
  73616. }
  73617. }
  73618. if (this._slerping && this._yawRange > Math.PI) {
  73619. //are we going to be crossing into the min/max region?
  73620. var boneFwd = BoneLookController._tmpVecs[8];
  73621. boneFwd.copyFrom(BABYLON.Axis.Z);
  73622. if (this._transformYawPitch) {
  73623. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73624. }
  73625. var boneRotMat = BoneLookController._tmpMats[4];
  73626. this._boneQuat.toRotationMatrix(boneRotMat);
  73627. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73628. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73629. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73630. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73631. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73632. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  73633. if (angBtwTar > angBtwMidYaw) {
  73634. if (xzlen == null) {
  73635. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73636. }
  73637. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  73638. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  73639. if (angBtwMin < angBtwMax) {
  73640. newYaw = boneYaw + Math.PI * .75;
  73641. localTarget.z = Math.cos(newYaw) * xzlen;
  73642. localTarget.x = Math.sin(newYaw) * xzlen;
  73643. }
  73644. else {
  73645. newYaw = boneYaw - Math.PI * .75;
  73646. localTarget.z = Math.cos(newYaw) * xzlen;
  73647. localTarget.x = Math.sin(newYaw) * xzlen;
  73648. }
  73649. }
  73650. }
  73651. if (yaw != newYaw) {
  73652. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73653. localTarget.addInPlace(bonePos);
  73654. target = localTarget;
  73655. }
  73656. }
  73657. }
  73658. var zaxis = BoneLookController._tmpVecs[5];
  73659. var xaxis = BoneLookController._tmpVecs[6];
  73660. var yaxis = BoneLookController._tmpVecs[7];
  73661. var _tmpQuat = BoneLookController._tmpQuat;
  73662. target.subtractToRef(bonePos, zaxis);
  73663. zaxis.normalize();
  73664. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  73665. xaxis.normalize();
  73666. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  73667. yaxis.normalize();
  73668. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  73669. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  73670. return;
  73671. }
  73672. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  73673. return;
  73674. }
  73675. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  73676. return;
  73677. }
  73678. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  73679. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  73680. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  73681. }
  73682. if (this.slerpAmount < 1) {
  73683. if (!this._slerping) {
  73684. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  73685. }
  73686. if (this._transformYawPitch) {
  73687. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73688. }
  73689. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  73690. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  73691. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  73692. this._slerping = true;
  73693. }
  73694. else {
  73695. if (this._transformYawPitch) {
  73696. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73697. }
  73698. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  73699. this._slerping = false;
  73700. }
  73701. };
  73702. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  73703. var angDiff = ang2 - ang1;
  73704. angDiff %= Math.PI * 2;
  73705. if (angDiff > Math.PI) {
  73706. angDiff -= Math.PI * 2;
  73707. }
  73708. else if (angDiff < -Math.PI) {
  73709. angDiff += Math.PI * 2;
  73710. }
  73711. return angDiff;
  73712. };
  73713. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  73714. ang1 %= (2 * Math.PI);
  73715. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73716. ang2 %= (2 * Math.PI);
  73717. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73718. var ab = 0;
  73719. if (ang1 < ang2) {
  73720. ab = ang2 - ang1;
  73721. }
  73722. else {
  73723. ab = ang1 - ang2;
  73724. }
  73725. if (ab > Math.PI) {
  73726. ab = Math.PI * 2 - ab;
  73727. }
  73728. return ab;
  73729. };
  73730. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  73731. ang %= (2 * Math.PI);
  73732. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  73733. ang1 %= (2 * Math.PI);
  73734. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73735. ang2 %= (2 * Math.PI);
  73736. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73737. if (ang1 < ang2) {
  73738. if (ang > ang1 && ang < ang2) {
  73739. return true;
  73740. }
  73741. }
  73742. else {
  73743. if (ang > ang2 && ang < ang1) {
  73744. return true;
  73745. }
  73746. }
  73747. return false;
  73748. };
  73749. 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()];
  73750. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  73751. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73752. return BoneLookController;
  73753. }());
  73754. BABYLON.BoneLookController = BoneLookController;
  73755. })(BABYLON || (BABYLON = {}));
  73756. //# sourceMappingURL=babylon.boneLookController.js.map
  73757. "use strict";
  73758. var BABYLON;
  73759. (function (BABYLON) {
  73760. var Skeleton = /** @class */ (function () {
  73761. function Skeleton(name, id, scene) {
  73762. this.name = name;
  73763. this.id = id;
  73764. this.bones = new Array();
  73765. this.needInitialSkinMatrix = false;
  73766. this._isDirty = true;
  73767. this._meshesWithPoseMatrix = new Array();
  73768. this._identity = BABYLON.Matrix.Identity();
  73769. this._ranges = {};
  73770. this._lastAbsoluteTransformsUpdateId = -1;
  73771. /**
  73772. * Specifies if the skeleton should be serialized.
  73773. */
  73774. this.doNotSerialize = false;
  73775. // Events
  73776. /**
  73777. * An event triggered before computing the skeleton's matrices
  73778. * @type {BABYLON.Observable}
  73779. */
  73780. this.onBeforeComputeObservable = new BABYLON.Observable();
  73781. this.bones = [];
  73782. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73783. scene.skeletons.push(this);
  73784. //make sure it will recalculate the matrix next time prepare is called.
  73785. this._isDirty = true;
  73786. }
  73787. // Members
  73788. Skeleton.prototype.getTransformMatrices = function (mesh) {
  73789. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  73790. return mesh._bonesTransformMatrices;
  73791. }
  73792. if (!this._transformMatrices) {
  73793. this.prepare();
  73794. }
  73795. return this._transformMatrices;
  73796. };
  73797. Skeleton.prototype.getScene = function () {
  73798. return this._scene;
  73799. };
  73800. // Methods
  73801. /**
  73802. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  73803. */
  73804. Skeleton.prototype.toString = function (fullDetails) {
  73805. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  73806. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  73807. if (fullDetails) {
  73808. ret += ", Ranges: {";
  73809. var first = true;
  73810. for (var name_1 in this._ranges) {
  73811. if (first) {
  73812. ret += ", ";
  73813. first = false;
  73814. }
  73815. ret += name_1;
  73816. }
  73817. ret += "}";
  73818. }
  73819. return ret;
  73820. };
  73821. /**
  73822. * Get bone's index searching by name
  73823. * @param {string} name is bone's name to search for
  73824. * @return {number} Indice of the bone. Returns -1 if not found
  73825. */
  73826. Skeleton.prototype.getBoneIndexByName = function (name) {
  73827. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  73828. if (this.bones[boneIndex].name === name) {
  73829. return boneIndex;
  73830. }
  73831. }
  73832. return -1;
  73833. };
  73834. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  73835. // check name not already in use
  73836. if (!this._ranges[name]) {
  73837. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  73838. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73839. if (this.bones[i].animations[0]) {
  73840. this.bones[i].animations[0].createRange(name, from, to);
  73841. }
  73842. }
  73843. }
  73844. };
  73845. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  73846. if (deleteFrames === void 0) { deleteFrames = true; }
  73847. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73848. if (this.bones[i].animations[0]) {
  73849. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  73850. }
  73851. }
  73852. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  73853. };
  73854. Skeleton.prototype.getAnimationRange = function (name) {
  73855. return this._ranges[name];
  73856. };
  73857. /**
  73858. * Returns as an Array, all AnimationRanges defined on this skeleton
  73859. */
  73860. Skeleton.prototype.getAnimationRanges = function () {
  73861. var animationRanges = [];
  73862. var name;
  73863. var i = 0;
  73864. for (name in this._ranges) {
  73865. animationRanges[i] = this._ranges[name];
  73866. i++;
  73867. }
  73868. return animationRanges;
  73869. };
  73870. /**
  73871. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  73872. */
  73873. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  73874. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73875. if (this._ranges[name] || !source.getAnimationRange(name)) {
  73876. return false;
  73877. }
  73878. var ret = true;
  73879. var frameOffset = this._getHighestAnimationFrame() + 1;
  73880. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  73881. var boneDict = {};
  73882. var sourceBones = source.bones;
  73883. var nBones;
  73884. var i;
  73885. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  73886. boneDict[sourceBones[i].name] = sourceBones[i];
  73887. }
  73888. if (this.bones.length !== sourceBones.length) {
  73889. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  73890. ret = false;
  73891. }
  73892. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  73893. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  73894. var boneName = this.bones[i].name;
  73895. var sourceBone = boneDict[boneName];
  73896. if (sourceBone) {
  73897. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73898. }
  73899. else {
  73900. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73901. ret = false;
  73902. }
  73903. }
  73904. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73905. var range = source.getAnimationRange(name);
  73906. if (range) {
  73907. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73908. }
  73909. return ret;
  73910. };
  73911. Skeleton.prototype.returnToRest = function () {
  73912. for (var index = 0; index < this.bones.length; index++) {
  73913. this.bones[index].returnToRest();
  73914. }
  73915. };
  73916. Skeleton.prototype._getHighestAnimationFrame = function () {
  73917. var ret = 0;
  73918. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73919. if (this.bones[i].animations[0]) {
  73920. var highest = this.bones[i].animations[0].getHighestFrame();
  73921. if (ret < highest) {
  73922. ret = highest;
  73923. }
  73924. }
  73925. }
  73926. return ret;
  73927. };
  73928. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73929. var range = this.getAnimationRange(name);
  73930. if (!range) {
  73931. return null;
  73932. }
  73933. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73934. };
  73935. Skeleton.prototype._markAsDirty = function () {
  73936. this._isDirty = true;
  73937. };
  73938. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73939. this._meshesWithPoseMatrix.push(mesh);
  73940. };
  73941. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73942. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73943. if (index > -1) {
  73944. this._meshesWithPoseMatrix.splice(index, 1);
  73945. }
  73946. };
  73947. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73948. this.onBeforeComputeObservable.notifyObservers(this);
  73949. for (var index = 0; index < this.bones.length; index++) {
  73950. var bone = this.bones[index];
  73951. var parentBone = bone.getParent();
  73952. if (parentBone) {
  73953. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73954. }
  73955. else {
  73956. if (initialSkinMatrix) {
  73957. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73958. }
  73959. else {
  73960. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73961. }
  73962. }
  73963. if (bone._index !== -1) {
  73964. var mappedIndex = bone._index === null ? index : bone._index;
  73965. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73966. }
  73967. }
  73968. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73969. };
  73970. Skeleton.prototype.prepare = function () {
  73971. if (!this._isDirty) {
  73972. return;
  73973. }
  73974. if (this.needInitialSkinMatrix) {
  73975. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73976. var mesh = this._meshesWithPoseMatrix[index];
  73977. var poseMatrix = mesh.getPoseMatrix();
  73978. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73979. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73980. }
  73981. if (this._synchronizedWithMesh !== mesh) {
  73982. this._synchronizedWithMesh = mesh;
  73983. // Prepare bones
  73984. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73985. var bone = this.bones[boneIndex];
  73986. if (!bone.getParent()) {
  73987. var matrix = bone.getBaseMatrix();
  73988. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  73989. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  73990. }
  73991. }
  73992. }
  73993. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  73994. }
  73995. }
  73996. else {
  73997. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  73998. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73999. }
  74000. this._computeTransformMatrices(this._transformMatrices, null);
  74001. }
  74002. this._isDirty = false;
  74003. this._scene._activeBones.addCount(this.bones.length, false);
  74004. };
  74005. Skeleton.prototype.getAnimatables = function () {
  74006. if (!this._animatables || this._animatables.length !== this.bones.length) {
  74007. this._animatables = [];
  74008. for (var index = 0; index < this.bones.length; index++) {
  74009. this._animatables.push(this.bones[index]);
  74010. }
  74011. }
  74012. return this._animatables;
  74013. };
  74014. Skeleton.prototype.clone = function (name, id) {
  74015. var result = new Skeleton(name, id || name, this._scene);
  74016. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74017. for (var index = 0; index < this.bones.length; index++) {
  74018. var source = this.bones[index];
  74019. var parentBone = null;
  74020. var parent_1 = source.getParent();
  74021. if (parent_1) {
  74022. var parentIndex = this.bones.indexOf(parent_1);
  74023. parentBone = result.bones[parentIndex];
  74024. }
  74025. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  74026. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  74027. }
  74028. if (this._ranges) {
  74029. result._ranges = {};
  74030. for (var rangeName in this._ranges) {
  74031. var range = this._ranges[rangeName];
  74032. if (range) {
  74033. result._ranges[rangeName] = range.clone();
  74034. }
  74035. }
  74036. }
  74037. this._isDirty = true;
  74038. return result;
  74039. };
  74040. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74041. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74042. this.bones.forEach(function (bone) {
  74043. bone.animations.forEach(function (animation) {
  74044. animation.enableBlending = true;
  74045. animation.blendingSpeed = blendingSpeed;
  74046. });
  74047. });
  74048. };
  74049. Skeleton.prototype.dispose = function () {
  74050. this._meshesWithPoseMatrix = [];
  74051. // Animations
  74052. this.getScene().stopAnimation(this);
  74053. // Remove from scene
  74054. this.getScene().removeSkeleton(this);
  74055. };
  74056. Skeleton.prototype.serialize = function () {
  74057. var serializationObject = {};
  74058. serializationObject.name = this.name;
  74059. serializationObject.id = this.id;
  74060. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  74061. serializationObject.bones = [];
  74062. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74063. for (var index = 0; index < this.bones.length; index++) {
  74064. var bone = this.bones[index];
  74065. var parent_2 = bone.getParent();
  74066. var serializedBone = {
  74067. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74068. name: bone.name,
  74069. matrix: bone.getBaseMatrix().toArray(),
  74070. rest: bone.getRestPose().toArray()
  74071. };
  74072. serializationObject.bones.push(serializedBone);
  74073. if (bone.length) {
  74074. serializedBone.length = bone.length;
  74075. }
  74076. if (bone.animations && bone.animations.length > 0) {
  74077. serializedBone.animation = bone.animations[0].serialize();
  74078. }
  74079. serializationObject.ranges = [];
  74080. for (var name in this._ranges) {
  74081. var source = this._ranges[name];
  74082. if (!source) {
  74083. continue;
  74084. }
  74085. var range = {};
  74086. range.name = name;
  74087. range.from = source.from;
  74088. range.to = source.to;
  74089. serializationObject.ranges.push(range);
  74090. }
  74091. }
  74092. return serializationObject;
  74093. };
  74094. Skeleton.Parse = function (parsedSkeleton, scene) {
  74095. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74096. if (parsedSkeleton.dimensionsAtRest) {
  74097. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74098. }
  74099. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74100. var index;
  74101. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74102. var parsedBone = parsedSkeleton.bones[index];
  74103. var parentBone = null;
  74104. if (parsedBone.parentBoneIndex > -1) {
  74105. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74106. }
  74107. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74108. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74109. if (parsedBone.length) {
  74110. bone.length = parsedBone.length;
  74111. }
  74112. if (parsedBone.animation) {
  74113. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74114. }
  74115. }
  74116. // placed after bones, so createAnimationRange can cascade down
  74117. if (parsedSkeleton.ranges) {
  74118. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74119. var data = parsedSkeleton.ranges[index];
  74120. skeleton.createAnimationRange(data.name, data.from, data.to);
  74121. }
  74122. }
  74123. return skeleton;
  74124. };
  74125. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74126. if (forceUpdate === void 0) { forceUpdate = false; }
  74127. var renderId = this._scene.getRenderId();
  74128. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74129. this.bones[0].computeAbsoluteTransforms();
  74130. this._lastAbsoluteTransformsUpdateId = renderId;
  74131. }
  74132. };
  74133. Skeleton.prototype.getPoseMatrix = function () {
  74134. var poseMatrix = null;
  74135. if (this._meshesWithPoseMatrix.length > 0) {
  74136. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74137. }
  74138. return poseMatrix;
  74139. };
  74140. Skeleton.prototype.sortBones = function () {
  74141. var bones = new Array();
  74142. var visited = new Array(this.bones.length);
  74143. for (var index = 0; index < this.bones.length; index++) {
  74144. this._sortBones(index, bones, visited);
  74145. }
  74146. this.bones = bones;
  74147. };
  74148. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74149. if (visited[index]) {
  74150. return;
  74151. }
  74152. visited[index] = true;
  74153. var bone = this.bones[index];
  74154. if (bone._index === undefined) {
  74155. bone._index = index;
  74156. }
  74157. var parentBone = bone.getParent();
  74158. if (parentBone) {
  74159. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74160. }
  74161. bones.push(bone);
  74162. };
  74163. return Skeleton;
  74164. }());
  74165. BABYLON.Skeleton = Skeleton;
  74166. })(BABYLON || (BABYLON = {}));
  74167. //# sourceMappingURL=babylon.skeleton.js.map
  74168. "use strict";
  74169. var BABYLON;
  74170. (function (BABYLON) {
  74171. var SphericalPolynomial = /** @class */ (function () {
  74172. function SphericalPolynomial() {
  74173. this.x = BABYLON.Vector3.Zero();
  74174. this.y = BABYLON.Vector3.Zero();
  74175. this.z = BABYLON.Vector3.Zero();
  74176. this.xx = BABYLON.Vector3.Zero();
  74177. this.yy = BABYLON.Vector3.Zero();
  74178. this.zz = BABYLON.Vector3.Zero();
  74179. this.xy = BABYLON.Vector3.Zero();
  74180. this.yz = BABYLON.Vector3.Zero();
  74181. this.zx = BABYLON.Vector3.Zero();
  74182. }
  74183. SphericalPolynomial.prototype.addAmbient = function (color) {
  74184. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74185. this.xx = this.xx.add(colorVector);
  74186. this.yy = this.yy.add(colorVector);
  74187. this.zz = this.zz.add(colorVector);
  74188. };
  74189. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74190. var result = new SphericalPolynomial();
  74191. result.x = harmonics.L11.scale(1.02333);
  74192. result.y = harmonics.L1_1.scale(1.02333);
  74193. result.z = harmonics.L10.scale(1.02333);
  74194. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74195. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74196. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74197. result.yz = harmonics.L2_1.scale(0.858086);
  74198. result.zx = harmonics.L21.scale(0.858086);
  74199. result.xy = harmonics.L2_2.scale(0.858086);
  74200. result.scale(1.0 / Math.PI);
  74201. return result;
  74202. };
  74203. SphericalPolynomial.prototype.scale = function (scale) {
  74204. this.x = this.x.scale(scale);
  74205. this.y = this.y.scale(scale);
  74206. this.z = this.z.scale(scale);
  74207. this.xx = this.xx.scale(scale);
  74208. this.yy = this.yy.scale(scale);
  74209. this.zz = this.zz.scale(scale);
  74210. this.yz = this.yz.scale(scale);
  74211. this.zx = this.zx.scale(scale);
  74212. this.xy = this.xy.scale(scale);
  74213. };
  74214. return SphericalPolynomial;
  74215. }());
  74216. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74217. var SphericalHarmonics = /** @class */ (function () {
  74218. function SphericalHarmonics() {
  74219. this.L00 = BABYLON.Vector3.Zero();
  74220. this.L1_1 = BABYLON.Vector3.Zero();
  74221. this.L10 = BABYLON.Vector3.Zero();
  74222. this.L11 = BABYLON.Vector3.Zero();
  74223. this.L2_2 = BABYLON.Vector3.Zero();
  74224. this.L2_1 = BABYLON.Vector3.Zero();
  74225. this.L20 = BABYLON.Vector3.Zero();
  74226. this.L21 = BABYLON.Vector3.Zero();
  74227. this.L22 = BABYLON.Vector3.Zero();
  74228. }
  74229. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74230. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74231. var c = colorVector.scale(deltaSolidAngle);
  74232. this.L00 = this.L00.add(c.scale(0.282095));
  74233. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74234. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74235. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74236. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74237. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74238. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74239. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74240. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74241. };
  74242. SphericalHarmonics.prototype.scale = function (scale) {
  74243. this.L00 = this.L00.scale(scale);
  74244. this.L1_1 = this.L1_1.scale(scale);
  74245. this.L10 = this.L10.scale(scale);
  74246. this.L11 = this.L11.scale(scale);
  74247. this.L2_2 = this.L2_2.scale(scale);
  74248. this.L2_1 = this.L2_1.scale(scale);
  74249. this.L20 = this.L20.scale(scale);
  74250. this.L21 = this.L21.scale(scale);
  74251. this.L22 = this.L22.scale(scale);
  74252. };
  74253. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74254. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74255. //
  74256. // E_lm = A_l * L_lm
  74257. //
  74258. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74259. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74260. // the scaling factors are given in equation 9.
  74261. // Constant (Band 0)
  74262. this.L00 = this.L00.scale(3.141593);
  74263. // Linear (Band 1)
  74264. this.L1_1 = this.L1_1.scale(2.094395);
  74265. this.L10 = this.L10.scale(2.094395);
  74266. this.L11 = this.L11.scale(2.094395);
  74267. // Quadratic (Band 2)
  74268. this.L2_2 = this.L2_2.scale(0.785398);
  74269. this.L2_1 = this.L2_1.scale(0.785398);
  74270. this.L20 = this.L20.scale(0.785398);
  74271. this.L21 = this.L21.scale(0.785398);
  74272. this.L22 = this.L22.scale(0.785398);
  74273. };
  74274. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74275. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74276. // L = (1/pi) * E * rho
  74277. //
  74278. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74279. this.scale(1.0 / Math.PI);
  74280. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74281. // (The pixel shader must apply albedo after texture fetches, etc).
  74282. };
  74283. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74284. var result = new SphericalHarmonics();
  74285. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74286. result.L1_1 = polynomial.y.scale(0.977204);
  74287. result.L10 = polynomial.z.scale(0.977204);
  74288. result.L11 = polynomial.x.scale(0.977204);
  74289. result.L2_2 = polynomial.xy.scale(1.16538);
  74290. result.L2_1 = polynomial.yz.scale(1.16538);
  74291. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74292. result.L21 = polynomial.zx.scale(1.16538);
  74293. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74294. result.scale(Math.PI);
  74295. return result;
  74296. };
  74297. return SphericalHarmonics;
  74298. }());
  74299. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74300. })(BABYLON || (BABYLON = {}));
  74301. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74302. "use strict";
  74303. var BABYLON;
  74304. (function (BABYLON) {
  74305. var FileFaceOrientation = /** @class */ (function () {
  74306. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74307. this.name = name;
  74308. this.worldAxisForNormal = worldAxisForNormal;
  74309. this.worldAxisForFileX = worldAxisForFileX;
  74310. this.worldAxisForFileY = worldAxisForFileY;
  74311. }
  74312. return FileFaceOrientation;
  74313. }());
  74314. ;
  74315. /**
  74316. * Helper class dealing with the extraction of spherical polynomial dataArray
  74317. * from a cube map.
  74318. */
  74319. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74320. function CubeMapToSphericalPolynomialTools() {
  74321. }
  74322. /**
  74323. * Converts a texture to the according Spherical Polynomial data.
  74324. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74325. *
  74326. * @param texture The texture to extract the information from.
  74327. * @return The Spherical Polynomial data.
  74328. */
  74329. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74330. if (!texture.isCube) {
  74331. // Only supports cube Textures currently.
  74332. return null;
  74333. }
  74334. var size = texture.getSize().width;
  74335. var right = texture.readPixels(0);
  74336. var left = texture.readPixels(1);
  74337. var up;
  74338. var down;
  74339. if (texture.isRenderTarget) {
  74340. up = texture.readPixels(3);
  74341. down = texture.readPixels(2);
  74342. }
  74343. else {
  74344. up = texture.readPixels(2);
  74345. down = texture.readPixels(3);
  74346. }
  74347. var front = texture.readPixels(4);
  74348. var back = texture.readPixels(5);
  74349. var gammaSpace = texture.gammaSpace;
  74350. // Always read as RGBA.
  74351. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74352. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74353. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74354. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74355. }
  74356. var cubeInfo = {
  74357. size: size,
  74358. right: right,
  74359. left: left,
  74360. up: up,
  74361. down: down,
  74362. front: front,
  74363. back: back,
  74364. format: format,
  74365. type: type,
  74366. gammaSpace: gammaSpace,
  74367. };
  74368. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74369. };
  74370. /**
  74371. * Converts a cubemap to the according Spherical Polynomial data.
  74372. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74373. *
  74374. * @param cubeInfo The Cube map to extract the information from.
  74375. * @return The Spherical Polynomial data.
  74376. */
  74377. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74378. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74379. var totalSolidAngle = 0.0;
  74380. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74381. var du = 2.0 / cubeInfo.size;
  74382. var dv = du;
  74383. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74384. var minUV = du * 0.5 - 1.0;
  74385. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74386. var fileFace = this.FileFaces[faceIndex];
  74387. var dataArray = cubeInfo[fileFace.name];
  74388. var v = minUV;
  74389. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74390. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74391. // Because SP is still linear, so summation is fine in that basis.
  74392. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74393. for (var y = 0; y < cubeInfo.size; y++) {
  74394. var u = minUV;
  74395. for (var x = 0; x < cubeInfo.size; x++) {
  74396. // World direction (not normalised)
  74397. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74398. worldDirection.normalize();
  74399. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74400. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74401. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74402. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74403. // Handle Integer types.
  74404. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74405. r /= 255;
  74406. g /= 255;
  74407. b /= 255;
  74408. }
  74409. // Handle Gamma space textures.
  74410. if (cubeInfo.gammaSpace) {
  74411. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74412. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74413. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74414. }
  74415. var color = new BABYLON.Color3(r, g, b);
  74416. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74417. totalSolidAngle += deltaSolidAngle;
  74418. u += du;
  74419. }
  74420. v += dv;
  74421. }
  74422. }
  74423. // Solid angle for entire sphere is 4*pi
  74424. var sphereSolidAngle = 4.0 * Math.PI;
  74425. // Adjust the solid angle to allow for how many faces we processed.
  74426. var facesProcessed = 6.0;
  74427. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74428. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74429. // This is needed because the numerical integration over the cube uses a
  74430. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74431. // and also to compensate for accumulative error due to float precision in the summation.
  74432. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74433. sphericalHarmonics.scale(correctionFactor);
  74434. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74435. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74436. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74437. };
  74438. CubeMapToSphericalPolynomialTools.FileFaces = [
  74439. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74440. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74441. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74442. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74443. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74444. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74445. ];
  74446. return CubeMapToSphericalPolynomialTools;
  74447. }());
  74448. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74449. })(BABYLON || (BABYLON = {}));
  74450. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74451. "use strict";
  74452. var BABYLON;
  74453. (function (BABYLON) {
  74454. /**
  74455. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74456. */
  74457. var PanoramaToCubeMapTools = /** @class */ (function () {
  74458. function PanoramaToCubeMapTools() {
  74459. }
  74460. /**
  74461. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74462. *
  74463. * @param float32Array The source data.
  74464. * @param inputWidth The width of the input panorama.
  74465. * @param inputhHeight The height of the input panorama.
  74466. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74467. * @return The cubemap data
  74468. */
  74469. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74470. if (!float32Array) {
  74471. throw "ConvertPanoramaToCubemap: input cannot be null";
  74472. }
  74473. if (float32Array.length != inputWidth * inputHeight * 3) {
  74474. throw "ConvertPanoramaToCubemap: input size is wrong";
  74475. }
  74476. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74477. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74478. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74479. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74480. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74481. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74482. return {
  74483. front: textureFront,
  74484. back: textureBack,
  74485. left: textureLeft,
  74486. right: textureRight,
  74487. up: textureUp,
  74488. down: textureDown,
  74489. size: size,
  74490. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74491. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74492. gammaSpace: false,
  74493. };
  74494. };
  74495. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74496. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74497. var textureArray = new Float32Array(buffer);
  74498. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74499. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74500. var dy = 1 / texSize;
  74501. var fy = 0;
  74502. for (var y = 0; y < texSize; y++) {
  74503. var xv1 = faceData[0];
  74504. var xv2 = faceData[2];
  74505. for (var x = 0; x < texSize; x++) {
  74506. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74507. v.normalize();
  74508. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74509. // 3 channels per pixels
  74510. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74511. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74512. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74513. xv1 = xv1.add(rotDX1);
  74514. xv2 = xv2.add(rotDX2);
  74515. }
  74516. fy += dy;
  74517. }
  74518. return textureArray;
  74519. };
  74520. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74521. var theta = Math.atan2(vDir.z, vDir.x);
  74522. var phi = Math.acos(vDir.y);
  74523. while (theta < -Math.PI)
  74524. theta += 2 * Math.PI;
  74525. while (theta > Math.PI)
  74526. theta -= 2 * Math.PI;
  74527. var dx = theta / Math.PI;
  74528. var dy = phi / Math.PI;
  74529. // recenter.
  74530. dx = dx * 0.5 + 0.5;
  74531. var px = Math.round(dx * inputWidth);
  74532. if (px < 0)
  74533. px = 0;
  74534. else if (px >= inputWidth)
  74535. px = inputWidth - 1;
  74536. var py = Math.round(dy * inputHeight);
  74537. if (py < 0)
  74538. py = 0;
  74539. else if (py >= inputHeight)
  74540. py = inputHeight - 1;
  74541. var inputY = (inputHeight - py - 1);
  74542. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  74543. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  74544. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  74545. return {
  74546. r: r,
  74547. g: g,
  74548. b: b
  74549. };
  74550. };
  74551. PanoramaToCubeMapTools.FACE_FRONT = [
  74552. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74553. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74554. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74555. new BABYLON.Vector3(1.0, 1.0, -1.0)
  74556. ];
  74557. PanoramaToCubeMapTools.FACE_BACK = [
  74558. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74559. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74560. new BABYLON.Vector3(1.0, 1.0, 1.0),
  74561. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  74562. ];
  74563. PanoramaToCubeMapTools.FACE_RIGHT = [
  74564. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74565. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74566. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74567. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74568. ];
  74569. PanoramaToCubeMapTools.FACE_LEFT = [
  74570. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74571. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74572. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74573. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  74574. ];
  74575. PanoramaToCubeMapTools.FACE_DOWN = [
  74576. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74577. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74578. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74579. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74580. ];
  74581. PanoramaToCubeMapTools.FACE_UP = [
  74582. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74583. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74584. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74585. new BABYLON.Vector3(1.0, -1.0, -1.0)
  74586. ];
  74587. return PanoramaToCubeMapTools;
  74588. }());
  74589. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  74590. })(BABYLON || (BABYLON = {}));
  74591. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  74592. "use strict";
  74593. var BABYLON;
  74594. (function (BABYLON) {
  74595. ;
  74596. /**
  74597. * This groups tools to convert HDR texture to native colors array.
  74598. */
  74599. var HDRTools = /** @class */ (function () {
  74600. function HDRTools() {
  74601. }
  74602. HDRTools.Ldexp = function (mantissa, exponent) {
  74603. if (exponent > 1023) {
  74604. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  74605. }
  74606. if (exponent < -1074) {
  74607. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  74608. }
  74609. return mantissa * Math.pow(2, exponent);
  74610. };
  74611. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74612. if (exponent > 0) {
  74613. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74614. float32array[index + 0] = red * exponent;
  74615. float32array[index + 1] = green * exponent;
  74616. float32array[index + 2] = blue * exponent;
  74617. }
  74618. else {
  74619. float32array[index + 0] = 0;
  74620. float32array[index + 1] = 0;
  74621. float32array[index + 2] = 0;
  74622. }
  74623. };
  74624. HDRTools.readStringLine = function (uint8array, startIndex) {
  74625. var line = "";
  74626. var character = "";
  74627. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74628. character = String.fromCharCode(uint8array[i]);
  74629. if (character == "\n") {
  74630. break;
  74631. }
  74632. line += character;
  74633. }
  74634. return line;
  74635. };
  74636. /**
  74637. * Reads header information from an RGBE texture stored in a native array.
  74638. * More information on this format are available here:
  74639. * https://en.wikipedia.org/wiki/RGBE_image_format
  74640. *
  74641. * @param uint8array The binary file stored in native array.
  74642. * @return The header information.
  74643. */
  74644. HDRTools.RGBE_ReadHeader = function (uint8array) {
  74645. var height = 0;
  74646. var width = 0;
  74647. var line = this.readStringLine(uint8array, 0);
  74648. if (line[0] != '#' || line[1] != '?') {
  74649. throw "Bad HDR Format.";
  74650. }
  74651. var endOfHeader = false;
  74652. var findFormat = false;
  74653. var lineIndex = 0;
  74654. do {
  74655. lineIndex += (line.length + 1);
  74656. line = this.readStringLine(uint8array, lineIndex);
  74657. if (line == "FORMAT=32-bit_rle_rgbe") {
  74658. findFormat = true;
  74659. }
  74660. else if (line.length == 0) {
  74661. endOfHeader = true;
  74662. }
  74663. } while (!endOfHeader);
  74664. if (!findFormat) {
  74665. throw "HDR Bad header format, unsupported FORMAT";
  74666. }
  74667. lineIndex += (line.length + 1);
  74668. line = this.readStringLine(uint8array, lineIndex);
  74669. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  74670. var match = sizeRegexp.exec(line);
  74671. // TODO. Support +Y and -X if needed.
  74672. if (!match || match.length < 3) {
  74673. throw "HDR Bad header format, no size";
  74674. }
  74675. width = parseInt(match[2]);
  74676. height = parseInt(match[1]);
  74677. if (width < 8 || width > 0x7fff) {
  74678. throw "HDR Bad header format, unsupported size";
  74679. }
  74680. lineIndex += (line.length + 1);
  74681. return {
  74682. height: height,
  74683. width: width,
  74684. dataPosition: lineIndex
  74685. };
  74686. };
  74687. /**
  74688. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  74689. * This RGBE texture needs to store the information as a panorama.
  74690. *
  74691. * More information on this format are available here:
  74692. * https://en.wikipedia.org/wiki/RGBE_image_format
  74693. *
  74694. * @param buffer The binary file stored in an array buffer.
  74695. * @param size The expected size of the extracted cubemap.
  74696. * @return The Cube Map information.
  74697. */
  74698. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  74699. var uint8array = new Uint8Array(buffer);
  74700. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  74701. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74702. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  74703. return cubeMapData;
  74704. };
  74705. /**
  74706. * Returns the pixels data extracted from an RGBE texture.
  74707. * This pixels will be stored left to right up to down in the R G B order in one array.
  74708. *
  74709. * More information on this format are available here:
  74710. * https://en.wikipedia.org/wiki/RGBE_image_format
  74711. *
  74712. * @param uint8array The binary file stored in an array buffer.
  74713. * @param hdrInfo The header information of the file.
  74714. * @return The pixels data in RGB right to left up to down order.
  74715. */
  74716. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  74717. // Keep for multi format supports.
  74718. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74719. };
  74720. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  74721. var num_scanlines = hdrInfo.height;
  74722. var scanline_width = hdrInfo.width;
  74723. var a, b, c, d, count;
  74724. var dataIndex = hdrInfo.dataPosition;
  74725. var index = 0, endIndex = 0, i = 0;
  74726. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  74727. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  74728. // 3 channels of 4 bytes per pixel in float.
  74729. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  74730. var resultArray = new Float32Array(resultBuffer);
  74731. // read in each successive scanline
  74732. while (num_scanlines > 0) {
  74733. a = uint8array[dataIndex++];
  74734. b = uint8array[dataIndex++];
  74735. c = uint8array[dataIndex++];
  74736. d = uint8array[dataIndex++];
  74737. if (a != 2 || b != 2 || (c & 0x80)) {
  74738. // this file is not run length encoded
  74739. throw "HDR Bad header format, not RLE";
  74740. }
  74741. if (((c << 8) | d) != scanline_width) {
  74742. throw "HDR Bad header format, wrong scan line width";
  74743. }
  74744. index = 0;
  74745. // read each of the four channels for the scanline into the buffer
  74746. for (i = 0; i < 4; i++) {
  74747. endIndex = (i + 1) * scanline_width;
  74748. while (index < endIndex) {
  74749. a = uint8array[dataIndex++];
  74750. b = uint8array[dataIndex++];
  74751. if (a > 128) {
  74752. // a run of the same value
  74753. count = a - 128;
  74754. if ((count == 0) || (count > endIndex - index)) {
  74755. throw "HDR Bad Format, bad scanline data (run)";
  74756. }
  74757. while (count-- > 0) {
  74758. scanLineArray[index++] = b;
  74759. }
  74760. }
  74761. else {
  74762. // a non-run
  74763. count = a;
  74764. if ((count == 0) || (count > endIndex - index)) {
  74765. throw "HDR Bad Format, bad scanline data (non-run)";
  74766. }
  74767. scanLineArray[index++] = b;
  74768. if (--count > 0) {
  74769. for (var j = 0; j < count; j++) {
  74770. scanLineArray[index++] = uint8array[dataIndex++];
  74771. }
  74772. }
  74773. }
  74774. }
  74775. }
  74776. // now convert data from buffer into floats
  74777. for (i = 0; i < scanline_width; i++) {
  74778. a = scanLineArray[i];
  74779. b = scanLineArray[i + scanline_width];
  74780. c = scanLineArray[i + 2 * scanline_width];
  74781. d = scanLineArray[i + 3 * scanline_width];
  74782. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  74783. }
  74784. num_scanlines--;
  74785. }
  74786. return resultArray;
  74787. };
  74788. return HDRTools;
  74789. }());
  74790. BABYLON.HDRTools = HDRTools;
  74791. })(BABYLON || (BABYLON = {}));
  74792. //# sourceMappingURL=babylon.hdr.js.map
  74793. "use strict";
  74794. var BABYLON;
  74795. (function (BABYLON) {
  74796. /**
  74797. * This represents a texture coming from an HDR input.
  74798. *
  74799. * The only supported format is currently panorama picture stored in RGBE format.
  74800. * Example of such files can be found on HDRLib: http://hdrlib.com/
  74801. */
  74802. var HDRCubeTexture = /** @class */ (function (_super) {
  74803. __extends(HDRCubeTexture, _super);
  74804. /**
  74805. * Instantiates an HDRTexture from the following parameters.
  74806. *
  74807. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  74808. * @param scene The scene the texture will be used in
  74809. * @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.
  74810. * @param noMipmap Forces to not generate the mipmap if true
  74811. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  74812. * @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)
  74813. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  74814. */
  74815. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  74816. if (noMipmap === void 0) { noMipmap = false; }
  74817. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74818. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74819. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74820. if (onLoad === void 0) { onLoad = null; }
  74821. if (onError === void 0) { onError = null; }
  74822. var _this = _super.call(this, scene) || this;
  74823. _this._useInGammaSpace = false;
  74824. _this._generateHarmonics = true;
  74825. _this._isBABYLONPreprocessed = false;
  74826. _this._onLoad = null;
  74827. _this._onError = null;
  74828. /**
  74829. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  74830. */
  74831. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  74832. /**
  74833. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  74834. * This is usefull at run time to apply the good shader.
  74835. */
  74836. _this.isPMREM = false;
  74837. _this._isBlocking = true;
  74838. /**
  74839. * Gets or sets the center of the bounding box associated with the cube texture
  74840. * It must define where the camera used to render the texture was set
  74841. */
  74842. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  74843. if (!url) {
  74844. return _this;
  74845. }
  74846. _this.name = url;
  74847. _this.url = url;
  74848. _this.hasAlpha = false;
  74849. _this.isCube = true;
  74850. _this._textureMatrix = BABYLON.Matrix.Identity();
  74851. _this._onLoad = onLoad;
  74852. _this._onError = onError;
  74853. _this.gammaSpace = false;
  74854. var caps = scene.getEngine().getCaps();
  74855. if (size) {
  74856. _this._isBABYLONPreprocessed = false;
  74857. _this._noMipmap = noMipmap;
  74858. _this._size = size;
  74859. _this._useInGammaSpace = useInGammaSpace;
  74860. _this._usePMREMGenerator = usePMREMGenerator &&
  74861. caps.textureLOD &&
  74862. caps.textureFloat &&
  74863. !_this._useInGammaSpace;
  74864. }
  74865. else {
  74866. _this._isBABYLONPreprocessed = true;
  74867. _this._noMipmap = false;
  74868. _this._useInGammaSpace = false;
  74869. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  74870. !_this._useInGammaSpace;
  74871. }
  74872. _this.isPMREM = _this._usePMREMGenerator;
  74873. _this._texture = _this._getFromCache(url, _this._noMipmap);
  74874. if (!_this._texture) {
  74875. if (!scene.useDelayedTextureLoading) {
  74876. _this.loadTexture();
  74877. }
  74878. else {
  74879. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  74880. }
  74881. }
  74882. return _this;
  74883. }
  74884. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  74885. /**
  74886. * Gets wether or not the texture is blocking during loading.
  74887. */
  74888. get: function () {
  74889. return this._isBlocking;
  74890. },
  74891. /**
  74892. * Sets wether or not the texture is blocking during loading.
  74893. */
  74894. set: function (value) {
  74895. this._isBlocking = value;
  74896. },
  74897. enumerable: true,
  74898. configurable: true
  74899. });
  74900. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  74901. get: function () {
  74902. return this._boundingBoxSize;
  74903. },
  74904. /**
  74905. * Gets or sets the size of the bounding box associated with the cube texture
  74906. * When defined, the cubemap will switch to local mode
  74907. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74908. * @example https://www.babylonjs-playground.com/#RNASML
  74909. */
  74910. set: function (value) {
  74911. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74912. return;
  74913. }
  74914. this._boundingBoxSize = value;
  74915. var scene = this.getScene();
  74916. if (scene) {
  74917. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74918. }
  74919. },
  74920. enumerable: true,
  74921. configurable: true
  74922. });
  74923. /**
  74924. * Occurs when the file is a preprocessed .babylon.hdr file.
  74925. */
  74926. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74927. var _this = this;
  74928. var mipLevels = 0;
  74929. var floatArrayView = null;
  74930. var scene = this.getScene();
  74931. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74932. var mips = new Array();
  74933. if (!floatArrayView) {
  74934. return mips;
  74935. }
  74936. var startIndex = 30;
  74937. for (var level = 0; level < mipLevels; level++) {
  74938. mips.push([]);
  74939. // Fill each pixel of the mip level.
  74940. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74941. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74942. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74943. mips[level].push(faceData);
  74944. startIndex += faceSize;
  74945. }
  74946. }
  74947. return mips;
  74948. } : null;
  74949. var callback = function (buffer) {
  74950. var scene = _this.getScene();
  74951. if (!scene) {
  74952. return null;
  74953. }
  74954. // Create Native Array Views
  74955. var intArrayView = new Int32Array(buffer);
  74956. floatArrayView = new Float32Array(buffer);
  74957. // Fill header.
  74958. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74959. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74960. // Update Texture Information.
  74961. if (!_this._texture) {
  74962. return null;
  74963. }
  74964. _this._texture.updateSize(_this._size, _this._size);
  74965. // Fill polynomial information.
  74966. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74967. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74968. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74969. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74970. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74971. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74972. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74973. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74974. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74975. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74976. _this.sphericalPolynomial = sphericalPolynomial;
  74977. // Fill pixel data.
  74978. mipLevels = intArrayView[29]; // Number of mip levels.
  74979. var startIndex = 30;
  74980. var data = [];
  74981. var faceSize = Math.pow(_this._size, 2) * 3;
  74982. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74983. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74984. startIndex += faceSize;
  74985. }
  74986. var results = [];
  74987. var byteArray = null;
  74988. // Push each faces.
  74989. for (var k = 0; k < 6; k++) {
  74990. var dataFace = null;
  74991. // To be deprecated.
  74992. if (version === 1) {
  74993. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  74994. dataFace = data[j];
  74995. }
  74996. // If special cases.
  74997. if (!mipmapGenerator && dataFace) {
  74998. if (!scene.getEngine().getCaps().textureFloat) {
  74999. // 3 channels of 1 bytes per pixel in bytes.
  75000. var byteBuffer = new ArrayBuffer(faceSize);
  75001. byteArray = new Uint8Array(byteBuffer);
  75002. }
  75003. for (var i = 0; i < _this._size * _this._size; i++) {
  75004. // Put in gamma space if requested.
  75005. if (_this._useInGammaSpace) {
  75006. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75007. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75008. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75009. }
  75010. // Convert to int texture for fallback.
  75011. if (byteArray) {
  75012. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75013. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75014. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75015. // May use luminance instead if the result is not accurate.
  75016. var max = Math.max(Math.max(r, g), b);
  75017. if (max > 255) {
  75018. var scale = 255 / max;
  75019. r *= scale;
  75020. g *= scale;
  75021. b *= scale;
  75022. }
  75023. byteArray[(i * 3) + 0] = r;
  75024. byteArray[(i * 3) + 1] = g;
  75025. byteArray[(i * 3) + 2] = b;
  75026. }
  75027. }
  75028. }
  75029. // Fill the array accordingly.
  75030. if (byteArray) {
  75031. results.push(byteArray);
  75032. }
  75033. else {
  75034. results.push(dataFace);
  75035. }
  75036. }
  75037. return results;
  75038. };
  75039. if (scene) {
  75040. 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);
  75041. }
  75042. };
  75043. /**
  75044. * Occurs when the file is raw .hdr file.
  75045. */
  75046. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75047. var _this = this;
  75048. var callback = function (buffer) {
  75049. var scene = _this.getScene();
  75050. if (!scene) {
  75051. return null;
  75052. }
  75053. // Extract the raw linear data.
  75054. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75055. // Generate harmonics if needed.
  75056. if (_this._generateHarmonics) {
  75057. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75058. _this.sphericalPolynomial = sphericalPolynomial;
  75059. }
  75060. var results = [];
  75061. var byteArray = null;
  75062. // Push each faces.
  75063. for (var j = 0; j < 6; j++) {
  75064. // Create uintarray fallback.
  75065. if (!scene.getEngine().getCaps().textureFloat) {
  75066. // 3 channels of 1 bytes per pixel in bytes.
  75067. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75068. byteArray = new Uint8Array(byteBuffer);
  75069. }
  75070. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75071. // If special cases.
  75072. if (_this._useInGammaSpace || byteArray) {
  75073. for (var i = 0; i < _this._size * _this._size; i++) {
  75074. // Put in gamma space if requested.
  75075. if (_this._useInGammaSpace) {
  75076. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75077. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75078. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75079. }
  75080. // Convert to int texture for fallback.
  75081. if (byteArray) {
  75082. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75083. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75084. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75085. // May use luminance instead if the result is not accurate.
  75086. var max = Math.max(Math.max(r, g), b);
  75087. if (max > 255) {
  75088. var scale = 255 / max;
  75089. r *= scale;
  75090. g *= scale;
  75091. b *= scale;
  75092. }
  75093. byteArray[(i * 3) + 0] = r;
  75094. byteArray[(i * 3) + 1] = g;
  75095. byteArray[(i * 3) + 2] = b;
  75096. }
  75097. }
  75098. }
  75099. if (byteArray) {
  75100. results.push(byteArray);
  75101. }
  75102. else {
  75103. results.push(dataFace);
  75104. }
  75105. }
  75106. return results;
  75107. };
  75108. var mipmapGenerator = null;
  75109. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75110. // if (!this._noMipmap &&
  75111. // this._usePMREMGenerator) {
  75112. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75113. // // Custom setup of the generator matching with the PBR shader values.
  75114. // var generator = new BABYLON.PMREMGenerator(data,
  75115. // this._size,
  75116. // this._size,
  75117. // 0,
  75118. // 3,
  75119. // this.getScene().getEngine().getCaps().textureFloat,
  75120. // 2048,
  75121. // 0.25,
  75122. // false,
  75123. // true);
  75124. // return generator.filterCubeMap();
  75125. // };
  75126. // }
  75127. var scene = this.getScene();
  75128. if (scene) {
  75129. 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);
  75130. }
  75131. };
  75132. /**
  75133. * Starts the loading process of the texture.
  75134. */
  75135. HDRCubeTexture.prototype.loadTexture = function () {
  75136. if (this._isBABYLONPreprocessed) {
  75137. this.loadBabylonTexture();
  75138. }
  75139. else {
  75140. this.loadHDRTexture();
  75141. }
  75142. };
  75143. HDRCubeTexture.prototype.clone = function () {
  75144. var scene = this.getScene();
  75145. if (!scene) {
  75146. return this;
  75147. }
  75148. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75149. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75150. // Base texture
  75151. newTexture.level = this.level;
  75152. newTexture.wrapU = this.wrapU;
  75153. newTexture.wrapV = this.wrapV;
  75154. newTexture.coordinatesIndex = this.coordinatesIndex;
  75155. newTexture.coordinatesMode = this.coordinatesMode;
  75156. return newTexture;
  75157. };
  75158. // Methods
  75159. HDRCubeTexture.prototype.delayLoad = function () {
  75160. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75161. return;
  75162. }
  75163. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75164. this._texture = this._getFromCache(this.url, this._noMipmap);
  75165. if (!this._texture) {
  75166. this.loadTexture();
  75167. }
  75168. };
  75169. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75170. return this._textureMatrix;
  75171. };
  75172. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75173. this._textureMatrix = value;
  75174. };
  75175. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75176. var texture = null;
  75177. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75178. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75179. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75180. texture.name = parsedTexture.name;
  75181. texture.hasAlpha = parsedTexture.hasAlpha;
  75182. texture.level = parsedTexture.level;
  75183. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75184. texture.isBlocking = parsedTexture.isBlocking;
  75185. }
  75186. if (texture) {
  75187. if (parsedTexture.boundingBoxPosition) {
  75188. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75189. }
  75190. if (parsedTexture.boundingBoxSize) {
  75191. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75192. }
  75193. }
  75194. return texture;
  75195. };
  75196. HDRCubeTexture.prototype.serialize = function () {
  75197. if (!this.name) {
  75198. return null;
  75199. }
  75200. var serializationObject = {};
  75201. serializationObject.name = this.name;
  75202. serializationObject.hasAlpha = this.hasAlpha;
  75203. serializationObject.isCube = true;
  75204. serializationObject.level = this.level;
  75205. serializationObject.size = this._size;
  75206. serializationObject.coordinatesMode = this.coordinatesMode;
  75207. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75208. serializationObject.generateHarmonics = this._generateHarmonics;
  75209. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75210. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75211. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75212. serializationObject.noMipmap = this._noMipmap;
  75213. serializationObject.isBlocking = this._isBlocking;
  75214. return serializationObject;
  75215. };
  75216. /**
  75217. * Saves as a file the data contained in the texture in a binary format.
  75218. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75219. * as the spherical used in the lighting.
  75220. * @param url The HDR file url.
  75221. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75222. * @param onError Method called if any error happens during download.
  75223. * @return The packed binary data.
  75224. */
  75225. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75226. if (onError === void 0) { onError = null; }
  75227. var callback = function (buffer) {
  75228. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75229. // Returns a URL you can use as a href.
  75230. var objUrl = window.URL.createObjectURL(data);
  75231. // Simulates a link to it and click to dowload.
  75232. var a = document.createElement("a");
  75233. document.body.appendChild(a);
  75234. a.style.display = "none";
  75235. a.href = objUrl;
  75236. a.download = "envmap.babylon.hdr";
  75237. a.click();
  75238. };
  75239. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75240. };
  75241. /**
  75242. * Serializes the data contained in the texture in a binary format.
  75243. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75244. * as the spherical used in the lighting.
  75245. * @param url The HDR file url.
  75246. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75247. * @param onError Method called if any error happens during download.
  75248. * @return The packed binary data.
  75249. */
  75250. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75251. if (onError === void 0) { onError = null; }
  75252. // Needs the url tho create the texture.
  75253. if (!url) {
  75254. return;
  75255. }
  75256. // Check Power of two size.
  75257. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75258. return;
  75259. }
  75260. // Coming Back in 3.x.
  75261. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75262. };
  75263. HDRCubeTexture._facesMapping = [
  75264. "right",
  75265. "left",
  75266. "up",
  75267. "down",
  75268. "front",
  75269. "back"
  75270. ];
  75271. return HDRCubeTexture;
  75272. }(BABYLON.BaseTexture));
  75273. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75274. })(BABYLON || (BABYLON = {}));
  75275. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75276. "use strict";
  75277. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75278. // Huge respect for a such great lib.
  75279. // Earcut license:
  75280. // Copyright (c) 2016, Mapbox
  75281. //
  75282. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75283. // with or without fee is hereby granted, provided that the above copyright notice
  75284. // and this permission notice appear in all copies.
  75285. //
  75286. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75287. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75288. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75289. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75290. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75291. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75292. // THIS SOFTWARE.
  75293. var Earcut;
  75294. (function (Earcut) {
  75295. /**
  75296. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75297. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75298. * @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).
  75299. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75300. */
  75301. function earcut(data, holeIndices, dim) {
  75302. dim = dim || 2;
  75303. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75304. if (!outerNode)
  75305. return triangles;
  75306. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75307. if (hasHoles)
  75308. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75309. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75310. if (data.length > 80 * dim) {
  75311. minX = maxX = data[0];
  75312. minY = maxY = data[1];
  75313. for (var i = dim; i < outerLen; i += dim) {
  75314. x = data[i];
  75315. y = data[i + 1];
  75316. if (x < minX)
  75317. minX = x;
  75318. if (y < minY)
  75319. minY = y;
  75320. if (x > maxX)
  75321. maxX = x;
  75322. if (y > maxY)
  75323. maxY = y;
  75324. }
  75325. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75326. size = Math.max(maxX - minX, maxY - minY);
  75327. }
  75328. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75329. return triangles;
  75330. }
  75331. Earcut.earcut = earcut;
  75332. var Node = /** @class */ (function () {
  75333. function Node(i, x, y) {
  75334. this.i = i;
  75335. this.x = x;
  75336. this.y = y;
  75337. this.prev = null;
  75338. this.next = null;
  75339. this.z = null;
  75340. this.prevZ = null;
  75341. this.nextZ = null;
  75342. this.steiner = false;
  75343. }
  75344. return Node;
  75345. }());
  75346. // create a circular doubly linked list from polygon points in the specified winding order
  75347. function linkedList(data, start, end, dim, clockwise) {
  75348. var i, last = null;
  75349. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75350. for (i = start; i < end; i += dim)
  75351. last = insertNode(i, data[i], data[i + 1], last);
  75352. }
  75353. else {
  75354. for (i = end - dim; i >= start; i -= dim)
  75355. last = insertNode(i, data[i], data[i + 1], last);
  75356. }
  75357. if (last && equals(last, last.next)) {
  75358. removeNode(last);
  75359. last = last.next;
  75360. }
  75361. return last;
  75362. }
  75363. // eliminate colinear or duplicate points
  75364. function filterPoints(start, end) {
  75365. if (!start)
  75366. return start;
  75367. if (!end)
  75368. end = start;
  75369. var p = start, again;
  75370. do {
  75371. again = false;
  75372. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75373. removeNode(p);
  75374. p = end = p.prev;
  75375. if (p === p.next)
  75376. return undefined;
  75377. again = true;
  75378. }
  75379. else {
  75380. p = p.next;
  75381. }
  75382. } while (again || p !== end);
  75383. return end;
  75384. }
  75385. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75386. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75387. if (!ear)
  75388. return;
  75389. // interlink polygon nodes in z-order
  75390. if (!pass && size)
  75391. indexCurve(ear, minX, minY, size);
  75392. var stop = ear, prev, next;
  75393. // iterate through ears, slicing them one by one
  75394. while (ear.prev !== ear.next) {
  75395. prev = ear.prev;
  75396. next = ear.next;
  75397. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75398. // cut off the triangle
  75399. triangles.push(prev.i / dim);
  75400. triangles.push(ear.i / dim);
  75401. triangles.push(next.i / dim);
  75402. removeNode(ear);
  75403. // skipping the next vertice leads to less sliver triangles
  75404. ear = next.next;
  75405. stop = next.next;
  75406. continue;
  75407. }
  75408. ear = next;
  75409. // if we looped through the whole remaining polygon and can't find any more ears
  75410. if (ear === stop) {
  75411. // try filtering points and slicing again
  75412. if (!pass) {
  75413. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75414. // if this didn't work, try curing all small self-intersections locally
  75415. }
  75416. else if (pass === 1) {
  75417. ear = cureLocalIntersections(ear, triangles, dim);
  75418. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75419. // as a last resort, try splitting the remaining polygon into two
  75420. }
  75421. else if (pass === 2) {
  75422. splitEarcut(ear, triangles, dim, minX, minY, size);
  75423. }
  75424. break;
  75425. }
  75426. }
  75427. }
  75428. // check whether a polygon node forms a valid ear with adjacent nodes
  75429. function isEar(ear) {
  75430. var a = ear.prev, b = ear, c = ear.next;
  75431. if (area(a, b, c) >= 0)
  75432. return false; // reflex, can't be an ear
  75433. // now make sure we don't have other points inside the potential ear
  75434. var p = ear.next.next;
  75435. while (p !== ear.prev) {
  75436. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75437. area(p.prev, p, p.next) >= 0)
  75438. return false;
  75439. p = p.next;
  75440. }
  75441. return true;
  75442. }
  75443. function isEarHashed(ear, minX, minY, size) {
  75444. var a = ear.prev, b = ear, c = ear.next;
  75445. if (area(a, b, c) >= 0)
  75446. return false; // reflex, can't be an ear
  75447. // triangle bbox; min & max are calculated like this for speed
  75448. 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);
  75449. // z-order range for the current triangle bbox;
  75450. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75451. // first look for points inside the triangle in increasing z-order
  75452. var p = ear.nextZ;
  75453. while (p && p.z <= maxZ) {
  75454. if (p !== ear.prev &&
  75455. p !== ear.next &&
  75456. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75457. area(p.prev, p, p.next) >= 0)
  75458. return false;
  75459. p = p.nextZ;
  75460. }
  75461. // then look for points in decreasing z-order
  75462. p = ear.prevZ;
  75463. while (p && p.z >= minZ) {
  75464. if (p !== ear.prev &&
  75465. p !== ear.next &&
  75466. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75467. area(p.prev, p, p.next) >= 0)
  75468. return false;
  75469. p = p.prevZ;
  75470. }
  75471. return true;
  75472. }
  75473. // go through all polygon nodes and cure small local self-intersections
  75474. function cureLocalIntersections(start, triangles, dim) {
  75475. var p = start;
  75476. do {
  75477. var a = p.prev, b = p.next.next;
  75478. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75479. triangles.push(a.i / dim);
  75480. triangles.push(p.i / dim);
  75481. triangles.push(b.i / dim);
  75482. // remove two nodes involved
  75483. removeNode(p);
  75484. removeNode(p.next);
  75485. p = start = b;
  75486. }
  75487. p = p.next;
  75488. } while (p !== start);
  75489. return p;
  75490. }
  75491. // try splitting polygon into two and triangulate them independently
  75492. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75493. // look for a valid diagonal that divides the polygon into two
  75494. var a = start;
  75495. do {
  75496. var b = a.next.next;
  75497. while (b !== a.prev) {
  75498. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75499. // split the polygon in two by the diagonal
  75500. var c = splitPolygon(a, b);
  75501. // filter colinear points around the cuts
  75502. a = filterPoints(a, a.next);
  75503. c = filterPoints(c, c.next);
  75504. // run earcut on each half
  75505. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75506. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75507. return;
  75508. }
  75509. b = b.next;
  75510. }
  75511. a = a.next;
  75512. } while (a !== start);
  75513. }
  75514. // link every hole into the outer loop, producing a single-ring polygon without holes
  75515. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75516. var queue = [], i, len, start, end, list;
  75517. for (i = 0, len = holeIndices.length; i < len; i++) {
  75518. start = holeIndices[i] * dim;
  75519. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75520. list = linkedList(data, start, end, dim, false);
  75521. if (list === list.next)
  75522. list.steiner = true;
  75523. queue.push(getLeftmost(list));
  75524. }
  75525. queue.sort(compareX);
  75526. // process holes from left to right
  75527. for (i = 0; i < queue.length; i++) {
  75528. eliminateHole(queue[i], outerNode);
  75529. outerNode = filterPoints(outerNode, outerNode.next);
  75530. }
  75531. return outerNode;
  75532. }
  75533. function compareX(a, b) {
  75534. return a.x - b.x;
  75535. }
  75536. // find a bridge between vertices that connects hole with an outer ring and and link it
  75537. function eliminateHole(hole, outerNode) {
  75538. outerNode = findHoleBridge(hole, outerNode);
  75539. if (outerNode) {
  75540. var b = splitPolygon(outerNode, hole);
  75541. filterPoints(b, b.next);
  75542. }
  75543. }
  75544. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  75545. function findHoleBridge(hole, outerNode) {
  75546. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  75547. // find a segment intersected by a ray from the hole's leftmost point to the left;
  75548. // segment's endpoint with lesser x will be potential connection point
  75549. do {
  75550. if (hy <= p.y && hy >= p.next.y) {
  75551. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  75552. if (x <= hx && x > qx) {
  75553. qx = x;
  75554. if (x === hx) {
  75555. if (hy === p.y)
  75556. return p;
  75557. if (hy === p.next.y)
  75558. return p.next;
  75559. }
  75560. m = p.x < p.next.x ? p : p.next;
  75561. }
  75562. }
  75563. p = p.next;
  75564. } while (p !== outerNode);
  75565. if (!m)
  75566. return null;
  75567. if (hx === qx)
  75568. return m.prev; // hole touches outer segment; pick lower endpoint
  75569. // look for points inside the triangle of hole point, segment intersection and endpoint;
  75570. // if there are no points found, we have a valid connection;
  75571. // otherwise choose the point of the minimum angle with the ray as connection point
  75572. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  75573. p = m.next;
  75574. while (p !== stop) {
  75575. if (hx >= p.x &&
  75576. p.x >= mx &&
  75577. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  75578. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  75579. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  75580. m = p;
  75581. tanMin = tan;
  75582. }
  75583. }
  75584. p = p.next;
  75585. }
  75586. return m;
  75587. }
  75588. // interlink polygon nodes in z-order
  75589. function indexCurve(start, minX, minY, size) {
  75590. var p = start;
  75591. do {
  75592. if (p.z === null)
  75593. p.z = zOrder(p.x, p.y, minX, minY, size);
  75594. p.prevZ = p.prev;
  75595. p.nextZ = p.next;
  75596. p = p.next;
  75597. } while (p !== start);
  75598. p.prevZ.nextZ = null;
  75599. p.prevZ = null;
  75600. sortLinked(p);
  75601. }
  75602. // Simon Tatham's linked list merge sort algorithm
  75603. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  75604. function sortLinked(list) {
  75605. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  75606. do {
  75607. p = list;
  75608. list = null;
  75609. tail = null;
  75610. numMerges = 0;
  75611. while (p) {
  75612. numMerges++;
  75613. q = p;
  75614. pSize = 0;
  75615. for (i = 0; i < inSize; i++) {
  75616. pSize++;
  75617. q = q.nextZ;
  75618. if (!q)
  75619. break;
  75620. }
  75621. qSize = inSize;
  75622. while (pSize > 0 || (qSize > 0 && q)) {
  75623. if (pSize === 0) {
  75624. e = q;
  75625. q = q.nextZ;
  75626. qSize--;
  75627. }
  75628. else if (qSize === 0 || !q) {
  75629. e = p;
  75630. p = p.nextZ;
  75631. pSize--;
  75632. }
  75633. else if (p.z <= q.z) {
  75634. e = p;
  75635. p = p.nextZ;
  75636. pSize--;
  75637. }
  75638. else {
  75639. e = q;
  75640. q = q.nextZ;
  75641. qSize--;
  75642. }
  75643. if (tail)
  75644. tail.nextZ = e;
  75645. else
  75646. list = e;
  75647. e.prevZ = tail;
  75648. tail = e;
  75649. }
  75650. p = q;
  75651. }
  75652. tail.nextZ = null;
  75653. inSize *= 2;
  75654. } while (numMerges > 1);
  75655. return list;
  75656. }
  75657. // z-order of a point given coords and size of the data bounding box
  75658. function zOrder(x, y, minX, minY, size) {
  75659. // coords are transformed into non-negative 15-bit integer range
  75660. x = 32767 * (x - minX) / size;
  75661. y = 32767 * (y - minY) / size;
  75662. x = (x | (x << 8)) & 0x00FF00FF;
  75663. x = (x | (x << 4)) & 0x0F0F0F0F;
  75664. x = (x | (x << 2)) & 0x33333333;
  75665. x = (x | (x << 1)) & 0x55555555;
  75666. y = (y | (y << 8)) & 0x00FF00FF;
  75667. y = (y | (y << 4)) & 0x0F0F0F0F;
  75668. y = (y | (y << 2)) & 0x33333333;
  75669. y = (y | (y << 1)) & 0x55555555;
  75670. return x | (y << 1);
  75671. }
  75672. // find the leftmost node of a polygon ring
  75673. function getLeftmost(start) {
  75674. var p = start, leftmost = start;
  75675. do {
  75676. if (p.x < leftmost.x)
  75677. leftmost = p;
  75678. p = p.next;
  75679. } while (p !== start);
  75680. return leftmost;
  75681. }
  75682. // check if a point lies within a convex triangle
  75683. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  75684. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  75685. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  75686. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  75687. }
  75688. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  75689. function isValidDiagonal(a, b) {
  75690. return a.next.i !== b.i &&
  75691. a.prev.i !== b.i &&
  75692. !intersectsPolygon(a, b) &&
  75693. locallyInside(a, b) &&
  75694. locallyInside(b, a) &&
  75695. middleInside(a, b);
  75696. }
  75697. // signed area of a triangle
  75698. function area(p, q, r) {
  75699. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  75700. }
  75701. // check if two points are equal
  75702. function equals(p1, p2) {
  75703. return p1.x === p2.x && p1.y === p2.y;
  75704. }
  75705. // check if two segments intersect
  75706. function intersects(p1, q1, p2, q2) {
  75707. if ((equals(p1, q1) && equals(p2, q2)) ||
  75708. (equals(p1, q2) && equals(p2, q1)))
  75709. return true;
  75710. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  75711. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  75712. }
  75713. // check if a polygon diagonal intersects any polygon segments
  75714. function intersectsPolygon(a, b) {
  75715. var p = a;
  75716. do {
  75717. if (p.i !== a.i &&
  75718. p.next.i !== a.i &&
  75719. p.i !== b.i &&
  75720. p.next.i !== b.i &&
  75721. intersects(p, p.next, a, b))
  75722. return true;
  75723. p = p.next;
  75724. } while (p !== a);
  75725. return false;
  75726. }
  75727. // check if a polygon diagonal is locally inside the polygon
  75728. function locallyInside(a, b) {
  75729. return area(a.prev, a, a.next) < 0
  75730. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  75731. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  75732. }
  75733. // check if the middle point of a polygon diagonal is inside the polygon
  75734. function middleInside(a, b) {
  75735. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  75736. do {
  75737. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  75738. inside = !inside;
  75739. p = p.next;
  75740. } while (p !== a);
  75741. return inside;
  75742. }
  75743. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  75744. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  75745. function splitPolygon(a, b) {
  75746. 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;
  75747. a.next = b;
  75748. b.prev = a;
  75749. a2.next = an;
  75750. an.prev = a2;
  75751. b2.next = a2;
  75752. a2.prev = b2;
  75753. bp.next = b2;
  75754. b2.prev = bp;
  75755. return b2;
  75756. }
  75757. // create a node and optionally link it with previous one (in a circular doubly linked list)
  75758. function insertNode(i, x, y, last) {
  75759. var p = new Node(i, x, y);
  75760. if (!last) {
  75761. p.prev = p;
  75762. p.next = p;
  75763. }
  75764. else {
  75765. p.next = last.next;
  75766. p.prev = last;
  75767. last.next.prev = p;
  75768. last.next = p;
  75769. }
  75770. return p;
  75771. }
  75772. function removeNode(p) {
  75773. p.next.prev = p.prev;
  75774. p.prev.next = p.next;
  75775. if (p.prevZ)
  75776. p.prevZ.nextZ = p.nextZ;
  75777. if (p.nextZ)
  75778. p.nextZ.prevZ = p.prevZ;
  75779. }
  75780. /**
  75781. * return a percentage difference between the polygon area and its triangulation area;
  75782. * used to verify correctness of triangulation
  75783. */
  75784. function deviation(data, holeIndices, dim, triangles) {
  75785. var hasHoles = holeIndices && holeIndices.length;
  75786. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  75787. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  75788. if (hasHoles) {
  75789. for (var i = 0, len = holeIndices.length; i < len; i++) {
  75790. var start = holeIndices[i] * dim;
  75791. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75792. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  75793. }
  75794. }
  75795. var trianglesArea = 0;
  75796. for (i = 0; i < triangles.length; i += 3) {
  75797. var a = triangles[i] * dim;
  75798. var b = triangles[i + 1] * dim;
  75799. var c = triangles[i + 2] * dim;
  75800. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  75801. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  75802. }
  75803. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  75804. }
  75805. Earcut.deviation = deviation;
  75806. ;
  75807. function signedArea(data, start, end, dim) {
  75808. var sum = 0;
  75809. for (var i = start, j = end - dim; i < end; i += dim) {
  75810. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  75811. j = i;
  75812. }
  75813. return sum;
  75814. }
  75815. /**
  75816. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  75817. */
  75818. function flatten(data) {
  75819. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  75820. for (var i = 0; i < data.length; i++) {
  75821. for (var j = 0; j < data[i].length; j++) {
  75822. for (var d = 0; d < dim; d++)
  75823. result.vertices.push(data[i][j][d]);
  75824. }
  75825. if (i > 0) {
  75826. holeIndex += data[i - 1].length;
  75827. result.holes.push(holeIndex);
  75828. }
  75829. }
  75830. return result;
  75831. }
  75832. Earcut.flatten = flatten;
  75833. ;
  75834. })(Earcut || (Earcut = {}));
  75835. //# sourceMappingURL=babylon.earcut.js.map
  75836. "use strict";
  75837. var BABYLON;
  75838. (function (BABYLON) {
  75839. var IndexedVector2 = /** @class */ (function (_super) {
  75840. __extends(IndexedVector2, _super);
  75841. function IndexedVector2(original, index) {
  75842. var _this = _super.call(this, original.x, original.y) || this;
  75843. _this.index = index;
  75844. return _this;
  75845. }
  75846. return IndexedVector2;
  75847. }(BABYLON.Vector2));
  75848. var PolygonPoints = /** @class */ (function () {
  75849. function PolygonPoints() {
  75850. this.elements = new Array();
  75851. }
  75852. PolygonPoints.prototype.add = function (originalPoints) {
  75853. var _this = this;
  75854. var result = new Array();
  75855. originalPoints.forEach(function (point) {
  75856. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75857. var newPoint = new IndexedVector2(point, _this.elements.length);
  75858. result.push(newPoint);
  75859. _this.elements.push(newPoint);
  75860. }
  75861. });
  75862. return result;
  75863. };
  75864. PolygonPoints.prototype.computeBounds = function () {
  75865. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75866. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75867. this.elements.forEach(function (point) {
  75868. // x
  75869. if (point.x < lmin.x) {
  75870. lmin.x = point.x;
  75871. }
  75872. else if (point.x > lmax.x) {
  75873. lmax.x = point.x;
  75874. }
  75875. // y
  75876. if (point.y < lmin.y) {
  75877. lmin.y = point.y;
  75878. }
  75879. else if (point.y > lmax.y) {
  75880. lmax.y = point.y;
  75881. }
  75882. });
  75883. return {
  75884. min: lmin,
  75885. max: lmax,
  75886. width: lmax.x - lmin.x,
  75887. height: lmax.y - lmin.y
  75888. };
  75889. };
  75890. return PolygonPoints;
  75891. }());
  75892. var Polygon = /** @class */ (function () {
  75893. function Polygon() {
  75894. }
  75895. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75896. return [
  75897. new BABYLON.Vector2(xmin, ymin),
  75898. new BABYLON.Vector2(xmax, ymin),
  75899. new BABYLON.Vector2(xmax, ymax),
  75900. new BABYLON.Vector2(xmin, ymax)
  75901. ];
  75902. };
  75903. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75904. if (cx === void 0) { cx = 0; }
  75905. if (cy === void 0) { cy = 0; }
  75906. if (numberOfSides === void 0) { numberOfSides = 32; }
  75907. var result = new Array();
  75908. var angle = 0;
  75909. var increment = (Math.PI * 2) / numberOfSides;
  75910. for (var i = 0; i < numberOfSides; i++) {
  75911. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75912. angle -= increment;
  75913. }
  75914. return result;
  75915. };
  75916. Polygon.Parse = function (input) {
  75917. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75918. var i, result = [];
  75919. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75920. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75921. }
  75922. return result;
  75923. };
  75924. Polygon.StartingAt = function (x, y) {
  75925. return BABYLON.Path2.StartingAt(x, y);
  75926. };
  75927. return Polygon;
  75928. }());
  75929. BABYLON.Polygon = Polygon;
  75930. var PolygonMeshBuilder = /** @class */ (function () {
  75931. function PolygonMeshBuilder(name, contours, scene) {
  75932. this._points = new PolygonPoints();
  75933. this._outlinepoints = new PolygonPoints();
  75934. this._holes = new Array();
  75935. this._epoints = new Array();
  75936. this._eholes = new Array();
  75937. this._name = name;
  75938. this._scene = scene;
  75939. var points;
  75940. if (contours instanceof BABYLON.Path2) {
  75941. points = contours.getPoints();
  75942. }
  75943. else {
  75944. points = contours;
  75945. }
  75946. this._addToepoint(points);
  75947. this._points.add(points);
  75948. this._outlinepoints.add(points);
  75949. }
  75950. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75951. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75952. var p = points_1[_i];
  75953. this._epoints.push(p.x, p.y);
  75954. }
  75955. };
  75956. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75957. this._points.add(hole);
  75958. var holepoints = new PolygonPoints();
  75959. holepoints.add(hole);
  75960. this._holes.push(holepoints);
  75961. this._eholes.push(this._epoints.length / 2);
  75962. this._addToepoint(hole);
  75963. return this;
  75964. };
  75965. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75966. var _this = this;
  75967. if (updatable === void 0) { updatable = false; }
  75968. if (depth === void 0) { depth = 0; }
  75969. var result = new BABYLON.Mesh(this._name, this._scene);
  75970. var normals = new Array();
  75971. var positions = new Array();
  75972. var uvs = new Array();
  75973. var bounds = this._points.computeBounds();
  75974. this._points.elements.forEach(function (p) {
  75975. normals.push(0, 1.0, 0);
  75976. positions.push(p.x, 0, p.y);
  75977. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75978. });
  75979. var indices = new Array();
  75980. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75981. for (var i = 0; i < res.length; i++) {
  75982. indices.push(res[i]);
  75983. }
  75984. if (depth > 0) {
  75985. var positionscount = (positions.length / 3); //get the current pointcount
  75986. this._points.elements.forEach(function (p) {
  75987. normals.push(0, -1.0, 0);
  75988. positions.push(p.x, -depth, p.y);
  75989. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75990. });
  75991. var totalCount = indices.length;
  75992. for (var i = 0; i < totalCount; i += 3) {
  75993. var i0 = indices[i + 0];
  75994. var i1 = indices[i + 1];
  75995. var i2 = indices[i + 2];
  75996. indices.push(i2 + positionscount);
  75997. indices.push(i1 + positionscount);
  75998. indices.push(i0 + positionscount);
  75999. }
  76000. //Add the sides
  76001. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  76002. this._holes.forEach(function (hole) {
  76003. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  76004. });
  76005. }
  76006. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  76007. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  76008. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  76009. result.setIndices(indices);
  76010. return result;
  76011. };
  76012. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  76013. var StartIndex = positions.length / 3;
  76014. var ulength = 0;
  76015. for (var i = 0; i < points.elements.length; i++) {
  76016. var p = points.elements[i];
  76017. var p1;
  76018. if ((i + 1) > points.elements.length - 1) {
  76019. p1 = points.elements[0];
  76020. }
  76021. else {
  76022. p1 = points.elements[i + 1];
  76023. }
  76024. positions.push(p.x, 0, p.y);
  76025. positions.push(p.x, -depth, p.y);
  76026. positions.push(p1.x, 0, p1.y);
  76027. positions.push(p1.x, -depth, p1.y);
  76028. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76029. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76030. var v3 = v2.subtract(v1);
  76031. var v4 = new BABYLON.Vector3(0, 1, 0);
  76032. var vn = BABYLON.Vector3.Cross(v3, v4);
  76033. vn = vn.normalize();
  76034. uvs.push(ulength / bounds.width, 0);
  76035. uvs.push(ulength / bounds.width, 1);
  76036. ulength += v3.length();
  76037. uvs.push((ulength / bounds.width), 0);
  76038. uvs.push((ulength / bounds.width), 1);
  76039. if (!flip) {
  76040. normals.push(-vn.x, -vn.y, -vn.z);
  76041. normals.push(-vn.x, -vn.y, -vn.z);
  76042. normals.push(-vn.x, -vn.y, -vn.z);
  76043. normals.push(-vn.x, -vn.y, -vn.z);
  76044. indices.push(StartIndex);
  76045. indices.push(StartIndex + 1);
  76046. indices.push(StartIndex + 2);
  76047. indices.push(StartIndex + 1);
  76048. indices.push(StartIndex + 3);
  76049. indices.push(StartIndex + 2);
  76050. }
  76051. else {
  76052. normals.push(vn.x, vn.y, vn.z);
  76053. normals.push(vn.x, vn.y, vn.z);
  76054. normals.push(vn.x, vn.y, vn.z);
  76055. normals.push(vn.x, vn.y, vn.z);
  76056. indices.push(StartIndex);
  76057. indices.push(StartIndex + 2);
  76058. indices.push(StartIndex + 1);
  76059. indices.push(StartIndex + 1);
  76060. indices.push(StartIndex + 2);
  76061. indices.push(StartIndex + 3);
  76062. }
  76063. StartIndex += 4;
  76064. }
  76065. ;
  76066. };
  76067. return PolygonMeshBuilder;
  76068. }());
  76069. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76070. })(BABYLON || (BABYLON = {}));
  76071. //# sourceMappingURL=babylon.polygonMesh.js.map
  76072. "use strict";
  76073. var BABYLON;
  76074. (function (BABYLON) {
  76075. // Unique ID when we import meshes from Babylon to CSG
  76076. var currentCSGMeshId = 0;
  76077. // # class Vertex
  76078. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76079. // one to provide additional features like texture coordinates and vertex
  76080. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76081. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76082. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76083. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76084. // is not used anywhere else.
  76085. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76086. var Vertex = /** @class */ (function () {
  76087. function Vertex(pos, normal, uv) {
  76088. this.pos = pos;
  76089. this.normal = normal;
  76090. this.uv = uv;
  76091. }
  76092. Vertex.prototype.clone = function () {
  76093. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76094. };
  76095. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76096. // orientation of a polygon is flipped.
  76097. Vertex.prototype.flip = function () {
  76098. this.normal = this.normal.scale(-1);
  76099. };
  76100. // Create a new vertex between this vertex and `other` by linearly
  76101. // interpolating all properties using a parameter of `t`. Subclasses should
  76102. // override this to interpolate additional properties.
  76103. Vertex.prototype.interpolate = function (other, t) {
  76104. 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));
  76105. };
  76106. return Vertex;
  76107. }());
  76108. // # class Plane
  76109. // Represents a plane in 3D space.
  76110. var Plane = /** @class */ (function () {
  76111. function Plane(normal, w) {
  76112. this.normal = normal;
  76113. this.w = w;
  76114. }
  76115. Plane.FromPoints = function (a, b, c) {
  76116. var v0 = c.subtract(a);
  76117. var v1 = b.subtract(a);
  76118. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76119. return null;
  76120. }
  76121. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76122. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76123. };
  76124. Plane.prototype.clone = function () {
  76125. return new Plane(this.normal.clone(), this.w);
  76126. };
  76127. Plane.prototype.flip = function () {
  76128. this.normal.scaleInPlace(-1);
  76129. this.w = -this.w;
  76130. };
  76131. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76132. // fragments in the appropriate lists. Coplanar polygons go into either
  76133. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76134. // respect to this plane. Polygons in front or in back of this plane go into
  76135. // either `front` or `back`.
  76136. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76137. var COPLANAR = 0;
  76138. var FRONT = 1;
  76139. var BACK = 2;
  76140. var SPANNING = 3;
  76141. // Classify each point as well as the entire polygon into one of the above
  76142. // four classes.
  76143. var polygonType = 0;
  76144. var types = [];
  76145. var i;
  76146. var t;
  76147. for (i = 0; i < polygon.vertices.length; i++) {
  76148. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76149. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76150. polygonType |= type;
  76151. types.push(type);
  76152. }
  76153. // Put the polygon in the correct list, splitting it when necessary.
  76154. switch (polygonType) {
  76155. case COPLANAR:
  76156. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76157. break;
  76158. case FRONT:
  76159. front.push(polygon);
  76160. break;
  76161. case BACK:
  76162. back.push(polygon);
  76163. break;
  76164. case SPANNING:
  76165. var f = [], b = [];
  76166. for (i = 0; i < polygon.vertices.length; i++) {
  76167. var j = (i + 1) % polygon.vertices.length;
  76168. var ti = types[i], tj = types[j];
  76169. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76170. if (ti !== BACK)
  76171. f.push(vi);
  76172. if (ti !== FRONT)
  76173. b.push(ti !== BACK ? vi.clone() : vi);
  76174. if ((ti | tj) === SPANNING) {
  76175. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76176. var v = vi.interpolate(vj, t);
  76177. f.push(v);
  76178. b.push(v.clone());
  76179. }
  76180. }
  76181. var poly;
  76182. if (f.length >= 3) {
  76183. poly = new Polygon(f, polygon.shared);
  76184. if (poly.plane)
  76185. front.push(poly);
  76186. }
  76187. if (b.length >= 3) {
  76188. poly = new Polygon(b, polygon.shared);
  76189. if (poly.plane)
  76190. back.push(poly);
  76191. }
  76192. break;
  76193. }
  76194. };
  76195. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76196. // point is on the plane.
  76197. Plane.EPSILON = 1e-5;
  76198. return Plane;
  76199. }());
  76200. // # class Polygon
  76201. // Represents a convex polygon. The vertices used to initialize a polygon must
  76202. // be coplanar and form a convex loop.
  76203. //
  76204. // Each convex polygon has a `shared` property, which is shared between all
  76205. // polygons that are clones of each other or were split from the same polygon.
  76206. // This can be used to define per-polygon properties (such as surface color).
  76207. var Polygon = /** @class */ (function () {
  76208. function Polygon(vertices, shared) {
  76209. this.vertices = vertices;
  76210. this.shared = shared;
  76211. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76212. }
  76213. Polygon.prototype.clone = function () {
  76214. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76215. return new Polygon(vertices, this.shared);
  76216. };
  76217. Polygon.prototype.flip = function () {
  76218. this.vertices.reverse().map(function (v) { v.flip(); });
  76219. this.plane.flip();
  76220. };
  76221. return Polygon;
  76222. }());
  76223. // # class Node
  76224. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76225. // by picking a polygon to split along. That polygon (and all other coplanar
  76226. // polygons) are added directly to that node and the other polygons are added to
  76227. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76228. // no distinction between internal and leaf nodes.
  76229. var Node = /** @class */ (function () {
  76230. function Node(polygons) {
  76231. this.plane = null;
  76232. this.front = null;
  76233. this.back = null;
  76234. this.polygons = new Array();
  76235. if (polygons) {
  76236. this.build(polygons);
  76237. }
  76238. }
  76239. Node.prototype.clone = function () {
  76240. var node = new Node();
  76241. node.plane = this.plane && this.plane.clone();
  76242. node.front = this.front && this.front.clone();
  76243. node.back = this.back && this.back.clone();
  76244. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76245. return node;
  76246. };
  76247. // Convert solid space to empty space and empty space to solid space.
  76248. Node.prototype.invert = function () {
  76249. for (var i = 0; i < this.polygons.length; i++) {
  76250. this.polygons[i].flip();
  76251. }
  76252. if (this.plane) {
  76253. this.plane.flip();
  76254. }
  76255. if (this.front) {
  76256. this.front.invert();
  76257. }
  76258. if (this.back) {
  76259. this.back.invert();
  76260. }
  76261. var temp = this.front;
  76262. this.front = this.back;
  76263. this.back = temp;
  76264. };
  76265. // Recursively remove all polygons in `polygons` that are inside this BSP
  76266. // tree.
  76267. Node.prototype.clipPolygons = function (polygons) {
  76268. if (!this.plane)
  76269. return polygons.slice();
  76270. var front = new Array(), back = new Array();
  76271. for (var i = 0; i < polygons.length; i++) {
  76272. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76273. }
  76274. if (this.front) {
  76275. front = this.front.clipPolygons(front);
  76276. }
  76277. if (this.back) {
  76278. back = this.back.clipPolygons(back);
  76279. }
  76280. else {
  76281. back = [];
  76282. }
  76283. return front.concat(back);
  76284. };
  76285. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76286. // `bsp`.
  76287. Node.prototype.clipTo = function (bsp) {
  76288. this.polygons = bsp.clipPolygons(this.polygons);
  76289. if (this.front)
  76290. this.front.clipTo(bsp);
  76291. if (this.back)
  76292. this.back.clipTo(bsp);
  76293. };
  76294. // Return a list of all polygons in this BSP tree.
  76295. Node.prototype.allPolygons = function () {
  76296. var polygons = this.polygons.slice();
  76297. if (this.front)
  76298. polygons = polygons.concat(this.front.allPolygons());
  76299. if (this.back)
  76300. polygons = polygons.concat(this.back.allPolygons());
  76301. return polygons;
  76302. };
  76303. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76304. // new polygons are filtered down to the bottom of the tree and become new
  76305. // nodes there. Each set of polygons is partitioned using the first polygon
  76306. // (no heuristic is used to pick a good split).
  76307. Node.prototype.build = function (polygons) {
  76308. if (!polygons.length)
  76309. return;
  76310. if (!this.plane)
  76311. this.plane = polygons[0].plane.clone();
  76312. var front = new Array(), back = new Array();
  76313. for (var i = 0; i < polygons.length; i++) {
  76314. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76315. }
  76316. if (front.length) {
  76317. if (!this.front)
  76318. this.front = new Node();
  76319. this.front.build(front);
  76320. }
  76321. if (back.length) {
  76322. if (!this.back)
  76323. this.back = new Node();
  76324. this.back.build(back);
  76325. }
  76326. };
  76327. return Node;
  76328. }());
  76329. var CSG = /** @class */ (function () {
  76330. function CSG() {
  76331. this.polygons = new Array();
  76332. }
  76333. // Convert BABYLON.Mesh to BABYLON.CSG
  76334. CSG.FromMesh = function (mesh) {
  76335. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76336. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76337. if (mesh instanceof BABYLON.Mesh) {
  76338. mesh.computeWorldMatrix(true);
  76339. matrix = mesh.getWorldMatrix();
  76340. meshPosition = mesh.position.clone();
  76341. meshRotation = mesh.rotation.clone();
  76342. if (mesh.rotationQuaternion) {
  76343. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76344. }
  76345. meshScaling = mesh.scaling.clone();
  76346. }
  76347. else {
  76348. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76349. }
  76350. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76351. var subMeshes = mesh.subMeshes;
  76352. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76353. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76354. vertices = [];
  76355. for (var j = 0; j < 3; j++) {
  76356. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76357. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76358. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76359. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76360. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76361. vertex = new Vertex(position, normal, uv);
  76362. vertices.push(vertex);
  76363. }
  76364. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76365. // To handle the case of degenerated triangle
  76366. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76367. if (polygon.plane)
  76368. polygons.push(polygon);
  76369. }
  76370. }
  76371. var csg = CSG.FromPolygons(polygons);
  76372. csg.matrix = matrix;
  76373. csg.position = meshPosition;
  76374. csg.rotation = meshRotation;
  76375. csg.scaling = meshScaling;
  76376. csg.rotationQuaternion = meshRotationQuaternion;
  76377. currentCSGMeshId++;
  76378. return csg;
  76379. };
  76380. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76381. CSG.FromPolygons = function (polygons) {
  76382. var csg = new CSG();
  76383. csg.polygons = polygons;
  76384. return csg;
  76385. };
  76386. CSG.prototype.clone = function () {
  76387. var csg = new CSG();
  76388. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76389. csg.copyTransformAttributes(this);
  76390. return csg;
  76391. };
  76392. CSG.prototype.union = function (csg) {
  76393. var a = new Node(this.clone().polygons);
  76394. var b = new Node(csg.clone().polygons);
  76395. a.clipTo(b);
  76396. b.clipTo(a);
  76397. b.invert();
  76398. b.clipTo(a);
  76399. b.invert();
  76400. a.build(b.allPolygons());
  76401. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76402. };
  76403. CSG.prototype.unionInPlace = function (csg) {
  76404. var a = new Node(this.polygons);
  76405. var b = new Node(csg.polygons);
  76406. a.clipTo(b);
  76407. b.clipTo(a);
  76408. b.invert();
  76409. b.clipTo(a);
  76410. b.invert();
  76411. a.build(b.allPolygons());
  76412. this.polygons = a.allPolygons();
  76413. };
  76414. CSG.prototype.subtract = function (csg) {
  76415. var a = new Node(this.clone().polygons);
  76416. var b = new Node(csg.clone().polygons);
  76417. a.invert();
  76418. a.clipTo(b);
  76419. b.clipTo(a);
  76420. b.invert();
  76421. b.clipTo(a);
  76422. b.invert();
  76423. a.build(b.allPolygons());
  76424. a.invert();
  76425. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76426. };
  76427. CSG.prototype.subtractInPlace = function (csg) {
  76428. var a = new Node(this.polygons);
  76429. var b = new Node(csg.polygons);
  76430. a.invert();
  76431. a.clipTo(b);
  76432. b.clipTo(a);
  76433. b.invert();
  76434. b.clipTo(a);
  76435. b.invert();
  76436. a.build(b.allPolygons());
  76437. a.invert();
  76438. this.polygons = a.allPolygons();
  76439. };
  76440. CSG.prototype.intersect = function (csg) {
  76441. var a = new Node(this.clone().polygons);
  76442. var b = new Node(csg.clone().polygons);
  76443. a.invert();
  76444. b.clipTo(a);
  76445. b.invert();
  76446. a.clipTo(b);
  76447. b.clipTo(a);
  76448. a.build(b.allPolygons());
  76449. a.invert();
  76450. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76451. };
  76452. CSG.prototype.intersectInPlace = function (csg) {
  76453. var a = new Node(this.polygons);
  76454. var b = new Node(csg.polygons);
  76455. a.invert();
  76456. b.clipTo(a);
  76457. b.invert();
  76458. a.clipTo(b);
  76459. b.clipTo(a);
  76460. a.build(b.allPolygons());
  76461. a.invert();
  76462. this.polygons = a.allPolygons();
  76463. };
  76464. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76465. // not modified.
  76466. CSG.prototype.inverse = function () {
  76467. var csg = this.clone();
  76468. csg.inverseInPlace();
  76469. return csg;
  76470. };
  76471. CSG.prototype.inverseInPlace = function () {
  76472. this.polygons.map(function (p) { p.flip(); });
  76473. };
  76474. // This is used to keep meshes transformations so they can be restored
  76475. // when we build back a Babylon Mesh
  76476. // NB : All CSG operations are performed in world coordinates
  76477. CSG.prototype.copyTransformAttributes = function (csg) {
  76478. this.matrix = csg.matrix;
  76479. this.position = csg.position;
  76480. this.rotation = csg.rotation;
  76481. this.scaling = csg.scaling;
  76482. this.rotationQuaternion = csg.rotationQuaternion;
  76483. return this;
  76484. };
  76485. // Build Raw mesh from CSG
  76486. // Coordinates here are in world space
  76487. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76488. var matrix = this.matrix.clone();
  76489. matrix.invert();
  76490. 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;
  76491. if (keepSubMeshes) {
  76492. // Sort Polygons, since subMeshes are indices range
  76493. polygons.sort(function (a, b) {
  76494. if (a.shared.meshId === b.shared.meshId) {
  76495. return a.shared.subMeshId - b.shared.subMeshId;
  76496. }
  76497. else {
  76498. return a.shared.meshId - b.shared.meshId;
  76499. }
  76500. });
  76501. }
  76502. for (var i = 0, il = polygons.length; i < il; i++) {
  76503. polygon = polygons[i];
  76504. // Building SubMeshes
  76505. if (!subMesh_dict[polygon.shared.meshId]) {
  76506. subMesh_dict[polygon.shared.meshId] = {};
  76507. }
  76508. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76509. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76510. indexStart: +Infinity,
  76511. indexEnd: -Infinity,
  76512. materialIndex: polygon.shared.materialIndex
  76513. };
  76514. }
  76515. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76516. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76517. polygonIndices[0] = 0;
  76518. polygonIndices[1] = j - 1;
  76519. polygonIndices[2] = j;
  76520. for (var k = 0; k < 3; k++) {
  76521. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76522. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76523. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76524. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76525. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76526. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76527. // Check if 2 points can be merged
  76528. if (!(typeof vertex_idx !== 'undefined' &&
  76529. normals[vertex_idx * 3] === localNormal.x &&
  76530. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76531. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76532. uvs[vertex_idx * 2] === uv.x &&
  76533. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76534. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76535. uvs.push(uv.x, uv.y);
  76536. normals.push(normal.x, normal.y, normal.z);
  76537. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76538. }
  76539. indices.push(vertex_idx);
  76540. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76541. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76542. currentIndex++;
  76543. }
  76544. }
  76545. }
  76546. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76547. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76548. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76549. mesh.setIndices(indices, null);
  76550. if (keepSubMeshes) {
  76551. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76552. var materialIndexOffset = 0, materialMaxIndex;
  76553. mesh.subMeshes = new Array();
  76554. for (var m in subMesh_dict) {
  76555. materialMaxIndex = -1;
  76556. for (var sm in subMesh_dict[m]) {
  76557. subMesh_obj = subMesh_dict[m][sm];
  76558. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76559. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76560. }
  76561. materialIndexOffset += ++materialMaxIndex;
  76562. }
  76563. }
  76564. return mesh;
  76565. };
  76566. // Build Mesh from CSG taking material and transforms into account
  76567. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76568. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76569. mesh.material = material;
  76570. mesh.position.copyFrom(this.position);
  76571. mesh.rotation.copyFrom(this.rotation);
  76572. if (this.rotationQuaternion) {
  76573. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76574. }
  76575. mesh.scaling.copyFrom(this.scaling);
  76576. mesh.computeWorldMatrix(true);
  76577. return mesh;
  76578. };
  76579. return CSG;
  76580. }());
  76581. BABYLON.CSG = CSG;
  76582. })(BABYLON || (BABYLON = {}));
  76583. //# sourceMappingURL=babylon.csg.js.map
  76584. "use strict";
  76585. var BABYLON;
  76586. (function (BABYLON) {
  76587. var LensFlare = /** @class */ (function () {
  76588. function LensFlare(size, position, color, imgUrl, system) {
  76589. this.size = size;
  76590. this.position = position;
  76591. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76592. this.color = color || new BABYLON.Color3(1, 1, 1);
  76593. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76594. this._system = system;
  76595. system.lensFlares.push(this);
  76596. }
  76597. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76598. return new LensFlare(size, position, color, imgUrl, system);
  76599. };
  76600. LensFlare.prototype.dispose = function () {
  76601. if (this.texture) {
  76602. this.texture.dispose();
  76603. }
  76604. // Remove from scene
  76605. var index = this._system.lensFlares.indexOf(this);
  76606. this._system.lensFlares.splice(index, 1);
  76607. };
  76608. ;
  76609. return LensFlare;
  76610. }());
  76611. BABYLON.LensFlare = LensFlare;
  76612. })(BABYLON || (BABYLON = {}));
  76613. //# sourceMappingURL=babylon.lensFlare.js.map
  76614. "use strict";
  76615. var BABYLON;
  76616. (function (BABYLON) {
  76617. var LensFlareSystem = /** @class */ (function () {
  76618. function LensFlareSystem(name, emitter, scene) {
  76619. this.name = name;
  76620. this.lensFlares = new Array();
  76621. this.borderLimit = 300;
  76622. this.viewportBorder = 0;
  76623. this.layerMask = 0x0FFFFFFF;
  76624. this._vertexBuffers = {};
  76625. this._isEnabled = true;
  76626. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76627. this._emitter = emitter;
  76628. this.id = name;
  76629. scene.lensFlareSystems.push(this);
  76630. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76631. var engine = scene.getEngine();
  76632. // VBO
  76633. var vertices = [];
  76634. vertices.push(1, 1);
  76635. vertices.push(-1, 1);
  76636. vertices.push(-1, -1);
  76637. vertices.push(1, -1);
  76638. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76639. // Indices
  76640. var indices = [];
  76641. indices.push(0);
  76642. indices.push(1);
  76643. indices.push(2);
  76644. indices.push(0);
  76645. indices.push(2);
  76646. indices.push(3);
  76647. this._indexBuffer = engine.createIndexBuffer(indices);
  76648. // Effects
  76649. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76650. }
  76651. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76652. get: function () {
  76653. return this._isEnabled;
  76654. },
  76655. set: function (value) {
  76656. this._isEnabled = value;
  76657. },
  76658. enumerable: true,
  76659. configurable: true
  76660. });
  76661. LensFlareSystem.prototype.getScene = function () {
  76662. return this._scene;
  76663. };
  76664. LensFlareSystem.prototype.getEmitter = function () {
  76665. return this._emitter;
  76666. };
  76667. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76668. this._emitter = newEmitter;
  76669. };
  76670. LensFlareSystem.prototype.getEmitterPosition = function () {
  76671. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76672. };
  76673. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76674. var position = this.getEmitterPosition();
  76675. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76676. this._positionX = position.x;
  76677. this._positionY = position.y;
  76678. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76679. if (this.viewportBorder > 0) {
  76680. globalViewport.x -= this.viewportBorder;
  76681. globalViewport.y -= this.viewportBorder;
  76682. globalViewport.width += this.viewportBorder * 2;
  76683. globalViewport.height += this.viewportBorder * 2;
  76684. position.x += this.viewportBorder;
  76685. position.y += this.viewportBorder;
  76686. this._positionX += this.viewportBorder;
  76687. this._positionY += this.viewportBorder;
  76688. }
  76689. if (position.z > 0) {
  76690. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  76691. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76692. return true;
  76693. }
  76694. return true;
  76695. }
  76696. return false;
  76697. };
  76698. LensFlareSystem.prototype._isVisible = function () {
  76699. if (!this._isEnabled || !this._scene.activeCamera) {
  76700. return false;
  76701. }
  76702. var emitterPosition = this.getEmitterPosition();
  76703. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  76704. var distance = direction.length();
  76705. direction.normalize();
  76706. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  76707. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  76708. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  76709. };
  76710. LensFlareSystem.prototype.render = function () {
  76711. if (!this._effect.isReady() || !this._scene.activeCamera)
  76712. return false;
  76713. var engine = this._scene.getEngine();
  76714. var viewport = this._scene.activeCamera.viewport;
  76715. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  76716. // Position
  76717. if (!this.computeEffectivePosition(globalViewport)) {
  76718. return false;
  76719. }
  76720. // Visibility
  76721. if (!this._isVisible()) {
  76722. return false;
  76723. }
  76724. // Intensity
  76725. var awayX;
  76726. var awayY;
  76727. if (this._positionX < this.borderLimit + globalViewport.x) {
  76728. awayX = this.borderLimit + globalViewport.x - this._positionX;
  76729. }
  76730. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  76731. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  76732. }
  76733. else {
  76734. awayX = 0;
  76735. }
  76736. if (this._positionY < this.borderLimit + globalViewport.y) {
  76737. awayY = this.borderLimit + globalViewport.y - this._positionY;
  76738. }
  76739. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  76740. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  76741. }
  76742. else {
  76743. awayY = 0;
  76744. }
  76745. var away = (awayX > awayY) ? awayX : awayY;
  76746. away -= this.viewportBorder;
  76747. if (away > this.borderLimit) {
  76748. away = this.borderLimit;
  76749. }
  76750. var intensity = 1.0 - (away / this.borderLimit);
  76751. if (intensity < 0) {
  76752. return false;
  76753. }
  76754. if (intensity > 1.0) {
  76755. intensity = 1.0;
  76756. }
  76757. if (this.viewportBorder > 0) {
  76758. globalViewport.x += this.viewportBorder;
  76759. globalViewport.y += this.viewportBorder;
  76760. globalViewport.width -= this.viewportBorder * 2;
  76761. globalViewport.height -= this.viewportBorder * 2;
  76762. this._positionX -= this.viewportBorder;
  76763. this._positionY -= this.viewportBorder;
  76764. }
  76765. // Position
  76766. var centerX = globalViewport.x + globalViewport.width / 2;
  76767. var centerY = globalViewport.y + globalViewport.height / 2;
  76768. var distX = centerX - this._positionX;
  76769. var distY = centerY - this._positionY;
  76770. // Effects
  76771. engine.enableEffect(this._effect);
  76772. engine.setState(false);
  76773. engine.setDepthBuffer(false);
  76774. // VBOs
  76775. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76776. // Flares
  76777. for (var index = 0; index < this.lensFlares.length; index++) {
  76778. var flare = this.lensFlares[index];
  76779. engine.setAlphaMode(flare.alphaMode);
  76780. var x = centerX - (distX * flare.position);
  76781. var y = centerY - (distY * flare.position);
  76782. var cw = flare.size;
  76783. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76784. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76785. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76786. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76787. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76788. // Texture
  76789. this._effect.setTexture("textureSampler", flare.texture);
  76790. // Color
  76791. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76792. // Draw order
  76793. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76794. }
  76795. engine.setDepthBuffer(true);
  76796. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76797. return true;
  76798. };
  76799. LensFlareSystem.prototype.dispose = function () {
  76800. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76801. if (vertexBuffer) {
  76802. vertexBuffer.dispose();
  76803. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76804. }
  76805. if (this._indexBuffer) {
  76806. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76807. this._indexBuffer = null;
  76808. }
  76809. while (this.lensFlares.length) {
  76810. this.lensFlares[0].dispose();
  76811. }
  76812. // Remove from scene
  76813. var index = this._scene.lensFlareSystems.indexOf(this);
  76814. this._scene.lensFlareSystems.splice(index, 1);
  76815. };
  76816. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76817. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76818. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76819. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76820. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76821. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76822. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76823. var parsedFlare = parsedLensFlareSystem.flares[index];
  76824. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76825. }
  76826. return lensFlareSystem;
  76827. };
  76828. LensFlareSystem.prototype.serialize = function () {
  76829. var serializationObject = {};
  76830. serializationObject.id = this.id;
  76831. serializationObject.name = this.name;
  76832. serializationObject.emitterId = this.getEmitter().id;
  76833. serializationObject.borderLimit = this.borderLimit;
  76834. serializationObject.flares = [];
  76835. for (var index = 0; index < this.lensFlares.length; index++) {
  76836. var flare = this.lensFlares[index];
  76837. serializationObject.flares.push({
  76838. size: flare.size,
  76839. position: flare.position,
  76840. color: flare.color.asArray(),
  76841. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76842. });
  76843. }
  76844. return serializationObject;
  76845. };
  76846. return LensFlareSystem;
  76847. }());
  76848. BABYLON.LensFlareSystem = LensFlareSystem;
  76849. })(BABYLON || (BABYLON = {}));
  76850. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76851. "use strict";
  76852. var BABYLON;
  76853. (function (BABYLON) {
  76854. /**
  76855. * This is a holder class for the physics joint created by the physics plugin.
  76856. * It holds a set of functions to control the underlying joint.
  76857. */
  76858. var PhysicsJoint = /** @class */ (function () {
  76859. function PhysicsJoint(type, jointData) {
  76860. this.type = type;
  76861. this.jointData = jointData;
  76862. jointData.nativeParams = jointData.nativeParams || {};
  76863. }
  76864. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76865. get: function () {
  76866. return this._physicsJoint;
  76867. },
  76868. set: function (newJoint) {
  76869. if (this._physicsJoint) {
  76870. //remove from the wolrd
  76871. }
  76872. this._physicsJoint = newJoint;
  76873. },
  76874. enumerable: true,
  76875. configurable: true
  76876. });
  76877. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76878. set: function (physicsPlugin) {
  76879. this._physicsPlugin = physicsPlugin;
  76880. },
  76881. enumerable: true,
  76882. configurable: true
  76883. });
  76884. /**
  76885. * Execute a function that is physics-plugin specific.
  76886. * @param {Function} func the function that will be executed.
  76887. * It accepts two parameters: the physics world and the physics joint.
  76888. */
  76889. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76890. func(this._physicsPlugin.world, this._physicsJoint);
  76891. };
  76892. //TODO check if the native joints are the same
  76893. //Joint Types
  76894. PhysicsJoint.DistanceJoint = 0;
  76895. PhysicsJoint.HingeJoint = 1;
  76896. PhysicsJoint.BallAndSocketJoint = 2;
  76897. PhysicsJoint.WheelJoint = 3;
  76898. PhysicsJoint.SliderJoint = 4;
  76899. //OIMO
  76900. PhysicsJoint.PrismaticJoint = 5;
  76901. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76902. PhysicsJoint.UniversalJoint = 6;
  76903. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76904. //Cannon
  76905. //Similar to a Ball-Joint. Different in params
  76906. PhysicsJoint.PointToPointJoint = 8;
  76907. //Cannon only at the moment
  76908. PhysicsJoint.SpringJoint = 9;
  76909. PhysicsJoint.LockJoint = 10;
  76910. return PhysicsJoint;
  76911. }());
  76912. BABYLON.PhysicsJoint = PhysicsJoint;
  76913. /**
  76914. * A class representing a physics distance joint.
  76915. */
  76916. var DistanceJoint = /** @class */ (function (_super) {
  76917. __extends(DistanceJoint, _super);
  76918. function DistanceJoint(jointData) {
  76919. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76920. }
  76921. /**
  76922. * Update the predefined distance.
  76923. */
  76924. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76925. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76926. };
  76927. return DistanceJoint;
  76928. }(PhysicsJoint));
  76929. BABYLON.DistanceJoint = DistanceJoint;
  76930. var MotorEnabledJoint = /** @class */ (function (_super) {
  76931. __extends(MotorEnabledJoint, _super);
  76932. function MotorEnabledJoint(type, jointData) {
  76933. return _super.call(this, type, jointData) || this;
  76934. }
  76935. /**
  76936. * Set the motor values.
  76937. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76938. * @param {number} force the force to apply
  76939. * @param {number} maxForce max force for this motor.
  76940. */
  76941. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76942. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76943. };
  76944. /**
  76945. * Set the motor's limits.
  76946. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76947. */
  76948. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76949. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76950. };
  76951. return MotorEnabledJoint;
  76952. }(PhysicsJoint));
  76953. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76954. /**
  76955. * This class represents a single hinge physics joint
  76956. */
  76957. var HingeJoint = /** @class */ (function (_super) {
  76958. __extends(HingeJoint, _super);
  76959. function HingeJoint(jointData) {
  76960. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76961. }
  76962. /**
  76963. * Set the motor values.
  76964. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76965. * @param {number} force the force to apply
  76966. * @param {number} maxForce max force for this motor.
  76967. */
  76968. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76969. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76970. };
  76971. /**
  76972. * Set the motor's limits.
  76973. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76974. */
  76975. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76976. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76977. };
  76978. return HingeJoint;
  76979. }(MotorEnabledJoint));
  76980. BABYLON.HingeJoint = HingeJoint;
  76981. /**
  76982. * This class represents a dual hinge physics joint (same as wheel joint)
  76983. */
  76984. var Hinge2Joint = /** @class */ (function (_super) {
  76985. __extends(Hinge2Joint, _super);
  76986. function Hinge2Joint(jointData) {
  76987. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76988. }
  76989. /**
  76990. * Set the motor values.
  76991. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76992. * @param {number} force the force to apply
  76993. * @param {number} maxForce max force for this motor.
  76994. * @param {motorIndex} the motor's index, 0 or 1.
  76995. */
  76996. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76997. if (motorIndex === void 0) { motorIndex = 0; }
  76998. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76999. };
  77000. /**
  77001. * Set the motor limits.
  77002. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77003. * @param {number} upperLimit the upper limit
  77004. * @param {number} lowerLimit lower limit
  77005. * @param {motorIndex} the motor's index, 0 or 1.
  77006. */
  77007. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  77008. if (motorIndex === void 0) { motorIndex = 0; }
  77009. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  77010. };
  77011. return Hinge2Joint;
  77012. }(MotorEnabledJoint));
  77013. BABYLON.Hinge2Joint = Hinge2Joint;
  77014. })(BABYLON || (BABYLON = {}));
  77015. //# sourceMappingURL=babylon.physicsJoint.js.map
  77016. "use strict";
  77017. var BABYLON;
  77018. (function (BABYLON) {
  77019. var PhysicsImpostor = /** @class */ (function () {
  77020. function PhysicsImpostor(object, type, _options, _scene) {
  77021. if (_options === void 0) { _options = { mass: 0 }; }
  77022. var _this = this;
  77023. this.object = object;
  77024. this.type = type;
  77025. this._options = _options;
  77026. this._scene = _scene;
  77027. this._bodyUpdateRequired = false;
  77028. this._onBeforePhysicsStepCallbacks = new Array();
  77029. this._onAfterPhysicsStepCallbacks = new Array();
  77030. this._onPhysicsCollideCallbacks = [];
  77031. this._deltaPosition = BABYLON.Vector3.Zero();
  77032. this._isDisposed = false;
  77033. //temp variables for parent rotation calculations
  77034. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77035. this._tmpQuat = new BABYLON.Quaternion();
  77036. this._tmpQuat2 = new BABYLON.Quaternion();
  77037. /**
  77038. * this function is executed by the physics engine.
  77039. */
  77040. this.beforeStep = function () {
  77041. if (!_this._physicsEngine) {
  77042. return;
  77043. }
  77044. _this.object.translate(_this._deltaPosition, -1);
  77045. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77046. _this.object.computeWorldMatrix(false);
  77047. if (_this.object.parent && _this.object.rotationQuaternion) {
  77048. _this.getParentsRotation();
  77049. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77050. }
  77051. else {
  77052. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77053. }
  77054. if (!_this._options.disableBidirectionalTransformation) {
  77055. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77056. }
  77057. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77058. func(_this);
  77059. });
  77060. };
  77061. /**
  77062. * this function is executed by the physics engine.
  77063. */
  77064. this.afterStep = function () {
  77065. if (!_this._physicsEngine) {
  77066. return;
  77067. }
  77068. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77069. func(_this);
  77070. });
  77071. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77072. // object has now its world rotation. needs to be converted to local.
  77073. if (_this.object.parent && _this.object.rotationQuaternion) {
  77074. _this.getParentsRotation();
  77075. _this._tmpQuat.conjugateInPlace();
  77076. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77077. }
  77078. // take the position set and make it the absolute position of this object.
  77079. _this.object.setAbsolutePosition(_this.object.position);
  77080. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77081. _this.object.translate(_this._deltaPosition, 1);
  77082. };
  77083. /**
  77084. * Legacy collision detection event support
  77085. */
  77086. this.onCollideEvent = null;
  77087. //event and body object due to cannon's event-based architecture.
  77088. this.onCollide = function (e) {
  77089. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77090. return;
  77091. }
  77092. if (!_this._physicsEngine) {
  77093. return;
  77094. }
  77095. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77096. if (otherImpostor) {
  77097. // Legacy collision detection event support
  77098. if (_this.onCollideEvent) {
  77099. _this.onCollideEvent(_this, otherImpostor);
  77100. }
  77101. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77102. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77103. }).forEach(function (obj) {
  77104. obj.callback(_this, otherImpostor);
  77105. });
  77106. }
  77107. };
  77108. //sanity check!
  77109. if (!this.object) {
  77110. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77111. return;
  77112. }
  77113. //legacy support for old syntax.
  77114. if (!this._scene && object.getScene) {
  77115. this._scene = object.getScene();
  77116. }
  77117. if (!this._scene) {
  77118. return;
  77119. }
  77120. this._physicsEngine = this._scene.getPhysicsEngine();
  77121. if (!this._physicsEngine) {
  77122. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77123. }
  77124. else {
  77125. //set the object's quaternion, if not set
  77126. if (!this.object.rotationQuaternion) {
  77127. if (this.object.rotation) {
  77128. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77129. }
  77130. else {
  77131. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77132. }
  77133. }
  77134. //default options params
  77135. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77136. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77137. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77138. this._joints = [];
  77139. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77140. if (!this.object.parent || this._options.ignoreParent) {
  77141. this._init();
  77142. }
  77143. else if (this.object.parent.physicsImpostor) {
  77144. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77145. }
  77146. }
  77147. }
  77148. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77149. get: function () {
  77150. return this._isDisposed;
  77151. },
  77152. enumerable: true,
  77153. configurable: true
  77154. });
  77155. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77156. get: function () {
  77157. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77158. },
  77159. set: function (value) {
  77160. this.setMass(value);
  77161. },
  77162. enumerable: true,
  77163. configurable: true
  77164. });
  77165. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77166. get: function () {
  77167. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77168. },
  77169. set: function (value) {
  77170. if (!this._physicsEngine) {
  77171. return;
  77172. }
  77173. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77174. },
  77175. enumerable: true,
  77176. configurable: true
  77177. });
  77178. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77179. get: function () {
  77180. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77181. },
  77182. set: function (value) {
  77183. if (!this._physicsEngine) {
  77184. return;
  77185. }
  77186. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77187. },
  77188. enumerable: true,
  77189. configurable: true
  77190. });
  77191. /**
  77192. * This function will completly initialize this impostor.
  77193. * It will create a new body - but only if this mesh has no parent.
  77194. * If it has, this impostor will not be used other than to define the impostor
  77195. * of the child mesh.
  77196. */
  77197. PhysicsImpostor.prototype._init = function () {
  77198. if (!this._physicsEngine) {
  77199. return;
  77200. }
  77201. this._physicsEngine.removeImpostor(this);
  77202. this.physicsBody = null;
  77203. this._parent = this._parent || this._getPhysicsParent();
  77204. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77205. this._physicsEngine.addImpostor(this);
  77206. }
  77207. };
  77208. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77209. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77210. var parentMesh = this.object.parent;
  77211. return parentMesh.physicsImpostor;
  77212. }
  77213. return null;
  77214. };
  77215. /**
  77216. * Should a new body be generated.
  77217. */
  77218. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77219. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77220. };
  77221. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77222. this.forceUpdate();
  77223. };
  77224. /**
  77225. * Force a regeneration of this or the parent's impostor's body.
  77226. * Use under cautious - This will remove all joints already implemented.
  77227. */
  77228. PhysicsImpostor.prototype.forceUpdate = function () {
  77229. this._init();
  77230. if (this.parent && !this._options.ignoreParent) {
  77231. this.parent.forceUpdate();
  77232. }
  77233. };
  77234. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77235. /*public get mesh(): AbstractMesh {
  77236. return this._mesh;
  77237. }*/
  77238. /**
  77239. * Gets the body that holds this impostor. Either its own, or its parent.
  77240. */
  77241. get: function () {
  77242. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77243. },
  77244. /**
  77245. * Set the physics body. Used mainly by the physics engine/plugin
  77246. */
  77247. set: function (physicsBody) {
  77248. if (this._physicsBody && this._physicsEngine) {
  77249. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77250. }
  77251. this._physicsBody = physicsBody;
  77252. this.resetUpdateFlags();
  77253. },
  77254. enumerable: true,
  77255. configurable: true
  77256. });
  77257. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77258. get: function () {
  77259. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77260. },
  77261. set: function (value) {
  77262. this._parent = value;
  77263. },
  77264. enumerable: true,
  77265. configurable: true
  77266. });
  77267. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77268. this._bodyUpdateRequired = false;
  77269. };
  77270. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77271. if (this.object.getBoundingInfo) {
  77272. var q = this.object.rotationQuaternion;
  77273. //reset rotation
  77274. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77275. //calculate the world matrix with no rotation
  77276. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77277. var boundingInfo = this.object.getBoundingInfo();
  77278. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77279. //bring back the rotation
  77280. this.object.rotationQuaternion = q;
  77281. //calculate the world matrix with the new rotation
  77282. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77283. return size;
  77284. }
  77285. else {
  77286. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77287. }
  77288. };
  77289. PhysicsImpostor.prototype.getObjectCenter = function () {
  77290. if (this.object.getBoundingInfo) {
  77291. var boundingInfo = this.object.getBoundingInfo();
  77292. return boundingInfo.boundingBox.centerWorld;
  77293. }
  77294. else {
  77295. return this.object.position;
  77296. }
  77297. };
  77298. /**
  77299. * Get a specific parametes from the options parameter.
  77300. */
  77301. PhysicsImpostor.prototype.getParam = function (paramName) {
  77302. return this._options[paramName];
  77303. };
  77304. /**
  77305. * Sets a specific parameter in the options given to the physics plugin
  77306. */
  77307. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77308. this._options[paramName] = value;
  77309. this._bodyUpdateRequired = true;
  77310. };
  77311. /**
  77312. * Specifically change the body's mass option. Won't recreate the physics body object
  77313. */
  77314. PhysicsImpostor.prototype.setMass = function (mass) {
  77315. if (this.getParam("mass") !== mass) {
  77316. this.setParam("mass", mass);
  77317. }
  77318. if (this._physicsEngine) {
  77319. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77320. }
  77321. };
  77322. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77323. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77324. };
  77325. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77326. if (this._physicsEngine) {
  77327. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77328. }
  77329. };
  77330. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77331. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77332. };
  77333. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77334. if (this._physicsEngine) {
  77335. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77336. }
  77337. };
  77338. /**
  77339. * Execute a function with the physics plugin native code.
  77340. * Provide a function the will have two variables - the world object and the physics body object.
  77341. */
  77342. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77343. if (this._physicsEngine) {
  77344. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77345. }
  77346. };
  77347. /**
  77348. * Register a function that will be executed before the physics world is stepping forward.
  77349. */
  77350. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77351. this._onBeforePhysicsStepCallbacks.push(func);
  77352. };
  77353. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77354. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77355. if (index > -1) {
  77356. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77357. }
  77358. else {
  77359. BABYLON.Tools.Warn("Function to remove was not found");
  77360. }
  77361. };
  77362. /**
  77363. * Register a function that will be executed after the physics step
  77364. */
  77365. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77366. this._onAfterPhysicsStepCallbacks.push(func);
  77367. };
  77368. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77369. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77370. if (index > -1) {
  77371. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77372. }
  77373. else {
  77374. BABYLON.Tools.Warn("Function to remove was not found");
  77375. }
  77376. };
  77377. /**
  77378. * register a function that will be executed when this impostor collides against a different body.
  77379. */
  77380. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77381. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77382. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77383. };
  77384. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77385. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77386. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77387. if (index > -1) {
  77388. this._onPhysicsCollideCallbacks.splice(index, 1);
  77389. }
  77390. else {
  77391. BABYLON.Tools.Warn("Function to remove was not found");
  77392. }
  77393. };
  77394. PhysicsImpostor.prototype.getParentsRotation = function () {
  77395. var parent = this.object.parent;
  77396. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77397. while (parent) {
  77398. if (parent.rotationQuaternion) {
  77399. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77400. }
  77401. else {
  77402. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77403. }
  77404. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77405. parent = parent.parent;
  77406. }
  77407. return this._tmpQuat;
  77408. };
  77409. /**
  77410. * Apply a force
  77411. */
  77412. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77413. if (this._physicsEngine) {
  77414. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77415. }
  77416. return this;
  77417. };
  77418. /**
  77419. * Apply an impulse
  77420. */
  77421. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77422. if (this._physicsEngine) {
  77423. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77424. }
  77425. return this;
  77426. };
  77427. /**
  77428. * A help function to create a joint.
  77429. */
  77430. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77431. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77432. this.addJoint(otherImpostor, joint);
  77433. return this;
  77434. };
  77435. /**
  77436. * Add a joint to this impostor with a different impostor.
  77437. */
  77438. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77439. this._joints.push({
  77440. otherImpostor: otherImpostor,
  77441. joint: joint
  77442. });
  77443. if (this._physicsEngine) {
  77444. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77445. }
  77446. return this;
  77447. };
  77448. /**
  77449. * Will keep this body still, in a sleep mode.
  77450. */
  77451. PhysicsImpostor.prototype.sleep = function () {
  77452. if (this._physicsEngine) {
  77453. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77454. }
  77455. return this;
  77456. };
  77457. /**
  77458. * Wake the body up.
  77459. */
  77460. PhysicsImpostor.prototype.wakeUp = function () {
  77461. if (this._physicsEngine) {
  77462. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77463. }
  77464. return this;
  77465. };
  77466. PhysicsImpostor.prototype.clone = function (newObject) {
  77467. if (!newObject)
  77468. return null;
  77469. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77470. };
  77471. PhysicsImpostor.prototype.dispose = function () {
  77472. var _this = this;
  77473. //no dispose if no physics engine is available.
  77474. if (!this._physicsEngine) {
  77475. return;
  77476. }
  77477. this._joints.forEach(function (j) {
  77478. if (_this._physicsEngine) {
  77479. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77480. }
  77481. });
  77482. //dispose the physics body
  77483. this._physicsEngine.removeImpostor(this);
  77484. if (this.parent) {
  77485. this.parent.forceUpdate();
  77486. }
  77487. else {
  77488. /*this._object.getChildMeshes().forEach(function(mesh) {
  77489. if (mesh.physicsImpostor) {
  77490. if (disposeChildren) {
  77491. mesh.physicsImpostor.dispose();
  77492. mesh.physicsImpostor = null;
  77493. }
  77494. }
  77495. })*/
  77496. }
  77497. this._isDisposed = true;
  77498. };
  77499. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77500. this._deltaPosition.copyFrom(position);
  77501. };
  77502. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77503. if (!this._deltaRotation) {
  77504. this._deltaRotation = new BABYLON.Quaternion();
  77505. }
  77506. this._deltaRotation.copyFrom(rotation);
  77507. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77508. };
  77509. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77510. if (this._physicsEngine) {
  77511. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77512. }
  77513. return this;
  77514. };
  77515. PhysicsImpostor.prototype.getRadius = function () {
  77516. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77517. };
  77518. /**
  77519. * Sync a bone with this impostor
  77520. * @param bone The bone to sync to the impostor.
  77521. * @param boneMesh The mesh that the bone is influencing.
  77522. * @param jointPivot The pivot of the joint / bone in local space.
  77523. * @param distToJoint Optional distance from the impostor to the joint.
  77524. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77525. */
  77526. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77527. var tempVec = PhysicsImpostor._tmpVecs[0];
  77528. var mesh = this.object;
  77529. if (mesh.rotationQuaternion) {
  77530. if (adjustRotation) {
  77531. var tempQuat = PhysicsImpostor._tmpQuat;
  77532. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77533. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77534. }
  77535. else {
  77536. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77537. }
  77538. }
  77539. tempVec.x = 0;
  77540. tempVec.y = 0;
  77541. tempVec.z = 0;
  77542. if (jointPivot) {
  77543. tempVec.x = jointPivot.x;
  77544. tempVec.y = jointPivot.y;
  77545. tempVec.z = jointPivot.z;
  77546. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77547. if (distToJoint === undefined || distToJoint === null) {
  77548. distToJoint = jointPivot.length();
  77549. }
  77550. tempVec.x *= distToJoint;
  77551. tempVec.y *= distToJoint;
  77552. tempVec.z *= distToJoint;
  77553. }
  77554. if (bone.getParent()) {
  77555. tempVec.addInPlace(mesh.getAbsolutePosition());
  77556. bone.setAbsolutePosition(tempVec, boneMesh);
  77557. }
  77558. else {
  77559. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77560. boneMesh.position.x -= tempVec.x;
  77561. boneMesh.position.y -= tempVec.y;
  77562. boneMesh.position.z -= tempVec.z;
  77563. }
  77564. };
  77565. /**
  77566. * Sync impostor to a bone
  77567. * @param bone The bone that the impostor will be synced to.
  77568. * @param boneMesh The mesh that the bone is influencing.
  77569. * @param jointPivot The pivot of the joint / bone in local space.
  77570. * @param distToJoint Optional distance from the impostor to the joint.
  77571. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77572. * @param boneAxis Optional vector3 axis the bone is aligned with
  77573. */
  77574. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77575. var mesh = this.object;
  77576. if (mesh.rotationQuaternion) {
  77577. if (adjustRotation) {
  77578. var tempQuat = PhysicsImpostor._tmpQuat;
  77579. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77580. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77581. }
  77582. else {
  77583. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77584. }
  77585. }
  77586. var pos = PhysicsImpostor._tmpVecs[0];
  77587. var boneDir = PhysicsImpostor._tmpVecs[1];
  77588. if (!boneAxis) {
  77589. boneAxis = PhysicsImpostor._tmpVecs[2];
  77590. boneAxis.x = 0;
  77591. boneAxis.y = 1;
  77592. boneAxis.z = 0;
  77593. }
  77594. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77595. bone.getAbsolutePositionToRef(boneMesh, pos);
  77596. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77597. distToJoint = jointPivot.length();
  77598. }
  77599. if (distToJoint !== undefined && distToJoint !== null) {
  77600. pos.x += boneDir.x * distToJoint;
  77601. pos.y += boneDir.y * distToJoint;
  77602. pos.z += boneDir.z * distToJoint;
  77603. }
  77604. mesh.setAbsolutePosition(pos);
  77605. };
  77606. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77607. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77608. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77609. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77610. //Impostor types
  77611. PhysicsImpostor.NoImpostor = 0;
  77612. PhysicsImpostor.SphereImpostor = 1;
  77613. PhysicsImpostor.BoxImpostor = 2;
  77614. PhysicsImpostor.PlaneImpostor = 3;
  77615. PhysicsImpostor.MeshImpostor = 4;
  77616. PhysicsImpostor.CylinderImpostor = 7;
  77617. PhysicsImpostor.ParticleImpostor = 8;
  77618. PhysicsImpostor.HeightmapImpostor = 9;
  77619. return PhysicsImpostor;
  77620. }());
  77621. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77622. })(BABYLON || (BABYLON = {}));
  77623. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77624. "use strict";
  77625. var BABYLON;
  77626. (function (BABYLON) {
  77627. var PhysicsEngine = /** @class */ (function () {
  77628. function PhysicsEngine(gravity, _physicsPlugin) {
  77629. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77630. this._physicsPlugin = _physicsPlugin;
  77631. //new methods and parameters
  77632. this._impostors = [];
  77633. this._joints = [];
  77634. if (!this._physicsPlugin.isSupported()) {
  77635. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77636. + "Please make sure it is included.");
  77637. }
  77638. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77639. this.setGravity(gravity);
  77640. this.setTimeStep();
  77641. }
  77642. PhysicsEngine.prototype.setGravity = function (gravity) {
  77643. this.gravity = gravity;
  77644. this._physicsPlugin.setGravity(this.gravity);
  77645. };
  77646. /**
  77647. * Set the time step of the physics engine.
  77648. * default is 1/60.
  77649. * To slow it down, enter 1/600 for example.
  77650. * To speed it up, 1/30
  77651. * @param {number} newTimeStep the new timestep to apply to this world.
  77652. */
  77653. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77654. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77655. this._physicsPlugin.setTimeStep(newTimeStep);
  77656. };
  77657. /**
  77658. * Get the time step of the physics engine.
  77659. */
  77660. PhysicsEngine.prototype.getTimeStep = function () {
  77661. return this._physicsPlugin.getTimeStep();
  77662. };
  77663. PhysicsEngine.prototype.dispose = function () {
  77664. this._impostors.forEach(function (impostor) {
  77665. impostor.dispose();
  77666. });
  77667. this._physicsPlugin.dispose();
  77668. };
  77669. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77670. return this._physicsPlugin.name;
  77671. };
  77672. /**
  77673. * Adding a new impostor for the impostor tracking.
  77674. * This will be done by the impostor itself.
  77675. * @param {PhysicsImpostor} impostor the impostor to add
  77676. */
  77677. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77678. impostor.uniqueId = this._impostors.push(impostor);
  77679. //if no parent, generate the body
  77680. if (!impostor.parent) {
  77681. this._physicsPlugin.generatePhysicsBody(impostor);
  77682. }
  77683. };
  77684. /**
  77685. * Remove an impostor from the engine.
  77686. * This impostor and its mesh will not longer be updated by the physics engine.
  77687. * @param {PhysicsImpostor} impostor the impostor to remove
  77688. */
  77689. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  77690. var index = this._impostors.indexOf(impostor);
  77691. if (index > -1) {
  77692. var removed = this._impostors.splice(index, 1);
  77693. //Is it needed?
  77694. if (removed.length) {
  77695. //this will also remove it from the world.
  77696. removed[0].physicsBody = null;
  77697. }
  77698. }
  77699. };
  77700. /**
  77701. * Add a joint to the physics engine
  77702. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  77703. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  77704. * @param {PhysicsJoint} the joint that will connect both impostors.
  77705. */
  77706. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  77707. var impostorJoint = {
  77708. mainImpostor: mainImpostor,
  77709. connectedImpostor: connectedImpostor,
  77710. joint: joint
  77711. };
  77712. joint.physicsPlugin = this._physicsPlugin;
  77713. this._joints.push(impostorJoint);
  77714. this._physicsPlugin.generateJoint(impostorJoint);
  77715. };
  77716. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  77717. var matchingJoints = this._joints.filter(function (impostorJoint) {
  77718. return (impostorJoint.connectedImpostor === connectedImpostor
  77719. && impostorJoint.joint === joint
  77720. && impostorJoint.mainImpostor === mainImpostor);
  77721. });
  77722. if (matchingJoints.length) {
  77723. this._physicsPlugin.removeJoint(matchingJoints[0]);
  77724. //TODO remove it from the list as well
  77725. }
  77726. };
  77727. /**
  77728. * Called by the scene. no need to call it.
  77729. */
  77730. PhysicsEngine.prototype._step = function (delta) {
  77731. var _this = this;
  77732. //check if any mesh has no body / requires an update
  77733. this._impostors.forEach(function (impostor) {
  77734. if (impostor.isBodyInitRequired()) {
  77735. _this._physicsPlugin.generatePhysicsBody(impostor);
  77736. }
  77737. });
  77738. if (delta > 0.1) {
  77739. delta = 0.1;
  77740. }
  77741. else if (delta <= 0) {
  77742. delta = 1.0 / 60.0;
  77743. }
  77744. this._physicsPlugin.executeStep(delta, this._impostors);
  77745. };
  77746. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  77747. return this._physicsPlugin;
  77748. };
  77749. PhysicsEngine.prototype.getImpostors = function () {
  77750. return this._impostors;
  77751. };
  77752. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  77753. for (var i = 0; i < this._impostors.length; ++i) {
  77754. if (this._impostors[i].object === object) {
  77755. return this._impostors[i];
  77756. }
  77757. }
  77758. return null;
  77759. };
  77760. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  77761. for (var i = 0; i < this._impostors.length; ++i) {
  77762. if (this._impostors[i].physicsBody === body) {
  77763. return this._impostors[i];
  77764. }
  77765. }
  77766. return null;
  77767. };
  77768. // Statics
  77769. PhysicsEngine.Epsilon = 0.001;
  77770. return PhysicsEngine;
  77771. }());
  77772. BABYLON.PhysicsEngine = PhysicsEngine;
  77773. })(BABYLON || (BABYLON = {}));
  77774. //# sourceMappingURL=babylon.physicsEngine.js.map
  77775. "use strict";
  77776. var BABYLON;
  77777. (function (BABYLON) {
  77778. var PhysicsHelper = /** @class */ (function () {
  77779. function PhysicsHelper(scene) {
  77780. this._scene = scene;
  77781. this._physicsEngine = this._scene.getPhysicsEngine();
  77782. if (!this._physicsEngine) {
  77783. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77784. }
  77785. }
  77786. /**
  77787. * @param {Vector3} origin the origin of the explosion
  77788. * @param {number} radius the explosion radius
  77789. * @param {number} strength the explosion strength
  77790. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77791. */
  77792. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77793. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77794. if (!this._physicsEngine) {
  77795. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77796. return null;
  77797. }
  77798. var impostors = this._physicsEngine.getImpostors();
  77799. if (impostors.length === 0) {
  77800. return null;
  77801. }
  77802. var event = new PhysicsRadialExplosionEvent(this._scene);
  77803. impostors.forEach(function (impostor) {
  77804. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77805. if (!impostorForceAndContactPoint) {
  77806. return;
  77807. }
  77808. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77809. });
  77810. event.dispose(false);
  77811. return event;
  77812. };
  77813. /**
  77814. * @param {Vector3} origin the origin of the explosion
  77815. * @param {number} radius the explosion radius
  77816. * @param {number} strength the explosion strength
  77817. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77818. */
  77819. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77820. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77821. if (!this._physicsEngine) {
  77822. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77823. return null;
  77824. }
  77825. var impostors = this._physicsEngine.getImpostors();
  77826. if (impostors.length === 0) {
  77827. return null;
  77828. }
  77829. var event = new PhysicsRadialExplosionEvent(this._scene);
  77830. impostors.forEach(function (impostor) {
  77831. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77832. if (!impostorForceAndContactPoint) {
  77833. return;
  77834. }
  77835. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77836. });
  77837. event.dispose(false);
  77838. return event;
  77839. };
  77840. /**
  77841. * @param {Vector3} origin the origin of the explosion
  77842. * @param {number} radius the explosion radius
  77843. * @param {number} strength the explosion strength
  77844. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77845. */
  77846. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77847. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77848. if (!this._physicsEngine) {
  77849. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77850. return null;
  77851. }
  77852. var impostors = this._physicsEngine.getImpostors();
  77853. if (impostors.length === 0) {
  77854. return null;
  77855. }
  77856. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77857. event.dispose(false);
  77858. return event;
  77859. };
  77860. /**
  77861. * @param {Vector3} origin the origin of the updraft
  77862. * @param {number} radius the radius of the updraft
  77863. * @param {number} strength the strength of the updraft
  77864. * @param {number} height the height of the updraft
  77865. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77866. */
  77867. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77868. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77869. if (!this._physicsEngine) {
  77870. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77871. return null;
  77872. }
  77873. if (this._physicsEngine.getImpostors().length === 0) {
  77874. return null;
  77875. }
  77876. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77877. event.dispose(false);
  77878. return event;
  77879. };
  77880. /**
  77881. * @param {Vector3} origin the of the vortex
  77882. * @param {number} radius the radius of the vortex
  77883. * @param {number} strength the strength of the vortex
  77884. * @param {number} height the height of the vortex
  77885. */
  77886. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77887. if (!this._physicsEngine) {
  77888. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77889. return null;
  77890. }
  77891. if (this._physicsEngine.getImpostors().length === 0) {
  77892. return null;
  77893. }
  77894. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77895. event.dispose(false);
  77896. return event;
  77897. };
  77898. return PhysicsHelper;
  77899. }());
  77900. BABYLON.PhysicsHelper = PhysicsHelper;
  77901. /***** Radial explosion *****/
  77902. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77903. function PhysicsRadialExplosionEvent(scene) {
  77904. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77905. this._rays = [];
  77906. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77907. this._scene = scene;
  77908. }
  77909. /**
  77910. * Returns the data related to the radial explosion event (sphere & rays).
  77911. * @returns {PhysicsRadialExplosionEventData}
  77912. */
  77913. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77914. this._dataFetched = true;
  77915. return {
  77916. sphere: this._sphere,
  77917. rays: this._rays,
  77918. };
  77919. };
  77920. /**
  77921. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77922. * @param impostor
  77923. * @param {Vector3} origin the origin of the explosion
  77924. * @param {number} radius the explosion radius
  77925. * @param {number} strength the explosion strength
  77926. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77927. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77928. */
  77929. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77930. if (impostor.mass === 0) {
  77931. return null;
  77932. }
  77933. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77934. return null;
  77935. }
  77936. if (impostor.object.getClassName() !== 'Mesh') {
  77937. return null;
  77938. }
  77939. var impostorObject = impostor.object;
  77940. var impostorObjectCenter = impostor.getObjectCenter();
  77941. var direction = impostorObjectCenter.subtract(origin);
  77942. var ray = new BABYLON.Ray(origin, direction, radius);
  77943. this._rays.push(ray);
  77944. var hit = ray.intersectsMesh(impostorObject);
  77945. var contactPoint = hit.pickedPoint;
  77946. if (!contactPoint) {
  77947. return null;
  77948. }
  77949. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77950. if (distanceFromOrigin > radius) {
  77951. return null;
  77952. }
  77953. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77954. ? strength
  77955. : strength * (1 - (distanceFromOrigin / radius));
  77956. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77957. return { force: force, contactPoint: contactPoint };
  77958. };
  77959. /**
  77960. * Disposes the sphere.
  77961. * @param {bolean} force
  77962. */
  77963. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77964. var _this = this;
  77965. if (force === void 0) { force = true; }
  77966. if (force) {
  77967. this._sphere.dispose();
  77968. }
  77969. else {
  77970. setTimeout(function () {
  77971. if (!_this._dataFetched) {
  77972. _this._sphere.dispose();
  77973. }
  77974. }, 0);
  77975. }
  77976. };
  77977. /*** Helpers ***/
  77978. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77979. if (!this._sphere) {
  77980. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77981. this._sphere.isVisible = false;
  77982. }
  77983. };
  77984. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77985. var impostorObject = impostor.object;
  77986. this._prepareSphere();
  77987. this._sphere.position = origin;
  77988. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77989. this._sphere._updateBoundingInfo();
  77990. this._sphere.computeWorldMatrix(true);
  77991. return this._sphere.intersectsMesh(impostorObject, true);
  77992. };
  77993. return PhysicsRadialExplosionEvent;
  77994. }());
  77995. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77996. /***** Gravitational Field *****/
  77997. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77998. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77999. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78000. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78001. this._physicsHelper = physicsHelper;
  78002. this._scene = scene;
  78003. this._origin = origin;
  78004. this._radius = radius;
  78005. this._strength = strength;
  78006. this._falloff = falloff;
  78007. this._tickCallback = this._tick.bind(this);
  78008. }
  78009. /**
  78010. * Returns the data related to the gravitational field event (sphere).
  78011. * @returns {PhysicsGravitationalFieldEventData}
  78012. */
  78013. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  78014. this._dataFetched = true;
  78015. return {
  78016. sphere: this._sphere,
  78017. };
  78018. };
  78019. /**
  78020. * Enables the gravitational field.
  78021. */
  78022. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78023. this._tickCallback.call(this);
  78024. this._scene.registerBeforeRender(this._tickCallback);
  78025. };
  78026. /**
  78027. * Disables the gravitational field.
  78028. */
  78029. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78030. this._scene.unregisterBeforeRender(this._tickCallback);
  78031. };
  78032. /**
  78033. * Disposes the sphere.
  78034. * @param {bolean} force
  78035. */
  78036. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78037. var _this = this;
  78038. if (force === void 0) { force = true; }
  78039. if (force) {
  78040. this._sphere.dispose();
  78041. }
  78042. else {
  78043. setTimeout(function () {
  78044. if (!_this._dataFetched) {
  78045. _this._sphere.dispose();
  78046. }
  78047. }, 0);
  78048. }
  78049. };
  78050. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78051. // Since the params won't change, we fetch the event only once
  78052. if (this._sphere) {
  78053. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78054. }
  78055. else {
  78056. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78057. if (radialExplosionEvent) {
  78058. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78059. }
  78060. }
  78061. };
  78062. return PhysicsGravitationalFieldEvent;
  78063. }());
  78064. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78065. /***** Updraft *****/
  78066. var PhysicsUpdraftEvent = /** @class */ (function () {
  78067. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78068. this._scene = _scene;
  78069. this._origin = _origin;
  78070. this._radius = _radius;
  78071. this._strength = _strength;
  78072. this._height = _height;
  78073. this._updraftMode = _updraftMode;
  78074. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78075. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78076. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78077. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78078. this._physicsEngine = this._scene.getPhysicsEngine();
  78079. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78080. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78081. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78082. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78083. }
  78084. this._tickCallback = this._tick.bind(this);
  78085. }
  78086. /**
  78087. * Returns the data related to the updraft event (cylinder).
  78088. * @returns {PhysicsUpdraftEventData}
  78089. */
  78090. PhysicsUpdraftEvent.prototype.getData = function () {
  78091. this._dataFetched = true;
  78092. return {
  78093. cylinder: this._cylinder,
  78094. };
  78095. };
  78096. /**
  78097. * Enables the updraft.
  78098. */
  78099. PhysicsUpdraftEvent.prototype.enable = function () {
  78100. this._tickCallback.call(this);
  78101. this._scene.registerBeforeRender(this._tickCallback);
  78102. };
  78103. /**
  78104. * Disables the cortex.
  78105. */
  78106. PhysicsUpdraftEvent.prototype.disable = function () {
  78107. this._scene.unregisterBeforeRender(this._tickCallback);
  78108. };
  78109. /**
  78110. * Disposes the sphere.
  78111. * @param {bolean} force
  78112. */
  78113. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78114. var _this = this;
  78115. if (force === void 0) { force = true; }
  78116. if (force) {
  78117. this._cylinder.dispose();
  78118. }
  78119. else {
  78120. setTimeout(function () {
  78121. if (!_this._dataFetched) {
  78122. _this._cylinder.dispose();
  78123. }
  78124. }, 0);
  78125. }
  78126. };
  78127. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78128. if (impostor.mass === 0) {
  78129. return null;
  78130. }
  78131. if (!this._intersectsWithCylinder(impostor)) {
  78132. return null;
  78133. }
  78134. var impostorObjectCenter = impostor.getObjectCenter();
  78135. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78136. var direction = this._originDirection;
  78137. }
  78138. else {
  78139. var direction = impostorObjectCenter.subtract(this._originTop);
  78140. }
  78141. var multiplier = this._strength * -1;
  78142. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78143. return { force: force, contactPoint: impostorObjectCenter };
  78144. };
  78145. PhysicsUpdraftEvent.prototype._tick = function () {
  78146. var _this = this;
  78147. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78148. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78149. if (!impostorForceAndContactPoint) {
  78150. return;
  78151. }
  78152. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78153. });
  78154. };
  78155. /*** Helpers ***/
  78156. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78157. if (!this._cylinder) {
  78158. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78159. height: this._height,
  78160. diameter: this._radius * 2,
  78161. }, this._scene);
  78162. this._cylinder.isVisible = false;
  78163. }
  78164. };
  78165. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78166. var impostorObject = impostor.object;
  78167. this._prepareCylinder();
  78168. this._cylinder.position = this._cylinderPosition;
  78169. return this._cylinder.intersectsMesh(impostorObject, true);
  78170. };
  78171. return PhysicsUpdraftEvent;
  78172. }());
  78173. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78174. /***** Vortex *****/
  78175. var PhysicsVortexEvent = /** @class */ (function () {
  78176. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78177. this._scene = _scene;
  78178. this._origin = _origin;
  78179. this._radius = _radius;
  78180. this._strength = _strength;
  78181. this._height = _height;
  78182. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78183. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78184. this._updraftMultiplier = 0.02;
  78185. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78186. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78187. this._physicsEngine = this._scene.getPhysicsEngine();
  78188. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78189. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78190. this._tickCallback = this._tick.bind(this);
  78191. }
  78192. /**
  78193. * Returns the data related to the vortex event (cylinder).
  78194. * @returns {PhysicsVortexEventData}
  78195. */
  78196. PhysicsVortexEvent.prototype.getData = function () {
  78197. this._dataFetched = true;
  78198. return {
  78199. cylinder: this._cylinder,
  78200. };
  78201. };
  78202. /**
  78203. * Enables the vortex.
  78204. */
  78205. PhysicsVortexEvent.prototype.enable = function () {
  78206. this._tickCallback.call(this);
  78207. this._scene.registerBeforeRender(this._tickCallback);
  78208. };
  78209. /**
  78210. * Disables the cortex.
  78211. */
  78212. PhysicsVortexEvent.prototype.disable = function () {
  78213. this._scene.unregisterBeforeRender(this._tickCallback);
  78214. };
  78215. /**
  78216. * Disposes the sphere.
  78217. * @param {bolean} force
  78218. */
  78219. PhysicsVortexEvent.prototype.dispose = function (force) {
  78220. var _this = this;
  78221. if (force === void 0) { force = true; }
  78222. if (force) {
  78223. this._cylinder.dispose();
  78224. }
  78225. else {
  78226. setTimeout(function () {
  78227. if (!_this._dataFetched) {
  78228. _this._cylinder.dispose();
  78229. }
  78230. }, 0);
  78231. }
  78232. };
  78233. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78234. if (impostor.mass === 0) {
  78235. return null;
  78236. }
  78237. if (!this._intersectsWithCylinder(impostor)) {
  78238. return null;
  78239. }
  78240. if (impostor.object.getClassName() !== 'Mesh') {
  78241. return null;
  78242. }
  78243. var impostorObject = impostor.object;
  78244. var impostorObjectCenter = impostor.getObjectCenter();
  78245. 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)
  78246. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78247. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78248. var hit = ray.intersectsMesh(impostorObject);
  78249. var contactPoint = hit.pickedPoint;
  78250. if (!contactPoint) {
  78251. return null;
  78252. }
  78253. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78254. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78255. var directionToOrigin = contactPoint.normalize();
  78256. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78257. directionToOrigin = directionToOrigin.negate();
  78258. }
  78259. // TODO: find a more physically based solution
  78260. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78261. var forceX = directionToOrigin.x * this._strength / 8;
  78262. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78263. var forceZ = directionToOrigin.z * this._strength / 8;
  78264. }
  78265. else {
  78266. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78267. var forceY = this._originTop.y * this._updraftMultiplier;
  78268. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78269. }
  78270. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78271. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78272. return { force: force, contactPoint: impostorObjectCenter };
  78273. };
  78274. PhysicsVortexEvent.prototype._tick = function () {
  78275. var _this = this;
  78276. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78277. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78278. if (!impostorForceAndContactPoint) {
  78279. return;
  78280. }
  78281. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78282. });
  78283. };
  78284. /*** Helpers ***/
  78285. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78286. if (!this._cylinder) {
  78287. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78288. height: this._height,
  78289. diameter: this._radius * 2,
  78290. }, this._scene);
  78291. this._cylinder.isVisible = false;
  78292. }
  78293. };
  78294. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78295. var impostorObject = impostor.object;
  78296. this._prepareCylinder();
  78297. this._cylinder.position = this._cylinderPosition;
  78298. return this._cylinder.intersectsMesh(impostorObject, true);
  78299. };
  78300. return PhysicsVortexEvent;
  78301. }());
  78302. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78303. /***** Enums *****/
  78304. /**
  78305. * The strenght of the force in correspondence to the distance of the affected object
  78306. */
  78307. var PhysicsRadialImpulseFalloff;
  78308. (function (PhysicsRadialImpulseFalloff) {
  78309. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78310. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78311. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78312. /**
  78313. * The strenght of the force in correspondence to the distance of the affected object
  78314. */
  78315. var PhysicsUpdraftMode;
  78316. (function (PhysicsUpdraftMode) {
  78317. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78318. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78319. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78320. })(BABYLON || (BABYLON = {}));
  78321. //# sourceMappingURL=babylon.physicsHelper.js.map
  78322. "use strict";
  78323. var BABYLON;
  78324. (function (BABYLON) {
  78325. var CannonJSPlugin = /** @class */ (function () {
  78326. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78327. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78328. if (iterations === void 0) { iterations = 10; }
  78329. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78330. this.name = "CannonJSPlugin";
  78331. this._physicsMaterials = new Array();
  78332. this._fixedTimeStep = 1 / 60;
  78333. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78334. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  78335. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78336. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78337. this._tmpPosition = BABYLON.Vector3.Zero();
  78338. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78339. this._tmpUnityRotation = new BABYLON.Quaternion();
  78340. if (!this.isSupported()) {
  78341. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78342. return;
  78343. }
  78344. this._extendNamespace();
  78345. this.world = new this.BJSCANNON.World();
  78346. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78347. this.world.solver.iterations = iterations;
  78348. }
  78349. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78350. this.world.gravity.copy(gravity);
  78351. };
  78352. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78353. this._fixedTimeStep = timeStep;
  78354. };
  78355. CannonJSPlugin.prototype.getTimeStep = function () {
  78356. return this._fixedTimeStep;
  78357. };
  78358. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78359. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78360. };
  78361. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78362. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78363. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78364. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78365. };
  78366. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78367. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78368. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78369. impostor.physicsBody.applyForce(impulse, worldPoint);
  78370. };
  78371. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78372. //parent-child relationship. Does this impostor has a parent impostor?
  78373. if (impostor.parent) {
  78374. if (impostor.physicsBody) {
  78375. this.removePhysicsBody(impostor);
  78376. //TODO is that needed?
  78377. impostor.forceUpdate();
  78378. }
  78379. return;
  78380. }
  78381. //should a new body be created for this impostor?
  78382. if (impostor.isBodyInitRequired()) {
  78383. var shape = this._createShape(impostor);
  78384. //unregister events, if body is being changed
  78385. var oldBody = impostor.physicsBody;
  78386. if (oldBody) {
  78387. this.removePhysicsBody(impostor);
  78388. }
  78389. //create the body and material
  78390. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78391. var bodyCreationObject = {
  78392. mass: impostor.getParam("mass"),
  78393. material: material
  78394. };
  78395. // A simple extend, in case native options were used.
  78396. var nativeOptions = impostor.getParam("nativeOptions");
  78397. for (var key in nativeOptions) {
  78398. if (nativeOptions.hasOwnProperty(key)) {
  78399. bodyCreationObject[key] = nativeOptions[key];
  78400. }
  78401. }
  78402. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78403. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78404. this.world.addEventListener("preStep", impostor.beforeStep);
  78405. this.world.addEventListener("postStep", impostor.afterStep);
  78406. impostor.physicsBody.addShape(shape);
  78407. this.world.add(impostor.physicsBody);
  78408. //try to keep the body moving in the right direction by taking old properties.
  78409. //Should be tested!
  78410. if (oldBody) {
  78411. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78412. impostor.physicsBody[param].copy(oldBody[param]);
  78413. });
  78414. }
  78415. this._processChildMeshes(impostor);
  78416. }
  78417. //now update the body's transformation
  78418. this._updatePhysicsBodyTransformation(impostor);
  78419. };
  78420. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78421. var _this = this;
  78422. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78423. var currentRotation = mainImpostor.object.rotationQuaternion;
  78424. if (meshChildren.length) {
  78425. var processMesh = function (localPosition, mesh) {
  78426. if (!currentRotation || !mesh.rotationQuaternion) {
  78427. return;
  78428. }
  78429. var childImpostor = mesh.getPhysicsImpostor();
  78430. if (childImpostor) {
  78431. var parent = childImpostor.parent;
  78432. if (parent !== mainImpostor) {
  78433. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78434. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78435. if (childImpostor.physicsBody) {
  78436. _this.removePhysicsBody(childImpostor);
  78437. childImpostor.physicsBody = null;
  78438. }
  78439. childImpostor.parent = mainImpostor;
  78440. childImpostor.resetUpdateFlags();
  78441. 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));
  78442. //Add the mass of the children.
  78443. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78444. }
  78445. }
  78446. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78447. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78448. };
  78449. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78450. }
  78451. };
  78452. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78453. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78454. this.world.removeEventListener("preStep", impostor.beforeStep);
  78455. this.world.removeEventListener("postStep", impostor.afterStep);
  78456. this.world.remove(impostor.physicsBody);
  78457. };
  78458. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78459. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78460. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78461. if (!mainBody || !connectedBody) {
  78462. return;
  78463. }
  78464. var constraint;
  78465. var jointData = impostorJoint.joint.jointData;
  78466. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78467. var constraintData = {
  78468. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78469. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78470. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78471. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78472. maxForce: jointData.nativeParams.maxForce,
  78473. collideConnected: !!jointData.collision
  78474. };
  78475. switch (impostorJoint.joint.type) {
  78476. case BABYLON.PhysicsJoint.HingeJoint:
  78477. case BABYLON.PhysicsJoint.Hinge2Joint:
  78478. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78479. break;
  78480. case BABYLON.PhysicsJoint.DistanceJoint:
  78481. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78482. break;
  78483. case BABYLON.PhysicsJoint.SpringJoint:
  78484. var springData = jointData;
  78485. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78486. restLength: springData.length,
  78487. stiffness: springData.stiffness,
  78488. damping: springData.damping,
  78489. localAnchorA: constraintData.pivotA,
  78490. localAnchorB: constraintData.pivotB
  78491. });
  78492. break;
  78493. case BABYLON.PhysicsJoint.LockJoint:
  78494. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78495. break;
  78496. case BABYLON.PhysicsJoint.PointToPointJoint:
  78497. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78498. default:
  78499. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78500. break;
  78501. }
  78502. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78503. constraint.collideConnected = !!jointData.collision;
  78504. impostorJoint.joint.physicsJoint = constraint;
  78505. //don't add spring as constraint, as it is not one.
  78506. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78507. this.world.addConstraint(constraint);
  78508. }
  78509. else {
  78510. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78511. constraint.applyForce();
  78512. });
  78513. }
  78514. };
  78515. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78516. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78517. };
  78518. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78519. var index;
  78520. var mat;
  78521. for (index = 0; index < this._physicsMaterials.length; index++) {
  78522. mat = this._physicsMaterials[index];
  78523. if (mat.friction === friction && mat.restitution === restitution) {
  78524. return mat;
  78525. }
  78526. }
  78527. var currentMat = new this.BJSCANNON.Material(name);
  78528. currentMat.friction = friction;
  78529. currentMat.restitution = restitution;
  78530. this._physicsMaterials.push(currentMat);
  78531. return currentMat;
  78532. };
  78533. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78534. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78535. };
  78536. CannonJSPlugin.prototype._createShape = function (impostor) {
  78537. var object = impostor.object;
  78538. var returnValue;
  78539. var extendSize = impostor.getObjectExtendSize();
  78540. switch (impostor.type) {
  78541. case BABYLON.PhysicsImpostor.SphereImpostor:
  78542. var radiusX = extendSize.x;
  78543. var radiusY = extendSize.y;
  78544. var radiusZ = extendSize.z;
  78545. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78546. break;
  78547. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78548. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78549. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78550. break;
  78551. case BABYLON.PhysicsImpostor.BoxImpostor:
  78552. var box = extendSize.scale(0.5);
  78553. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78554. break;
  78555. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78556. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78557. returnValue = new this.BJSCANNON.Plane();
  78558. break;
  78559. case BABYLON.PhysicsImpostor.MeshImpostor:
  78560. // should transform the vertex data to world coordinates!!
  78561. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78562. var rawFaces = object.getIndices ? object.getIndices() : [];
  78563. if (!rawVerts)
  78564. return;
  78565. // get only scale! so the object could transform correctly.
  78566. var oldPosition = object.position.clone();
  78567. var oldRotation = object.rotation && object.rotation.clone();
  78568. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78569. object.position.copyFromFloats(0, 0, 0);
  78570. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78571. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78572. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78573. var transform = object.computeWorldMatrix(true);
  78574. // convert rawVerts to object space
  78575. var temp = new Array();
  78576. var index;
  78577. for (index = 0; index < rawVerts.length; index += 3) {
  78578. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78579. }
  78580. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78581. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78582. //now set back the transformation!
  78583. object.position.copyFrom(oldPosition);
  78584. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78585. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78586. break;
  78587. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78588. var oldPosition2 = object.position.clone();
  78589. var oldRotation2 = object.rotation && object.rotation.clone();
  78590. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78591. object.position.copyFromFloats(0, 0, 0);
  78592. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78593. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78594. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78595. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78596. returnValue = this._createHeightmap(object);
  78597. object.position.copyFrom(oldPosition2);
  78598. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78599. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78600. object.computeWorldMatrix(true);
  78601. break;
  78602. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78603. returnValue = new this.BJSCANNON.Particle();
  78604. break;
  78605. }
  78606. return returnValue;
  78607. };
  78608. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78609. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78610. var transform = object.computeWorldMatrix(true);
  78611. // convert rawVerts to object space
  78612. var temp = new Array();
  78613. var index;
  78614. for (index = 0; index < pos.length; index += 3) {
  78615. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78616. }
  78617. pos = temp;
  78618. var matrix = new Array();
  78619. //For now pointDepth will not be used and will be automatically calculated.
  78620. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78621. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78622. var boundingInfo = object.getBoundingInfo();
  78623. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78624. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78625. var elementSize = dim * 2 / arraySize;
  78626. for (var i = 0; i < pos.length; i = i + 3) {
  78627. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78628. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78629. var y = -pos[i + 2] + minY;
  78630. if (!matrix[x]) {
  78631. matrix[x] = [];
  78632. }
  78633. if (!matrix[x][z]) {
  78634. matrix[x][z] = y;
  78635. }
  78636. matrix[x][z] = Math.max(y, matrix[x][z]);
  78637. }
  78638. for (var x = 0; x <= arraySize; ++x) {
  78639. if (!matrix[x]) {
  78640. var loc = 1;
  78641. while (!matrix[(x + loc) % arraySize]) {
  78642. loc++;
  78643. }
  78644. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78645. //console.log("missing x", x);
  78646. }
  78647. for (var z = 0; z <= arraySize; ++z) {
  78648. if (!matrix[x][z]) {
  78649. var loc = 1;
  78650. var newValue;
  78651. while (newValue === undefined) {
  78652. newValue = matrix[x][(z + loc++) % arraySize];
  78653. }
  78654. matrix[x][z] = newValue;
  78655. }
  78656. }
  78657. }
  78658. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78659. elementSize: elementSize
  78660. });
  78661. //For future reference, needed for body transformation
  78662. shape.minY = minY;
  78663. return shape;
  78664. };
  78665. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78666. var object = impostor.object;
  78667. //make sure it is updated...
  78668. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78669. // The delta between the mesh position and the mesh bounding box center
  78670. var bInfo = object.getBoundingInfo();
  78671. if (!bInfo)
  78672. return;
  78673. var center = impostor.getObjectCenter();
  78674. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78675. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78676. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78677. this._tmpPosition.copyFrom(center);
  78678. var quaternion = object.rotationQuaternion;
  78679. if (!quaternion) {
  78680. return;
  78681. }
  78682. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  78683. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  78684. //-90 DEG in X, precalculated
  78685. quaternion = quaternion.multiply(this._minus90X);
  78686. //Invert! (Precalculated, 90 deg in X)
  78687. //No need to clone. this will never change.
  78688. impostor.setDeltaRotation(this._plus90X);
  78689. }
  78690. //If it is a heightfield, if should be centered.
  78691. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78692. var mesh = object;
  78693. var boundingInfo = mesh.getBoundingInfo();
  78694. //calculate the correct body position:
  78695. var rotationQuaternion = mesh.rotationQuaternion;
  78696. mesh.rotationQuaternion = this._tmpUnityRotation;
  78697. mesh.computeWorldMatrix(true);
  78698. //get original center with no rotation
  78699. var c = center.clone();
  78700. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78701. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78702. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78703. mesh.setPreTransformMatrix(p);
  78704. mesh.computeWorldMatrix(true);
  78705. //calculate the translation
  78706. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  78707. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  78708. //add it inverted to the delta
  78709. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  78710. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  78711. //rotation is back
  78712. mesh.rotationQuaternion = rotationQuaternion;
  78713. mesh.setPreTransformMatrix(oldPivot);
  78714. mesh.computeWorldMatrix(true);
  78715. }
  78716. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  78717. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  78718. //this._tmpPosition.copyFrom(object.position);
  78719. }
  78720. impostor.setDeltaPosition(this._tmpDeltaPosition);
  78721. //Now update the impostor object
  78722. impostor.physicsBody.position.copy(this._tmpPosition);
  78723. impostor.physicsBody.quaternion.copy(quaternion);
  78724. };
  78725. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78726. impostor.object.position.copyFrom(impostor.physicsBody.position);
  78727. if (impostor.object.rotationQuaternion) {
  78728. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  78729. }
  78730. };
  78731. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78732. impostor.physicsBody.position.copy(newPosition);
  78733. impostor.physicsBody.quaternion.copy(newRotation);
  78734. };
  78735. CannonJSPlugin.prototype.isSupported = function () {
  78736. return this.BJSCANNON !== undefined;
  78737. };
  78738. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78739. impostor.physicsBody.velocity.copy(velocity);
  78740. };
  78741. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78742. impostor.physicsBody.angularVelocity.copy(velocity);
  78743. };
  78744. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78745. var v = impostor.physicsBody.velocity;
  78746. if (!v) {
  78747. return null;
  78748. }
  78749. return new BABYLON.Vector3(v.x, v.y, v.z);
  78750. };
  78751. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78752. var v = impostor.physicsBody.angularVelocity;
  78753. if (!v) {
  78754. return null;
  78755. }
  78756. return new BABYLON.Vector3(v.x, v.y, v.z);
  78757. };
  78758. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78759. impostor.physicsBody.mass = mass;
  78760. impostor.physicsBody.updateMassProperties();
  78761. };
  78762. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  78763. return impostor.physicsBody.mass;
  78764. };
  78765. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78766. return impostor.physicsBody.material.friction;
  78767. };
  78768. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78769. impostor.physicsBody.material.friction = friction;
  78770. };
  78771. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78772. return impostor.physicsBody.material.restitution;
  78773. };
  78774. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78775. impostor.physicsBody.material.restitution = restitution;
  78776. };
  78777. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78778. impostor.physicsBody.sleep();
  78779. };
  78780. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78781. impostor.physicsBody.wakeUp();
  78782. };
  78783. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78784. joint.physicsJoint.distance = maxDistance;
  78785. };
  78786. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78787. // if (!motorIndex) {
  78788. // joint.physicsJoint.enableMotor();
  78789. // }
  78790. // }
  78791. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78792. // if (!motorIndex) {
  78793. // joint.physicsJoint.disableMotor();
  78794. // }
  78795. // }
  78796. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78797. if (!motorIndex) {
  78798. joint.physicsJoint.enableMotor();
  78799. joint.physicsJoint.setMotorSpeed(speed);
  78800. if (maxForce) {
  78801. this.setLimit(joint, maxForce);
  78802. }
  78803. }
  78804. };
  78805. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78806. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78807. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78808. };
  78809. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78810. var body = impostor.physicsBody;
  78811. mesh.position.x = body.position.x;
  78812. mesh.position.y = body.position.y;
  78813. mesh.position.z = body.position.z;
  78814. if (mesh.rotationQuaternion) {
  78815. mesh.rotationQuaternion.x = body.quaternion.x;
  78816. mesh.rotationQuaternion.y = body.quaternion.y;
  78817. mesh.rotationQuaternion.z = body.quaternion.z;
  78818. mesh.rotationQuaternion.w = body.quaternion.w;
  78819. }
  78820. };
  78821. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78822. var shape = impostor.physicsBody.shapes[0];
  78823. return shape.boundingSphereRadius;
  78824. };
  78825. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78826. var shape = impostor.physicsBody.shapes[0];
  78827. result.x = shape.halfExtents.x * 2;
  78828. result.y = shape.halfExtents.y * 2;
  78829. result.z = shape.halfExtents.z * 2;
  78830. };
  78831. CannonJSPlugin.prototype.dispose = function () {
  78832. };
  78833. CannonJSPlugin.prototype._extendNamespace = function () {
  78834. //this will force cannon to execute at least one step when using interpolation
  78835. var step_tmp1 = new this.BJSCANNON.Vec3();
  78836. var Engine = this.BJSCANNON;
  78837. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78838. maxSubSteps = maxSubSteps || 10;
  78839. timeSinceLastCalled = timeSinceLastCalled || 0;
  78840. if (timeSinceLastCalled === 0) {
  78841. this.internalStep(dt);
  78842. this.time += dt;
  78843. }
  78844. else {
  78845. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78846. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78847. var t0 = performance.now();
  78848. for (var i = 0; i !== internalSteps; i++) {
  78849. this.internalStep(dt);
  78850. if (performance.now() - t0 > dt * 1000) {
  78851. break;
  78852. }
  78853. }
  78854. this.time += timeSinceLastCalled;
  78855. var h = this.time % dt;
  78856. var h_div_dt = h / dt;
  78857. var interpvelo = step_tmp1;
  78858. var bodies = this.bodies;
  78859. for (var j = 0; j !== bodies.length; j++) {
  78860. var b = bodies[j];
  78861. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78862. b.position.vsub(b.previousPosition, interpvelo);
  78863. interpvelo.scale(h_div_dt, interpvelo);
  78864. b.position.vadd(interpvelo, b.interpolatedPosition);
  78865. }
  78866. else {
  78867. b.interpolatedPosition.copy(b.position);
  78868. b.interpolatedQuaternion.copy(b.quaternion);
  78869. }
  78870. }
  78871. }
  78872. };
  78873. };
  78874. return CannonJSPlugin;
  78875. }());
  78876. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78877. })(BABYLON || (BABYLON = {}));
  78878. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78879. "use strict";
  78880. var BABYLON;
  78881. (function (BABYLON) {
  78882. var OimoJSPlugin = /** @class */ (function () {
  78883. function OimoJSPlugin(iterations) {
  78884. this.name = "OimoJSPlugin";
  78885. this._tmpImpostorsArray = [];
  78886. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78887. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  78888. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  78889. this.world.worldscale(1);
  78890. this.world.clear();
  78891. //making sure no stats are calculated
  78892. this.world.isNoStat = true;
  78893. }
  78894. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78895. this.world.gravity.copy(gravity);
  78896. };
  78897. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78898. this.world.timeStep = timeStep;
  78899. };
  78900. OimoJSPlugin.prototype.getTimeStep = function () {
  78901. return this.world.timeStep;
  78902. };
  78903. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78904. var _this = this;
  78905. impostors.forEach(function (impostor) {
  78906. impostor.beforeStep();
  78907. });
  78908. this.world.step();
  78909. impostors.forEach(function (impostor) {
  78910. impostor.afterStep();
  78911. //update the ordered impostors array
  78912. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78913. });
  78914. //check for collisions
  78915. var contact = this.world.contacts;
  78916. while (contact !== null) {
  78917. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78918. contact = contact.next;
  78919. continue;
  78920. }
  78921. //is this body colliding with any other? get the impostor
  78922. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78923. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78924. if (!mainImpostor || !collidingImpostor) {
  78925. contact = contact.next;
  78926. continue;
  78927. }
  78928. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78929. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78930. contact = contact.next;
  78931. }
  78932. };
  78933. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78934. var mass = impostor.physicsBody.massInfo.mass;
  78935. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  78936. };
  78937. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78938. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78939. this.applyImpulse(impostor, force, contactPoint);
  78940. };
  78941. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78942. var _this = this;
  78943. //parent-child relationship. Does this impostor has a parent impostor?
  78944. if (impostor.parent) {
  78945. if (impostor.physicsBody) {
  78946. this.removePhysicsBody(impostor);
  78947. //TODO is that needed?
  78948. impostor.forceUpdate();
  78949. }
  78950. return;
  78951. }
  78952. if (impostor.isBodyInitRequired()) {
  78953. var bodyConfig = {
  78954. name: impostor.uniqueId,
  78955. //Oimo must have mass, also for static objects.
  78956. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78957. size: [],
  78958. type: [],
  78959. pos: [],
  78960. rot: [],
  78961. move: impostor.getParam("mass") !== 0,
  78962. //Supporting older versions of Oimo
  78963. world: this.world
  78964. };
  78965. var impostors = [impostor];
  78966. var addToArray = function (parent) {
  78967. if (!parent.getChildMeshes)
  78968. return;
  78969. parent.getChildMeshes().forEach(function (m) {
  78970. if (m.physicsImpostor) {
  78971. impostors.push(m.physicsImpostor);
  78972. //m.physicsImpostor._init();
  78973. }
  78974. });
  78975. };
  78976. addToArray(impostor.object);
  78977. var checkWithEpsilon_1 = function (value) {
  78978. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78979. };
  78980. impostors.forEach(function (i) {
  78981. if (!impostor.object.rotationQuaternion) {
  78982. return;
  78983. }
  78984. //get the correct bounding box
  78985. var oldQuaternion = i.object.rotationQuaternion;
  78986. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  78987. x: impostor.object.rotationQuaternion.x,
  78988. y: impostor.object.rotationQuaternion.y,
  78989. z: impostor.object.rotationQuaternion.z,
  78990. s: impostor.object.rotationQuaternion.w
  78991. });
  78992. var extendSize = i.getObjectExtendSize();
  78993. if (i === impostor) {
  78994. var center = impostor.getObjectCenter();
  78995. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78996. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78997. //Can also use Array.prototype.push.apply
  78998. bodyConfig.pos.push(center.x);
  78999. bodyConfig.pos.push(center.y);
  79000. bodyConfig.pos.push(center.z);
  79001. //tmp solution
  79002. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  79003. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  79004. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  79005. }
  79006. else {
  79007. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  79008. bodyConfig.pos.push(localPosition.x);
  79009. bodyConfig.pos.push(localPosition.y);
  79010. bodyConfig.pos.push(localPosition.z);
  79011. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  79012. bodyConfig.rot.push(0);
  79013. bodyConfig.rot.push(0);
  79014. bodyConfig.rot.push(0);
  79015. }
  79016. // register mesh
  79017. switch (i.type) {
  79018. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79019. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  79020. case BABYLON.PhysicsImpostor.SphereImpostor:
  79021. var radiusX = extendSize.x;
  79022. var radiusY = extendSize.y;
  79023. var radiusZ = extendSize.z;
  79024. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79025. bodyConfig.type.push('sphere');
  79026. //due to the way oimo works with compounds, add 3 times
  79027. bodyConfig.size.push(size);
  79028. bodyConfig.size.push(size);
  79029. bodyConfig.size.push(size);
  79030. break;
  79031. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79032. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79033. var sizeY = checkWithEpsilon_1(extendSize.y);
  79034. bodyConfig.type.push('cylinder');
  79035. bodyConfig.size.push(sizeX);
  79036. bodyConfig.size.push(sizeY);
  79037. //due to the way oimo works with compounds, add one more value.
  79038. bodyConfig.size.push(sizeY);
  79039. break;
  79040. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79041. case BABYLON.PhysicsImpostor.BoxImpostor:
  79042. default:
  79043. var sizeX = checkWithEpsilon_1(extendSize.x);
  79044. var sizeY = checkWithEpsilon_1(extendSize.y);
  79045. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79046. bodyConfig.type.push('box');
  79047. bodyConfig.size.push(sizeX);
  79048. bodyConfig.size.push(sizeY);
  79049. bodyConfig.size.push(sizeZ);
  79050. break;
  79051. }
  79052. //actually not needed, but hey...
  79053. i.object.rotationQuaternion = oldQuaternion;
  79054. });
  79055. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  79056. }
  79057. else {
  79058. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79059. }
  79060. impostor.setDeltaPosition(this._tmpPositionVector);
  79061. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79062. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79063. };
  79064. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79065. //impostor.physicsBody.dispose();
  79066. //Same as : (older oimo versions)
  79067. this.world.removeRigidBody(impostor.physicsBody);
  79068. };
  79069. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79070. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79071. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79072. if (!mainBody || !connectedBody) {
  79073. return;
  79074. }
  79075. var jointData = impostorJoint.joint.jointData;
  79076. var options = jointData.nativeParams || {};
  79077. var type;
  79078. var nativeJointData = {
  79079. body1: mainBody,
  79080. body2: connectedBody,
  79081. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79082. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79083. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79084. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79085. min: options.min,
  79086. max: options.max,
  79087. collision: options.collision || jointData.collision,
  79088. spring: options.spring,
  79089. //supporting older version of Oimo
  79090. world: this.world
  79091. };
  79092. switch (impostorJoint.joint.type) {
  79093. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79094. type = "jointBall";
  79095. break;
  79096. case BABYLON.PhysicsJoint.SpringJoint:
  79097. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79098. var springData = jointData;
  79099. nativeJointData.min = springData.length || nativeJointData.min;
  79100. //Max should also be set, just make sure it is at least min
  79101. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79102. case BABYLON.PhysicsJoint.DistanceJoint:
  79103. type = "jointDistance";
  79104. nativeJointData.max = jointData.maxDistance;
  79105. break;
  79106. case BABYLON.PhysicsJoint.PrismaticJoint:
  79107. type = "jointPrisme";
  79108. break;
  79109. case BABYLON.PhysicsJoint.SliderJoint:
  79110. type = "jointSlide";
  79111. break;
  79112. case BABYLON.PhysicsJoint.WheelJoint:
  79113. type = "jointWheel";
  79114. break;
  79115. case BABYLON.PhysicsJoint.HingeJoint:
  79116. default:
  79117. type = "jointHinge";
  79118. break;
  79119. }
  79120. nativeJointData.type = type;
  79121. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  79122. };
  79123. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79124. //Bug in Oimo prevents us from disposing a joint in the playground
  79125. //joint.joint.physicsJoint.dispose();
  79126. //So we will bruteforce it!
  79127. try {
  79128. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79129. }
  79130. catch (e) {
  79131. BABYLON.Tools.Warn(e);
  79132. }
  79133. };
  79134. OimoJSPlugin.prototype.isSupported = function () {
  79135. return this.BJSOIMO !== undefined;
  79136. };
  79137. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79138. if (!impostor.physicsBody.sleeping) {
  79139. //TODO check that
  79140. if (impostor.physicsBody.shapes.next) {
  79141. var parentShape = this._getLastShape(impostor.physicsBody);
  79142. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  79143. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  79144. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  79145. }
  79146. else {
  79147. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79148. }
  79149. if (impostor.object.rotationQuaternion) {
  79150. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79151. impostor.object.rotationQuaternion.normalize();
  79152. }
  79153. }
  79154. };
  79155. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79156. var body = impostor.physicsBody;
  79157. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  79158. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  79159. body.syncShapes();
  79160. body.awake();
  79161. };
  79162. OimoJSPlugin.prototype._getLastShape = function (body) {
  79163. var lastShape = body.shapes;
  79164. while (lastShape.next) {
  79165. lastShape = lastShape.next;
  79166. }
  79167. return lastShape;
  79168. };
  79169. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79170. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79171. };
  79172. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79173. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79174. };
  79175. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79176. var v = impostor.physicsBody.linearVelocity;
  79177. if (!v) {
  79178. return null;
  79179. }
  79180. return new BABYLON.Vector3(v.x, v.y, v.z);
  79181. };
  79182. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79183. var v = impostor.physicsBody.angularVelocity;
  79184. if (!v) {
  79185. return null;
  79186. }
  79187. return new BABYLON.Vector3(v.x, v.y, v.z);
  79188. };
  79189. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79190. var staticBody = mass === 0;
  79191. //this will actually set the body's density and not its mass.
  79192. //But this is how oimo treats the mass variable.
  79193. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79194. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79195. };
  79196. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79197. return impostor.physicsBody.shapes.density;
  79198. };
  79199. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79200. return impostor.physicsBody.shapes.friction;
  79201. };
  79202. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79203. impostor.physicsBody.shapes.friction = friction;
  79204. };
  79205. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79206. return impostor.physicsBody.shapes.restitution;
  79207. };
  79208. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79209. impostor.physicsBody.shapes.restitution = restitution;
  79210. };
  79211. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79212. impostor.physicsBody.sleep();
  79213. };
  79214. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79215. impostor.physicsBody.awake();
  79216. };
  79217. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79218. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79219. if (minDistance !== void 0) {
  79220. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79221. }
  79222. };
  79223. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79224. //TODO separate rotational and transational motors.
  79225. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79226. if (motor) {
  79227. motor.setMotor(speed, maxForce);
  79228. }
  79229. };
  79230. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79231. //TODO separate rotational and transational motors.
  79232. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79233. if (motor) {
  79234. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79235. }
  79236. };
  79237. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79238. var body = impostor.physicsBody;
  79239. mesh.position.x = body.position.x;
  79240. mesh.position.y = body.position.y;
  79241. mesh.position.z = body.position.z;
  79242. if (mesh.rotationQuaternion) {
  79243. mesh.rotationQuaternion.x = body.orientation.x;
  79244. mesh.rotationQuaternion.y = body.orientation.y;
  79245. mesh.rotationQuaternion.z = body.orientation.z;
  79246. mesh.rotationQuaternion.w = body.orientation.s;
  79247. }
  79248. };
  79249. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79250. return impostor.physicsBody.shapes.radius;
  79251. };
  79252. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79253. var shape = impostor.physicsBody.shapes;
  79254. result.x = shape.halfWidth * 2;
  79255. result.y = shape.halfHeight * 2;
  79256. result.z = shape.halfDepth * 2;
  79257. };
  79258. OimoJSPlugin.prototype.dispose = function () {
  79259. this.world.clear();
  79260. };
  79261. return OimoJSPlugin;
  79262. }());
  79263. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79264. })(BABYLON || (BABYLON = {}));
  79265. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79266. "use strict";
  79267. var BABYLON;
  79268. (function (BABYLON) {
  79269. /*
  79270. * Based on jsTGALoader - Javascript loader for TGA file
  79271. * By Vincent Thibault
  79272. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79273. */
  79274. var TGATools = /** @class */ (function () {
  79275. function TGATools() {
  79276. }
  79277. TGATools.GetTGAHeader = function (data) {
  79278. var offset = 0;
  79279. var header = {
  79280. id_length: data[offset++],
  79281. colormap_type: data[offset++],
  79282. image_type: data[offset++],
  79283. colormap_index: data[offset++] | data[offset++] << 8,
  79284. colormap_length: data[offset++] | data[offset++] << 8,
  79285. colormap_size: data[offset++],
  79286. origin: [
  79287. data[offset++] | data[offset++] << 8,
  79288. data[offset++] | data[offset++] << 8
  79289. ],
  79290. width: data[offset++] | data[offset++] << 8,
  79291. height: data[offset++] | data[offset++] << 8,
  79292. pixel_size: data[offset++],
  79293. flags: data[offset++]
  79294. };
  79295. return header;
  79296. };
  79297. TGATools.UploadContent = function (gl, data) {
  79298. // Not enough data to contain header ?
  79299. if (data.length < 19) {
  79300. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79301. return;
  79302. }
  79303. // Read Header
  79304. var offset = 18;
  79305. var header = TGATools.GetTGAHeader(data);
  79306. // Assume it's a valid Targa file.
  79307. if (header.id_length + offset > data.length) {
  79308. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79309. return;
  79310. }
  79311. // Skip not needed data
  79312. offset += header.id_length;
  79313. var use_rle = false;
  79314. var use_pal = false;
  79315. var use_grey = false;
  79316. // Get some informations.
  79317. switch (header.image_type) {
  79318. case TGATools._TYPE_RLE_INDEXED:
  79319. use_rle = true;
  79320. case TGATools._TYPE_INDEXED:
  79321. use_pal = true;
  79322. break;
  79323. case TGATools._TYPE_RLE_RGB:
  79324. use_rle = true;
  79325. case TGATools._TYPE_RGB:
  79326. // use_rgb = true;
  79327. break;
  79328. case TGATools._TYPE_RLE_GREY:
  79329. use_rle = true;
  79330. case TGATools._TYPE_GREY:
  79331. use_grey = true;
  79332. break;
  79333. }
  79334. var pixel_data;
  79335. // var numAlphaBits = header.flags & 0xf;
  79336. var pixel_size = header.pixel_size >> 3;
  79337. var pixel_total = header.width * header.height * pixel_size;
  79338. // Read palettes
  79339. var palettes;
  79340. if (use_pal) {
  79341. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79342. }
  79343. // Read LRE
  79344. if (use_rle) {
  79345. pixel_data = new Uint8Array(pixel_total);
  79346. var c, count, i;
  79347. var localOffset = 0;
  79348. var pixels = new Uint8Array(pixel_size);
  79349. while (offset < pixel_total && localOffset < pixel_total) {
  79350. c = data[offset++];
  79351. count = (c & 0x7f) + 1;
  79352. // RLE pixels
  79353. if (c & 0x80) {
  79354. // Bind pixel tmp array
  79355. for (i = 0; i < pixel_size; ++i) {
  79356. pixels[i] = data[offset++];
  79357. }
  79358. // Copy pixel array
  79359. for (i = 0; i < count; ++i) {
  79360. pixel_data.set(pixels, localOffset + i * pixel_size);
  79361. }
  79362. localOffset += pixel_size * count;
  79363. }
  79364. else {
  79365. count *= pixel_size;
  79366. for (i = 0; i < count; ++i) {
  79367. pixel_data[localOffset + i] = data[offset++];
  79368. }
  79369. localOffset += count;
  79370. }
  79371. }
  79372. }
  79373. else {
  79374. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79375. }
  79376. // Load to texture
  79377. var x_start, y_start, x_step, y_step, y_end, x_end;
  79378. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79379. default:
  79380. case TGATools._ORIGIN_UL:
  79381. x_start = 0;
  79382. x_step = 1;
  79383. x_end = header.width;
  79384. y_start = 0;
  79385. y_step = 1;
  79386. y_end = header.height;
  79387. break;
  79388. case TGATools._ORIGIN_BL:
  79389. x_start = 0;
  79390. x_step = 1;
  79391. x_end = header.width;
  79392. y_start = header.height - 1;
  79393. y_step = -1;
  79394. y_end = -1;
  79395. break;
  79396. case TGATools._ORIGIN_UR:
  79397. x_start = header.width - 1;
  79398. x_step = -1;
  79399. x_end = -1;
  79400. y_start = 0;
  79401. y_step = 1;
  79402. y_end = header.height;
  79403. break;
  79404. case TGATools._ORIGIN_BR:
  79405. x_start = header.width - 1;
  79406. x_step = -1;
  79407. x_end = -1;
  79408. y_start = header.height - 1;
  79409. y_step = -1;
  79410. y_end = -1;
  79411. break;
  79412. }
  79413. // Load the specify method
  79414. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79415. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79416. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79417. };
  79418. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79419. var image = pixel_data, colormap = palettes;
  79420. var width = header.width, height = header.height;
  79421. var color, i = 0, x, y;
  79422. var imageData = new Uint8Array(width * height * 4);
  79423. for (y = y_start; y !== y_end; y += y_step) {
  79424. for (x = x_start; x !== x_end; x += x_step, i++) {
  79425. color = image[i];
  79426. imageData[(x + width * y) * 4 + 3] = 255;
  79427. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79428. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79429. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79430. }
  79431. }
  79432. return imageData;
  79433. };
  79434. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79435. var image = pixel_data;
  79436. var width = header.width, height = header.height;
  79437. var color, i = 0, x, y;
  79438. var imageData = new Uint8Array(width * height * 4);
  79439. for (y = y_start; y !== y_end; y += y_step) {
  79440. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79441. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79442. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79443. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79444. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79445. imageData[(x + width * y) * 4 + 0] = r;
  79446. imageData[(x + width * y) * 4 + 1] = g;
  79447. imageData[(x + width * y) * 4 + 2] = b;
  79448. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79449. }
  79450. }
  79451. return imageData;
  79452. };
  79453. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79454. var image = pixel_data;
  79455. var width = header.width, height = header.height;
  79456. var i = 0, x, y;
  79457. var imageData = new Uint8Array(width * height * 4);
  79458. for (y = y_start; y !== y_end; y += y_step) {
  79459. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79460. imageData[(x + width * y) * 4 + 3] = 255;
  79461. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79462. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79463. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79464. }
  79465. }
  79466. return imageData;
  79467. };
  79468. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79469. var image = pixel_data;
  79470. var width = header.width, height = header.height;
  79471. var i = 0, x, y;
  79472. var imageData = new Uint8Array(width * height * 4);
  79473. for (y = y_start; y !== y_end; y += y_step) {
  79474. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79475. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79476. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79477. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79478. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79479. }
  79480. }
  79481. return imageData;
  79482. };
  79483. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79484. var image = pixel_data;
  79485. var width = header.width, height = header.height;
  79486. var color, i = 0, x, y;
  79487. var imageData = new Uint8Array(width * height * 4);
  79488. for (y = y_start; y !== y_end; y += y_step) {
  79489. for (x = x_start; x !== x_end; x += x_step, i++) {
  79490. color = image[i];
  79491. imageData[(x + width * y) * 4 + 0] = color;
  79492. imageData[(x + width * y) * 4 + 1] = color;
  79493. imageData[(x + width * y) * 4 + 2] = color;
  79494. imageData[(x + width * y) * 4 + 3] = 255;
  79495. }
  79496. }
  79497. return imageData;
  79498. };
  79499. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79500. var image = pixel_data;
  79501. var width = header.width, height = header.height;
  79502. var i = 0, x, y;
  79503. var imageData = new Uint8Array(width * height * 4);
  79504. for (y = y_start; y !== y_end; y += y_step) {
  79505. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79506. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79507. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79508. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79509. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79510. }
  79511. }
  79512. return imageData;
  79513. };
  79514. //private static _TYPE_NO_DATA = 0;
  79515. TGATools._TYPE_INDEXED = 1;
  79516. TGATools._TYPE_RGB = 2;
  79517. TGATools._TYPE_GREY = 3;
  79518. TGATools._TYPE_RLE_INDEXED = 9;
  79519. TGATools._TYPE_RLE_RGB = 10;
  79520. TGATools._TYPE_RLE_GREY = 11;
  79521. TGATools._ORIGIN_MASK = 0x30;
  79522. TGATools._ORIGIN_SHIFT = 0x04;
  79523. TGATools._ORIGIN_BL = 0x00;
  79524. TGATools._ORIGIN_BR = 0x01;
  79525. TGATools._ORIGIN_UL = 0x02;
  79526. TGATools._ORIGIN_UR = 0x03;
  79527. return TGATools;
  79528. }());
  79529. BABYLON.TGATools = TGATools;
  79530. })(BABYLON || (BABYLON = {}));
  79531. //# sourceMappingURL=babylon.tga.js.map
  79532. "use strict";
  79533. var BABYLON;
  79534. (function (BABYLON) {
  79535. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79536. // All values and structures referenced from:
  79537. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79538. var DDS_MAGIC = 0x20534444;
  79539. var
  79540. //DDSD_CAPS = 0x1,
  79541. //DDSD_HEIGHT = 0x2,
  79542. //DDSD_WIDTH = 0x4,
  79543. //DDSD_PITCH = 0x8,
  79544. //DDSD_PIXELFORMAT = 0x1000,
  79545. DDSD_MIPMAPCOUNT = 0x20000;
  79546. //DDSD_LINEARSIZE = 0x80000,
  79547. //DDSD_DEPTH = 0x800000;
  79548. // var DDSCAPS_COMPLEX = 0x8,
  79549. // DDSCAPS_MIPMAP = 0x400000,
  79550. // DDSCAPS_TEXTURE = 0x1000;
  79551. var DDSCAPS2_CUBEMAP = 0x200;
  79552. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79553. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79554. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79555. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79556. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79557. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79558. // DDSCAPS2_VOLUME = 0x200000;
  79559. var
  79560. //DDPF_ALPHAPIXELS = 0x1,
  79561. //DDPF_ALPHA = 0x2,
  79562. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79563. //DDPF_YUV = 0x200,
  79564. DDPF_LUMINANCE = 0x20000;
  79565. function FourCCToInt32(value) {
  79566. return value.charCodeAt(0) +
  79567. (value.charCodeAt(1) << 8) +
  79568. (value.charCodeAt(2) << 16) +
  79569. (value.charCodeAt(3) << 24);
  79570. }
  79571. function Int32ToFourCC(value) {
  79572. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79573. }
  79574. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79575. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79576. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79577. var FOURCC_DX10 = FourCCToInt32("DX10");
  79578. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79579. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79580. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79581. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79582. var headerLengthInt = 31; // The header length in 32 bit ints
  79583. // Offsets into the header array
  79584. var off_magic = 0;
  79585. var off_size = 1;
  79586. var off_flags = 2;
  79587. var off_height = 3;
  79588. var off_width = 4;
  79589. var off_mipmapCount = 7;
  79590. var off_pfFlags = 20;
  79591. var off_pfFourCC = 21;
  79592. var off_RGBbpp = 22;
  79593. var off_RMask = 23;
  79594. var off_GMask = 24;
  79595. var off_BMask = 25;
  79596. var off_AMask = 26;
  79597. // var off_caps1 = 27;
  79598. var off_caps2 = 28;
  79599. // var off_caps3 = 29;
  79600. // var off_caps4 = 30;
  79601. var off_dxgiFormat = 32;
  79602. ;
  79603. var DDSTools = /** @class */ (function () {
  79604. function DDSTools() {
  79605. }
  79606. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79607. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79608. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79609. var mipmapCount = 1;
  79610. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79611. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79612. }
  79613. var fourCC = header[off_pfFourCC];
  79614. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79615. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79616. switch (fourCC) {
  79617. case FOURCC_D3DFMT_R16G16B16A16F:
  79618. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79619. break;
  79620. case FOURCC_D3DFMT_R32G32B32A32F:
  79621. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79622. break;
  79623. case FOURCC_DX10:
  79624. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79625. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79626. break;
  79627. }
  79628. }
  79629. return {
  79630. width: header[off_width],
  79631. height: header[off_height],
  79632. mipmapCount: mipmapCount,
  79633. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79634. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79635. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79636. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79637. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79638. dxgiFormat: dxgiFormat,
  79639. textureType: textureType
  79640. };
  79641. };
  79642. DDSTools._ToHalfFloat = function (value) {
  79643. if (!DDSTools._FloatView) {
  79644. DDSTools._FloatView = new Float32Array(1);
  79645. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79646. }
  79647. DDSTools._FloatView[0] = value;
  79648. var x = DDSTools._Int32View[0];
  79649. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79650. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79651. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79652. /* If zero, or denormal, or exponent underflows too much for a denormal
  79653. * half, return signed zero. */
  79654. if (e < 103) {
  79655. return bits;
  79656. }
  79657. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79658. if (e > 142) {
  79659. bits |= 0x7c00;
  79660. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79661. * not Inf, so make sure we set one mantissa bit too. */
  79662. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79663. return bits;
  79664. }
  79665. /* If exponent underflows but not too much, return a denormal */
  79666. if (e < 113) {
  79667. m |= 0x0800;
  79668. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79669. * to 1, which is OK. */
  79670. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79671. return bits;
  79672. }
  79673. bits |= ((e - 112) << 10) | (m >> 1);
  79674. bits += m & 1;
  79675. return bits;
  79676. };
  79677. DDSTools._FromHalfFloat = function (value) {
  79678. var s = (value & 0x8000) >> 15;
  79679. var e = (value & 0x7C00) >> 10;
  79680. var f = value & 0x03FF;
  79681. if (e === 0) {
  79682. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  79683. }
  79684. else if (e == 0x1F) {
  79685. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79686. }
  79687. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79688. };
  79689. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79690. var destArray = new Float32Array(dataLength);
  79691. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79692. var index = 0;
  79693. for (var y = 0; y < height; y++) {
  79694. for (var x = 0; x < width; x++) {
  79695. var srcPos = (x + y * width) * 4;
  79696. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  79697. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  79698. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  79699. if (DDSTools.StoreLODInAlphaChannel) {
  79700. destArray[index + 3] = lod;
  79701. }
  79702. else {
  79703. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  79704. }
  79705. index += 4;
  79706. }
  79707. }
  79708. return destArray;
  79709. };
  79710. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79711. if (DDSTools.StoreLODInAlphaChannel) {
  79712. var destArray = new Uint16Array(dataLength);
  79713. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79714. var index = 0;
  79715. for (var y = 0; y < height; y++) {
  79716. for (var x = 0; x < width; x++) {
  79717. var srcPos = (x + y * width) * 4;
  79718. destArray[index] = srcData[srcPos];
  79719. destArray[index + 1] = srcData[srcPos + 1];
  79720. destArray[index + 2] = srcData[srcPos + 2];
  79721. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  79722. index += 4;
  79723. }
  79724. }
  79725. return destArray;
  79726. }
  79727. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  79728. };
  79729. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79730. if (DDSTools.StoreLODInAlphaChannel) {
  79731. var destArray = new Float32Array(dataLength);
  79732. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79733. var index = 0;
  79734. for (var y = 0; y < height; y++) {
  79735. for (var x = 0; x < width; x++) {
  79736. var srcPos = (x + y * width) * 4;
  79737. destArray[index] = srcData[srcPos];
  79738. destArray[index + 1] = srcData[srcPos + 1];
  79739. destArray[index + 2] = srcData[srcPos + 2];
  79740. destArray[index + 3] = lod;
  79741. index += 4;
  79742. }
  79743. }
  79744. return destArray;
  79745. }
  79746. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  79747. };
  79748. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79749. var destArray = new Uint8Array(dataLength);
  79750. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79751. var index = 0;
  79752. for (var y = 0; y < height; y++) {
  79753. for (var x = 0; x < width; x++) {
  79754. var srcPos = (x + y * width) * 4;
  79755. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  79756. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  79757. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  79758. if (DDSTools.StoreLODInAlphaChannel) {
  79759. destArray[index + 3] = lod;
  79760. }
  79761. else {
  79762. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79763. }
  79764. index += 4;
  79765. }
  79766. }
  79767. return destArray;
  79768. };
  79769. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79770. var destArray = new Uint8Array(dataLength);
  79771. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79772. var index = 0;
  79773. for (var y = 0; y < height; y++) {
  79774. for (var x = 0; x < width; x++) {
  79775. var srcPos = (x + y * width) * 4;
  79776. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79777. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79778. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79779. if (DDSTools.StoreLODInAlphaChannel) {
  79780. destArray[index + 3] = lod;
  79781. }
  79782. else {
  79783. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79784. }
  79785. index += 4;
  79786. }
  79787. }
  79788. return destArray;
  79789. };
  79790. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79791. var byteArray = new Uint8Array(dataLength);
  79792. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79793. var index = 0;
  79794. for (var y = 0; y < height; y++) {
  79795. for (var x = 0; x < width; x++) {
  79796. var srcPos = (x + y * width) * 4;
  79797. byteArray[index] = srcData[srcPos + rOffset];
  79798. byteArray[index + 1] = srcData[srcPos + gOffset];
  79799. byteArray[index + 2] = srcData[srcPos + bOffset];
  79800. byteArray[index + 3] = srcData[srcPos + aOffset];
  79801. index += 4;
  79802. }
  79803. }
  79804. return byteArray;
  79805. };
  79806. DDSTools._ExtractLongWordOrder = function (value) {
  79807. if (value === 0 || value === 255 || value === -16777216) {
  79808. return 0;
  79809. }
  79810. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79811. };
  79812. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79813. var byteArray = new Uint8Array(dataLength);
  79814. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79815. var index = 0;
  79816. for (var y = 0; y < height; y++) {
  79817. for (var x = 0; x < width; x++) {
  79818. var srcPos = (x + y * width) * 3;
  79819. byteArray[index] = srcData[srcPos + rOffset];
  79820. byteArray[index + 1] = srcData[srcPos + gOffset];
  79821. byteArray[index + 2] = srcData[srcPos + bOffset];
  79822. index += 3;
  79823. }
  79824. }
  79825. return byteArray;
  79826. };
  79827. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79828. var byteArray = new Uint8Array(dataLength);
  79829. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79830. var index = 0;
  79831. for (var y = 0; y < height; y++) {
  79832. for (var x = 0; x < width; x++) {
  79833. var srcPos = (x + y * width);
  79834. byteArray[index] = srcData[srcPos];
  79835. index++;
  79836. }
  79837. }
  79838. return byteArray;
  79839. };
  79840. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79841. if (lodIndex === void 0) { lodIndex = -1; }
  79842. var ext = engine.getCaps().s3tc;
  79843. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79844. var fourCC, width, height, dataLength = 0, dataOffset;
  79845. var byteArray, mipmapCount, mip;
  79846. var internalFormat = 0;
  79847. var format = 0;
  79848. var blockBytes = 1;
  79849. if (header[off_magic] !== DDS_MAGIC) {
  79850. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79851. return;
  79852. }
  79853. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79854. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79855. return;
  79856. }
  79857. if (info.isCompressed && !ext) {
  79858. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79859. return;
  79860. }
  79861. var bpp = header[off_RGBbpp];
  79862. dataOffset = header[off_size] + 4;
  79863. var computeFormats = false;
  79864. if (info.isFourCC) {
  79865. fourCC = header[off_pfFourCC];
  79866. switch (fourCC) {
  79867. case FOURCC_DXT1:
  79868. blockBytes = 8;
  79869. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79870. break;
  79871. case FOURCC_DXT3:
  79872. blockBytes = 16;
  79873. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79874. break;
  79875. case FOURCC_DXT5:
  79876. blockBytes = 16;
  79877. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79878. break;
  79879. case FOURCC_D3DFMT_R16G16B16A16F:
  79880. computeFormats = true;
  79881. break;
  79882. case FOURCC_D3DFMT_R32G32B32A32F:
  79883. computeFormats = true;
  79884. break;
  79885. case FOURCC_DX10:
  79886. // There is an additionnal header so dataOffset need to be changed
  79887. dataOffset += 5 * 4; // 5 uints
  79888. var supported = false;
  79889. switch (info.dxgiFormat) {
  79890. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79891. computeFormats = true;
  79892. supported = true;
  79893. break;
  79894. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79895. info.isRGB = true;
  79896. info.isFourCC = false;
  79897. bpp = 32;
  79898. supported = true;
  79899. break;
  79900. }
  79901. if (supported) {
  79902. break;
  79903. }
  79904. default:
  79905. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79906. return;
  79907. }
  79908. }
  79909. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79910. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79911. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79912. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79913. if (computeFormats) {
  79914. format = engine._getWebGLTextureType(info.textureType);
  79915. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79916. }
  79917. mipmapCount = 1;
  79918. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79919. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79920. }
  79921. for (var face = 0; face < faces; face++) {
  79922. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79923. width = header[off_width];
  79924. height = header[off_height];
  79925. for (mip = 0; mip < mipmapCount; ++mip) {
  79926. if (lodIndex === -1 || lodIndex === mip) {
  79927. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79928. var i = (lodIndex === -1) ? mip : 0;
  79929. if (!info.isCompressed && info.isFourCC) {
  79930. dataLength = width * height * 4;
  79931. var floatArray = null;
  79932. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79933. if (bpp === 128) {
  79934. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79935. }
  79936. else if (bpp === 64) {
  79937. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79938. }
  79939. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79940. format = engine._getWebGLTextureType(info.textureType);
  79941. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79942. }
  79943. else {
  79944. if (bpp === 128) {
  79945. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79946. }
  79947. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79948. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79949. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79950. format = engine._getWebGLTextureType(info.textureType);
  79951. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79952. }
  79953. else {
  79954. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79955. }
  79956. }
  79957. if (floatArray) {
  79958. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79959. }
  79960. }
  79961. else if (info.isRGB) {
  79962. if (bpp === 24) {
  79963. dataLength = width * height * 3;
  79964. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79965. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79966. }
  79967. else {
  79968. dataLength = width * height * 4;
  79969. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79970. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79971. }
  79972. }
  79973. else if (info.isLuminance) {
  79974. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79975. var unpaddedRowSize = width;
  79976. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79977. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79978. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79979. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79980. }
  79981. else {
  79982. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79983. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79984. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79985. }
  79986. }
  79987. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79988. width *= 0.5;
  79989. height *= 0.5;
  79990. width = Math.max(1.0, width);
  79991. height = Math.max(1.0, height);
  79992. }
  79993. if (currentFace !== undefined) {
  79994. // Loading a single face
  79995. break;
  79996. }
  79997. }
  79998. };
  79999. DDSTools.StoreLODInAlphaChannel = false;
  80000. return DDSTools;
  80001. }());
  80002. BABYLON.DDSTools = DDSTools;
  80003. })(BABYLON || (BABYLON = {}));
  80004. //# sourceMappingURL=babylon.dds.js.map
  80005. "use strict";
  80006. var BABYLON;
  80007. (function (BABYLON) {
  80008. /**
  80009. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  80010. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  80011. */
  80012. var KhronosTextureContainer = /** @class */ (function () {
  80013. /**
  80014. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80015. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80016. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80017. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80018. */
  80019. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80020. this.arrayBuffer = arrayBuffer;
  80021. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80022. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80023. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80024. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80025. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80026. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80027. BABYLON.Tools.Error("texture missing KTX identifier");
  80028. return;
  80029. }
  80030. // load the reset of the header in native 32 bit int
  80031. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80032. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80033. var oppositeEndianess = header[0] === 0x01020304;
  80034. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80035. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80036. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80037. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80038. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80039. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80040. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80041. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80042. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80043. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80044. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80045. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80046. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80047. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80048. if (this.glType !== 0) {
  80049. BABYLON.Tools.Error("only compressed formats currently supported");
  80050. return;
  80051. }
  80052. else {
  80053. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80054. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80055. }
  80056. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80057. BABYLON.Tools.Error("only 2D textures currently supported");
  80058. return;
  80059. }
  80060. if (this.numberOfArrayElements !== 0) {
  80061. BABYLON.Tools.Error("texture arrays not currently supported");
  80062. return;
  80063. }
  80064. if (this.numberOfFaces !== facesExpected) {
  80065. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80066. return;
  80067. }
  80068. // we now have a completely validated file, so could use existence of loadType as success
  80069. // would need to make this more elaborate & adjust checks above to support more than one load type
  80070. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80071. }
  80072. // not as fast hardware based, but will probably never need to use
  80073. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80074. return ((val & 0xFF) << 24)
  80075. | ((val & 0xFF00) << 8)
  80076. | ((val >> 8) & 0xFF00)
  80077. | ((val >> 24) & 0xFF);
  80078. };
  80079. /**
  80080. * It is assumed that the texture has already been created & is currently bound
  80081. */
  80082. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80083. switch (this.loadType) {
  80084. case KhronosTextureContainer.COMPRESSED_2D:
  80085. this._upload2DCompressedLevels(gl, loadMipmaps);
  80086. break;
  80087. case KhronosTextureContainer.TEX_2D:
  80088. case KhronosTextureContainer.COMPRESSED_3D:
  80089. case KhronosTextureContainer.TEX_3D:
  80090. }
  80091. };
  80092. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80093. // initialize width & height for level 1
  80094. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80095. var width = this.pixelWidth;
  80096. var height = this.pixelHeight;
  80097. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80098. for (var level = 0; level < mipmapCount; level++) {
  80099. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80100. for (var face = 0; face < this.numberOfFaces; face++) {
  80101. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80102. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80103. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80104. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80105. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80106. }
  80107. width = Math.max(1.0, width * 0.5);
  80108. height = Math.max(1.0, height * 0.5);
  80109. }
  80110. };
  80111. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80112. // load types
  80113. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80114. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80115. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80116. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80117. return KhronosTextureContainer;
  80118. }());
  80119. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80120. })(BABYLON || (BABYLON = {}));
  80121. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80122. "use strict";
  80123. var BABYLON;
  80124. (function (BABYLON) {
  80125. var Debug = /** @class */ (function () {
  80126. function Debug() {
  80127. }
  80128. Debug.AxesViewer = /** @class */ (function () {
  80129. function AxesViewer(scene, scaleLines) {
  80130. if (scaleLines === void 0) { scaleLines = 1; }
  80131. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80132. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80133. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80134. this.scaleLines = 1;
  80135. this.scaleLines = scaleLines;
  80136. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80137. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80138. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80139. this._xmesh.renderingGroupId = 2;
  80140. this._ymesh.renderingGroupId = 2;
  80141. this._zmesh.renderingGroupId = 2;
  80142. this._xmesh.material.checkReadyOnlyOnce = true;
  80143. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80144. this._ymesh.material.checkReadyOnlyOnce = true;
  80145. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80146. this._zmesh.material.checkReadyOnlyOnce = true;
  80147. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80148. this.scene = scene;
  80149. }
  80150. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80151. var scaleLines = this.scaleLines;
  80152. if (this._xmesh) {
  80153. this._xmesh.position.copyFrom(position);
  80154. }
  80155. if (this._ymesh) {
  80156. this._ymesh.position.copyFrom(position);
  80157. }
  80158. if (this._zmesh) {
  80159. this._zmesh.position.copyFrom(position);
  80160. }
  80161. var point2 = this._xline[1];
  80162. point2.x = xaxis.x * scaleLines;
  80163. point2.y = xaxis.y * scaleLines;
  80164. point2.z = xaxis.z * scaleLines;
  80165. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80166. point2 = this._yline[1];
  80167. point2.x = yaxis.x * scaleLines;
  80168. point2.y = yaxis.y * scaleLines;
  80169. point2.z = yaxis.z * scaleLines;
  80170. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80171. point2 = this._zline[1];
  80172. point2.x = zaxis.x * scaleLines;
  80173. point2.y = zaxis.y * scaleLines;
  80174. point2.z = zaxis.z * scaleLines;
  80175. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80176. };
  80177. AxesViewer.prototype.dispose = function () {
  80178. if (this._xmesh) {
  80179. this._xmesh.dispose();
  80180. }
  80181. if (this._ymesh) {
  80182. this._ymesh.dispose();
  80183. }
  80184. if (this._zmesh) {
  80185. this._zmesh.dispose();
  80186. }
  80187. this._xmesh = null;
  80188. this._ymesh = null;
  80189. this._zmesh = null;
  80190. this.scene = null;
  80191. };
  80192. return AxesViewer;
  80193. }());
  80194. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80195. __extends(BoneAxesViewer, _super);
  80196. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80197. if (scaleLines === void 0) { scaleLines = 1; }
  80198. var _this = _super.call(this, scene, scaleLines) || this;
  80199. _this.pos = BABYLON.Vector3.Zero();
  80200. _this.xaxis = BABYLON.Vector3.Zero();
  80201. _this.yaxis = BABYLON.Vector3.Zero();
  80202. _this.zaxis = BABYLON.Vector3.Zero();
  80203. _this.mesh = mesh;
  80204. _this.bone = bone;
  80205. return _this;
  80206. }
  80207. BoneAxesViewer.prototype.update = function () {
  80208. if (!this.mesh || !this.bone) {
  80209. return;
  80210. }
  80211. var bone = this.bone;
  80212. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80213. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80214. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80215. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80216. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80217. };
  80218. BoneAxesViewer.prototype.dispose = function () {
  80219. if (this.mesh) {
  80220. this.mesh = null;
  80221. this.bone = null;
  80222. _super.prototype.dispose.call(this);
  80223. }
  80224. };
  80225. return BoneAxesViewer;
  80226. }(Debug.AxesViewer));
  80227. Debug.PhysicsViewer = /** @class */ (function () {
  80228. function PhysicsViewer(scene) {
  80229. this._impostors = [];
  80230. this._meshes = [];
  80231. this._numMeshes = 0;
  80232. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80233. var physicEngine = this._scene.getPhysicsEngine();
  80234. if (physicEngine) {
  80235. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80236. }
  80237. }
  80238. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80239. var plugin = this._physicsEnginePlugin;
  80240. for (var i = 0; i < this._numMeshes; i++) {
  80241. var impostor = this._impostors[i];
  80242. if (!impostor) {
  80243. continue;
  80244. }
  80245. if (impostor.isDisposed) {
  80246. this.hideImpostor(this._impostors[i--]);
  80247. }
  80248. else {
  80249. var mesh = this._meshes[i];
  80250. if (mesh && plugin) {
  80251. plugin.syncMeshWithImpostor(mesh, impostor);
  80252. }
  80253. }
  80254. }
  80255. };
  80256. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80257. if (!this._scene) {
  80258. return;
  80259. }
  80260. for (var i = 0; i < this._numMeshes; i++) {
  80261. if (this._impostors[i] == impostor) {
  80262. return;
  80263. }
  80264. }
  80265. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80266. if (debugMesh) {
  80267. this._impostors[this._numMeshes] = impostor;
  80268. this._meshes[this._numMeshes] = debugMesh;
  80269. if (this._numMeshes === 0) {
  80270. this._renderFunction = this._updateDebugMeshes.bind(this);
  80271. this._scene.registerBeforeRender(this._renderFunction);
  80272. }
  80273. this._numMeshes++;
  80274. }
  80275. };
  80276. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80277. if (!impostor || !this._scene) {
  80278. return;
  80279. }
  80280. var removed = false;
  80281. for (var i = 0; i < this._numMeshes; i++) {
  80282. if (this._impostors[i] == impostor) {
  80283. var mesh = this._meshes[i];
  80284. if (!mesh) {
  80285. continue;
  80286. }
  80287. this._scene.removeMesh(mesh);
  80288. mesh.dispose();
  80289. this._numMeshes--;
  80290. if (this._numMeshes > 0) {
  80291. this._meshes[i] = this._meshes[this._numMeshes];
  80292. this._impostors[i] = this._impostors[this._numMeshes];
  80293. this._meshes[this._numMeshes] = null;
  80294. this._impostors[this._numMeshes] = null;
  80295. }
  80296. else {
  80297. this._meshes[0] = null;
  80298. this._impostors[0] = null;
  80299. }
  80300. removed = true;
  80301. break;
  80302. }
  80303. }
  80304. if (removed && this._numMeshes === 0) {
  80305. this._scene.unregisterBeforeRender(this._renderFunction);
  80306. }
  80307. };
  80308. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80309. if (!this._debugMaterial) {
  80310. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80311. this._debugMaterial.wireframe = true;
  80312. }
  80313. return this._debugMaterial;
  80314. };
  80315. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80316. if (!this._debugBoxMesh) {
  80317. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80318. this._debugBoxMesh.renderingGroupId = 1;
  80319. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80320. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80321. scene.removeMesh(this._debugBoxMesh);
  80322. }
  80323. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80324. };
  80325. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80326. if (!this._debugSphereMesh) {
  80327. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80328. this._debugSphereMesh.renderingGroupId = 1;
  80329. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80330. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80331. scene.removeMesh(this._debugSphereMesh);
  80332. }
  80333. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80334. };
  80335. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80336. var mesh = null;
  80337. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80338. mesh = this._getDebugBoxMesh(scene);
  80339. impostor.getBoxSizeToRef(mesh.scaling);
  80340. }
  80341. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80342. mesh = this._getDebugSphereMesh(scene);
  80343. var radius = impostor.getRadius();
  80344. mesh.scaling.x = radius * 2;
  80345. mesh.scaling.y = radius * 2;
  80346. mesh.scaling.z = radius * 2;
  80347. }
  80348. return mesh;
  80349. };
  80350. PhysicsViewer.prototype.dispose = function () {
  80351. for (var i = 0; i < this._numMeshes; i++) {
  80352. this.hideImpostor(this._impostors[i]);
  80353. }
  80354. if (this._debugBoxMesh) {
  80355. this._debugBoxMesh.dispose();
  80356. }
  80357. if (this._debugSphereMesh) {
  80358. this._debugSphereMesh.dispose();
  80359. }
  80360. if (this._debugMaterial) {
  80361. this._debugMaterial.dispose();
  80362. }
  80363. this._impostors.length = 0;
  80364. this._scene = null;
  80365. this._physicsEnginePlugin = null;
  80366. };
  80367. return PhysicsViewer;
  80368. }());
  80369. Debug.SkeletonViewer = /** @class */ (function () {
  80370. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80371. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80372. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80373. this.skeleton = skeleton;
  80374. this.mesh = mesh;
  80375. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80376. this.renderingGroupId = renderingGroupId;
  80377. this.color = BABYLON.Color3.White();
  80378. this._debugLines = new Array();
  80379. this._isEnabled = false;
  80380. this._scene = scene;
  80381. this.update();
  80382. this._renderFunction = this.update.bind(this);
  80383. }
  80384. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80385. get: function () {
  80386. return this._isEnabled;
  80387. },
  80388. set: function (value) {
  80389. if (this._isEnabled === value) {
  80390. return;
  80391. }
  80392. this._isEnabled = value;
  80393. if (value) {
  80394. this._scene.registerBeforeRender(this._renderFunction);
  80395. }
  80396. else {
  80397. this._scene.unregisterBeforeRender(this._renderFunction);
  80398. }
  80399. },
  80400. enumerable: true,
  80401. configurable: true
  80402. });
  80403. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80404. if (x === void 0) { x = 0; }
  80405. if (y === void 0) { y = 0; }
  80406. if (z === void 0) { z = 0; }
  80407. var tmat = BABYLON.Tmp.Matrix[0];
  80408. var parentBone = bone.getParent();
  80409. tmat.copyFrom(bone.getLocalMatrix());
  80410. if (x !== 0 || y !== 0 || z !== 0) {
  80411. var tmat2 = BABYLON.Tmp.Matrix[1];
  80412. BABYLON.Matrix.IdentityToRef(tmat2);
  80413. tmat2.m[12] = x;
  80414. tmat2.m[13] = y;
  80415. tmat2.m[14] = z;
  80416. tmat2.multiplyToRef(tmat, tmat);
  80417. }
  80418. if (parentBone) {
  80419. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80420. }
  80421. tmat.multiplyToRef(meshMat, tmat);
  80422. position.x = tmat.m[12];
  80423. position.y = tmat.m[13];
  80424. position.z = tmat.m[14];
  80425. };
  80426. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80427. var len = bones.length;
  80428. var meshPos = this.mesh.position;
  80429. for (var i = 0; i < len; i++) {
  80430. var bone = bones[i];
  80431. var points = this._debugLines[i];
  80432. if (!points) {
  80433. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80434. this._debugLines[i] = points;
  80435. }
  80436. this._getBonePosition(points[0], bone, meshMat);
  80437. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80438. points[0].subtractInPlace(meshPos);
  80439. points[1].subtractInPlace(meshPos);
  80440. }
  80441. };
  80442. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80443. var len = bones.length;
  80444. var boneNum = 0;
  80445. var meshPos = this.mesh.position;
  80446. for (var i = len - 1; i >= 0; i--) {
  80447. var childBone = bones[i];
  80448. var parentBone = childBone.getParent();
  80449. if (!parentBone) {
  80450. continue;
  80451. }
  80452. var points = this._debugLines[boneNum];
  80453. if (!points) {
  80454. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80455. this._debugLines[boneNum] = points;
  80456. }
  80457. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80458. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80459. points[0].subtractInPlace(meshPos);
  80460. points[1].subtractInPlace(meshPos);
  80461. boneNum++;
  80462. }
  80463. };
  80464. SkeletonViewer.prototype.update = function () {
  80465. if (this.autoUpdateBonesMatrices) {
  80466. this.skeleton.computeAbsoluteTransforms();
  80467. }
  80468. if (this.skeleton.bones[0].length === undefined) {
  80469. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80470. }
  80471. else {
  80472. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80473. }
  80474. if (!this._debugMesh) {
  80475. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80476. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80477. }
  80478. else {
  80479. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80480. }
  80481. this._debugMesh.position.copyFrom(this.mesh.position);
  80482. this._debugMesh.color = this.color;
  80483. };
  80484. SkeletonViewer.prototype.dispose = function () {
  80485. if (this._debugMesh) {
  80486. this.isEnabled = false;
  80487. this._debugMesh.dispose();
  80488. this._debugMesh = null;
  80489. }
  80490. };
  80491. return SkeletonViewer;
  80492. }());
  80493. return Debug;
  80494. }());
  80495. BABYLON.Debug = Debug;
  80496. })(BABYLON || (BABYLON = {}));
  80497. //# sourceMappingURL=babylon.debugModules.js.map
  80498. "use strict";
  80499. var BABYLON;
  80500. (function (BABYLON) {
  80501. var RayHelper = /** @class */ (function () {
  80502. function RayHelper(ray) {
  80503. this.ray = ray;
  80504. }
  80505. RayHelper.CreateAndShow = function (ray, scene, color) {
  80506. var helper = new RayHelper(ray);
  80507. helper.show(scene, color);
  80508. return helper;
  80509. };
  80510. RayHelper.prototype.show = function (scene, color) {
  80511. if (!this._renderFunction && this.ray) {
  80512. var ray = this.ray;
  80513. this._renderFunction = this._render.bind(this);
  80514. this._scene = scene;
  80515. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80516. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80517. if (this._renderFunction) {
  80518. this._scene.registerBeforeRender(this._renderFunction);
  80519. }
  80520. }
  80521. if (color && this._renderLine) {
  80522. this._renderLine.color.copyFrom(color);
  80523. }
  80524. };
  80525. RayHelper.prototype.hide = function () {
  80526. if (this._renderFunction && this._scene) {
  80527. this._scene.unregisterBeforeRender(this._renderFunction);
  80528. this._scene = null;
  80529. this._renderFunction = null;
  80530. if (this._renderLine) {
  80531. this._renderLine.dispose();
  80532. this._renderLine = null;
  80533. }
  80534. this._renderPoints = [];
  80535. }
  80536. };
  80537. RayHelper.prototype._render = function () {
  80538. var ray = this.ray;
  80539. if (!ray) {
  80540. return;
  80541. }
  80542. var point = this._renderPoints[1];
  80543. var len = Math.min(ray.length, 1000000);
  80544. point.copyFrom(ray.direction);
  80545. point.scaleInPlace(len);
  80546. point.addInPlace(ray.origin);
  80547. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80548. };
  80549. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80550. this._attachedToMesh = mesh;
  80551. var ray = this.ray;
  80552. if (!ray) {
  80553. return;
  80554. }
  80555. if (!ray.direction) {
  80556. ray.direction = BABYLON.Vector3.Zero();
  80557. }
  80558. if (!ray.origin) {
  80559. ray.origin = BABYLON.Vector3.Zero();
  80560. }
  80561. if (length) {
  80562. ray.length = length;
  80563. }
  80564. if (!meshSpaceOrigin) {
  80565. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80566. }
  80567. if (!meshSpaceDirection) {
  80568. // -1 so that this will work with Mesh.lookAt
  80569. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80570. }
  80571. if (!this._meshSpaceDirection) {
  80572. this._meshSpaceDirection = meshSpaceDirection.clone();
  80573. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80574. }
  80575. else {
  80576. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80577. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80578. }
  80579. if (!this._updateToMeshFunction) {
  80580. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80581. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80582. }
  80583. this._updateToMesh();
  80584. };
  80585. RayHelper.prototype.detachFromMesh = function () {
  80586. if (this._attachedToMesh) {
  80587. if (this._updateToMeshFunction) {
  80588. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80589. }
  80590. this._attachedToMesh = null;
  80591. this._updateToMeshFunction = null;
  80592. }
  80593. };
  80594. RayHelper.prototype._updateToMesh = function () {
  80595. var ray = this.ray;
  80596. if (!this._attachedToMesh || !ray) {
  80597. return;
  80598. }
  80599. if (this._attachedToMesh._isDisposed) {
  80600. this.detachFromMesh();
  80601. return;
  80602. }
  80603. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80604. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80605. };
  80606. RayHelper.prototype.dispose = function () {
  80607. this.hide();
  80608. this.detachFromMesh();
  80609. this.ray = null;
  80610. };
  80611. return RayHelper;
  80612. }());
  80613. BABYLON.RayHelper = RayHelper;
  80614. })(BABYLON || (BABYLON = {}));
  80615. //# sourceMappingURL=babylon.rayHelper.js.map
  80616. "use strict";
  80617. var BABYLON;
  80618. (function (BABYLON) {
  80619. // load the inspector using require, if not present in the global namespace.
  80620. var DebugLayer = /** @class */ (function () {
  80621. function DebugLayer(scene) {
  80622. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80623. this._scene = scene;
  80624. // load inspector using require, if it doesn't exist on the global namespace.
  80625. }
  80626. /** Creates the inspector window. */
  80627. DebugLayer.prototype._createInspector = function (config) {
  80628. if (config === void 0) { config = {}; }
  80629. var popup = config.popup || false;
  80630. var initialTab = config.initialTab || 0;
  80631. var parentElement = config.parentElement || null;
  80632. if (!this._inspector) {
  80633. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80634. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80635. } // else nothing to do,; instance is already existing
  80636. };
  80637. DebugLayer.prototype.isVisible = function () {
  80638. if (!this._inspector) {
  80639. return false;
  80640. }
  80641. return true;
  80642. };
  80643. DebugLayer.prototype.hide = function () {
  80644. if (this._inspector) {
  80645. try {
  80646. this._inspector.dispose();
  80647. }
  80648. catch (e) {
  80649. // If the inspector has been removed directly from the inspector tool
  80650. }
  80651. this._inspector = null;
  80652. }
  80653. };
  80654. DebugLayer.prototype.show = function (config) {
  80655. if (config === void 0) { config = {}; }
  80656. if (typeof this.BJSINSPECTOR == 'undefined') {
  80657. // Load inspector and add it to the DOM
  80658. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80659. }
  80660. else {
  80661. // Otherwise creates the inspector
  80662. this._createInspector(config);
  80663. }
  80664. };
  80665. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80666. return DebugLayer;
  80667. }());
  80668. BABYLON.DebugLayer = DebugLayer;
  80669. })(BABYLON || (BABYLON = {}));
  80670. //# sourceMappingURL=babylon.debugLayer.js.map
  80671. "use strict";
  80672. var BABYLON;
  80673. (function (BABYLON) {
  80674. var BoundingBoxRenderer = /** @class */ (function () {
  80675. function BoundingBoxRenderer(scene) {
  80676. this.frontColor = new BABYLON.Color3(1, 1, 1);
  80677. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  80678. this.showBackLines = true;
  80679. this.renderList = new BABYLON.SmartArray(32);
  80680. this._vertexBuffers = {};
  80681. this._scene = scene;
  80682. }
  80683. BoundingBoxRenderer.prototype._prepareRessources = function () {
  80684. if (this._colorShader) {
  80685. return;
  80686. }
  80687. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80688. attributes: [BABYLON.VertexBuffer.PositionKind],
  80689. uniforms: ["world", "viewProjection", "color"]
  80690. });
  80691. var engine = this._scene.getEngine();
  80692. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80693. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80694. this._createIndexBuffer();
  80695. };
  80696. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  80697. var engine = this._scene.getEngine();
  80698. 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]);
  80699. };
  80700. BoundingBoxRenderer.prototype._rebuild = function () {
  80701. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80702. if (vb) {
  80703. vb._rebuild();
  80704. }
  80705. this._createIndexBuffer();
  80706. };
  80707. BoundingBoxRenderer.prototype.reset = function () {
  80708. this.renderList.reset();
  80709. };
  80710. BoundingBoxRenderer.prototype.render = function () {
  80711. if (this.renderList.length === 0) {
  80712. return;
  80713. }
  80714. this._prepareRessources();
  80715. if (!this._colorShader.isReady()) {
  80716. return;
  80717. }
  80718. var engine = this._scene.getEngine();
  80719. engine.setDepthWrite(false);
  80720. this._colorShader._preBind();
  80721. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  80722. var boundingBox = this.renderList.data[boundingBoxIndex];
  80723. var min = boundingBox.minimum;
  80724. var max = boundingBox.maximum;
  80725. var diff = max.subtract(min);
  80726. var median = min.add(diff.scale(0.5));
  80727. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80728. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80729. .multiply(boundingBox.getWorldMatrix());
  80730. // VBOs
  80731. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80732. if (this.showBackLines) {
  80733. // Back
  80734. engine.setDepthFunctionToGreaterOrEqual();
  80735. this._scene.resetCachedMaterial();
  80736. this._colorShader.setColor4("color", this.backColor.toColor4());
  80737. this._colorShader.bind(worldMatrix);
  80738. // Draw order
  80739. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80740. }
  80741. // Front
  80742. engine.setDepthFunctionToLess();
  80743. this._scene.resetCachedMaterial();
  80744. this._colorShader.setColor4("color", this.frontColor.toColor4());
  80745. this._colorShader.bind(worldMatrix);
  80746. // Draw order
  80747. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80748. }
  80749. this._colorShader.unbind();
  80750. engine.setDepthFunctionToLessOrEqual();
  80751. engine.setDepthWrite(true);
  80752. };
  80753. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  80754. this._prepareRessources();
  80755. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  80756. return;
  80757. }
  80758. var engine = this._scene.getEngine();
  80759. engine.setDepthWrite(false);
  80760. engine.setColorWrite(false);
  80761. this._colorShader._preBind();
  80762. var boundingBox = mesh._boundingInfo.boundingBox;
  80763. var min = boundingBox.minimum;
  80764. var max = boundingBox.maximum;
  80765. var diff = max.subtract(min);
  80766. var median = min.add(diff.scale(0.5));
  80767. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80768. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80769. .multiply(boundingBox.getWorldMatrix());
  80770. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80771. engine.setDepthFunctionToLess();
  80772. this._scene.resetCachedMaterial();
  80773. this._colorShader.bind(worldMatrix);
  80774. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80775. this._colorShader.unbind();
  80776. engine.setDepthFunctionToLessOrEqual();
  80777. engine.setDepthWrite(true);
  80778. engine.setColorWrite(true);
  80779. };
  80780. BoundingBoxRenderer.prototype.dispose = function () {
  80781. if (!this._colorShader) {
  80782. return;
  80783. }
  80784. this.renderList.dispose();
  80785. this._colorShader.dispose();
  80786. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80787. if (buffer) {
  80788. buffer.dispose();
  80789. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80790. }
  80791. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80792. };
  80793. return BoundingBoxRenderer;
  80794. }());
  80795. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80796. })(BABYLON || (BABYLON = {}));
  80797. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80798. "use strict";
  80799. var BABYLON;
  80800. (function (BABYLON) {
  80801. var MorphTarget = /** @class */ (function () {
  80802. function MorphTarget(name, influence) {
  80803. if (influence === void 0) { influence = 0; }
  80804. this.name = name;
  80805. this.animations = new Array();
  80806. this._positions = null;
  80807. this._normals = null;
  80808. this._tangents = null;
  80809. this.onInfluenceChanged = new BABYLON.Observable();
  80810. this.influence = influence;
  80811. }
  80812. Object.defineProperty(MorphTarget.prototype, "influence", {
  80813. get: function () {
  80814. return this._influence;
  80815. },
  80816. set: function (influence) {
  80817. if (this._influence === influence) {
  80818. return;
  80819. }
  80820. var previous = this._influence;
  80821. this._influence = influence;
  80822. if (this.onInfluenceChanged.hasObservers) {
  80823. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80824. }
  80825. },
  80826. enumerable: true,
  80827. configurable: true
  80828. });
  80829. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80830. get: function () {
  80831. return !!this._positions;
  80832. },
  80833. enumerable: true,
  80834. configurable: true
  80835. });
  80836. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80837. get: function () {
  80838. return !!this._normals;
  80839. },
  80840. enumerable: true,
  80841. configurable: true
  80842. });
  80843. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80844. get: function () {
  80845. return !!this._tangents;
  80846. },
  80847. enumerable: true,
  80848. configurable: true
  80849. });
  80850. MorphTarget.prototype.setPositions = function (data) {
  80851. this._positions = data;
  80852. };
  80853. MorphTarget.prototype.getPositions = function () {
  80854. return this._positions;
  80855. };
  80856. MorphTarget.prototype.setNormals = function (data) {
  80857. this._normals = data;
  80858. };
  80859. MorphTarget.prototype.getNormals = function () {
  80860. return this._normals;
  80861. };
  80862. MorphTarget.prototype.setTangents = function (data) {
  80863. this._tangents = data;
  80864. };
  80865. MorphTarget.prototype.getTangents = function () {
  80866. return this._tangents;
  80867. };
  80868. /**
  80869. * Serializes the current target into a Serialization object.
  80870. * Returns the serialized object.
  80871. */
  80872. MorphTarget.prototype.serialize = function () {
  80873. var serializationObject = {};
  80874. serializationObject.name = this.name;
  80875. serializationObject.influence = this.influence;
  80876. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80877. if (this.hasNormals) {
  80878. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80879. }
  80880. if (this.hasTangents) {
  80881. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80882. }
  80883. // Animations
  80884. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80885. return serializationObject;
  80886. };
  80887. // Statics
  80888. MorphTarget.Parse = function (serializationObject) {
  80889. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80890. result.setPositions(serializationObject.positions);
  80891. if (serializationObject.normals) {
  80892. result.setNormals(serializationObject.normals);
  80893. }
  80894. if (serializationObject.tangents) {
  80895. result.setTangents(serializationObject.tangents);
  80896. }
  80897. // Animations
  80898. if (serializationObject.animations) {
  80899. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80900. var parsedAnimation = serializationObject.animations[animationIndex];
  80901. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80902. }
  80903. }
  80904. return result;
  80905. };
  80906. MorphTarget.FromMesh = function (mesh, name, influence) {
  80907. if (!name) {
  80908. name = mesh.name;
  80909. }
  80910. var result = new MorphTarget(name, influence);
  80911. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80912. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80913. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80914. }
  80915. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80916. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80917. }
  80918. return result;
  80919. };
  80920. return MorphTarget;
  80921. }());
  80922. BABYLON.MorphTarget = MorphTarget;
  80923. })(BABYLON || (BABYLON = {}));
  80924. //# sourceMappingURL=babylon.morphTarget.js.map
  80925. "use strict";
  80926. var BABYLON;
  80927. (function (BABYLON) {
  80928. var MorphTargetManager = /** @class */ (function () {
  80929. function MorphTargetManager(scene) {
  80930. if (scene === void 0) { scene = null; }
  80931. this._targets = new Array();
  80932. this._targetObservable = new Array();
  80933. this._activeTargets = new BABYLON.SmartArray(16);
  80934. this._supportsNormals = false;
  80935. this._supportsTangents = false;
  80936. this._vertexCount = 0;
  80937. this._uniqueId = 0;
  80938. this._tempInfluences = new Array();
  80939. if (!scene) {
  80940. scene = BABYLON.Engine.LastCreatedScene;
  80941. }
  80942. this._scene = scene;
  80943. if (this._scene) {
  80944. this._scene.morphTargetManagers.push(this);
  80945. this._uniqueId = this._scene.getUniqueId();
  80946. }
  80947. }
  80948. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80949. get: function () {
  80950. return this._uniqueId;
  80951. },
  80952. enumerable: true,
  80953. configurable: true
  80954. });
  80955. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80956. get: function () {
  80957. return this._vertexCount;
  80958. },
  80959. enumerable: true,
  80960. configurable: true
  80961. });
  80962. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80963. get: function () {
  80964. return this._supportsNormals;
  80965. },
  80966. enumerable: true,
  80967. configurable: true
  80968. });
  80969. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80970. get: function () {
  80971. return this._supportsTangents;
  80972. },
  80973. enumerable: true,
  80974. configurable: true
  80975. });
  80976. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80977. get: function () {
  80978. return this._targets.length;
  80979. },
  80980. enumerable: true,
  80981. configurable: true
  80982. });
  80983. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80984. get: function () {
  80985. return this._activeTargets.length;
  80986. },
  80987. enumerable: true,
  80988. configurable: true
  80989. });
  80990. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80991. get: function () {
  80992. return this._influences;
  80993. },
  80994. enumerable: true,
  80995. configurable: true
  80996. });
  80997. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80998. return this._activeTargets.data[index];
  80999. };
  81000. MorphTargetManager.prototype.getTarget = function (index) {
  81001. return this._targets[index];
  81002. };
  81003. MorphTargetManager.prototype.addTarget = function (target) {
  81004. var _this = this;
  81005. this._targets.push(target);
  81006. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  81007. _this._syncActiveTargets(needUpdate);
  81008. }));
  81009. this._syncActiveTargets(true);
  81010. };
  81011. MorphTargetManager.prototype.removeTarget = function (target) {
  81012. var index = this._targets.indexOf(target);
  81013. if (index >= 0) {
  81014. this._targets.splice(index, 1);
  81015. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81016. this._syncActiveTargets(true);
  81017. }
  81018. };
  81019. /**
  81020. * Serializes the current manager into a Serialization object.
  81021. * Returns the serialized object.
  81022. */
  81023. MorphTargetManager.prototype.serialize = function () {
  81024. var serializationObject = {};
  81025. serializationObject.id = this.uniqueId;
  81026. serializationObject.targets = [];
  81027. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81028. var target = _a[_i];
  81029. serializationObject.targets.push(target.serialize());
  81030. }
  81031. return serializationObject;
  81032. };
  81033. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81034. var influenceCount = 0;
  81035. this._activeTargets.reset();
  81036. this._supportsNormals = true;
  81037. this._supportsTangents = true;
  81038. this._vertexCount = 0;
  81039. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81040. var target = _a[_i];
  81041. this._activeTargets.push(target);
  81042. this._tempInfluences[influenceCount++] = target.influence;
  81043. var positions = target.getPositions();
  81044. if (positions) {
  81045. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81046. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81047. var vertexCount = positions.length / 3;
  81048. if (this._vertexCount === 0) {
  81049. this._vertexCount = vertexCount;
  81050. }
  81051. else if (this._vertexCount !== vertexCount) {
  81052. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81053. return;
  81054. }
  81055. }
  81056. }
  81057. if (!this._influences || this._influences.length !== influenceCount) {
  81058. this._influences = new Float32Array(influenceCount);
  81059. }
  81060. for (var index = 0; index < influenceCount; index++) {
  81061. this._influences[index] = this._tempInfluences[index];
  81062. }
  81063. if (needUpdate && this._scene) {
  81064. // Flag meshes as dirty to resync with the active targets
  81065. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81066. var mesh = _c[_b];
  81067. if (mesh.morphTargetManager === this) {
  81068. mesh._syncGeometryWithMorphTargetManager();
  81069. }
  81070. }
  81071. }
  81072. };
  81073. // Statics
  81074. MorphTargetManager.Parse = function (serializationObject, scene) {
  81075. var result = new MorphTargetManager(scene);
  81076. result._uniqueId = serializationObject.id;
  81077. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81078. var targetData = _a[_i];
  81079. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81080. }
  81081. return result;
  81082. };
  81083. return MorphTargetManager;
  81084. }());
  81085. BABYLON.MorphTargetManager = MorphTargetManager;
  81086. })(BABYLON || (BABYLON = {}));
  81087. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81088. "use strict";
  81089. var BABYLON;
  81090. (function (BABYLON) {
  81091. var Octree = /** @class */ (function () {
  81092. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81093. if (maxDepth === void 0) { maxDepth = 2; }
  81094. this.maxDepth = maxDepth;
  81095. this.dynamicContent = new Array();
  81096. this._maxBlockCapacity = maxBlockCapacity || 64;
  81097. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81098. this._creationFunc = creationFunc;
  81099. }
  81100. // Methods
  81101. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81102. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81103. };
  81104. Octree.prototype.addMesh = function (entry) {
  81105. for (var index = 0; index < this.blocks.length; index++) {
  81106. var block = this.blocks[index];
  81107. block.addEntry(entry);
  81108. }
  81109. };
  81110. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81111. this._selectionContent.reset();
  81112. for (var index = 0; index < this.blocks.length; index++) {
  81113. var block = this.blocks[index];
  81114. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81115. }
  81116. if (allowDuplicate) {
  81117. this._selectionContent.concat(this.dynamicContent);
  81118. }
  81119. else {
  81120. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81121. }
  81122. return this._selectionContent;
  81123. };
  81124. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81125. this._selectionContent.reset();
  81126. for (var index = 0; index < this.blocks.length; index++) {
  81127. var block = this.blocks[index];
  81128. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81129. }
  81130. if (allowDuplicate) {
  81131. this._selectionContent.concat(this.dynamicContent);
  81132. }
  81133. else {
  81134. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81135. }
  81136. return this._selectionContent;
  81137. };
  81138. Octree.prototype.intersectsRay = function (ray) {
  81139. this._selectionContent.reset();
  81140. for (var index = 0; index < this.blocks.length; index++) {
  81141. var block = this.blocks[index];
  81142. block.intersectsRay(ray, this._selectionContent);
  81143. }
  81144. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81145. return this._selectionContent;
  81146. };
  81147. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81148. target.blocks = new Array();
  81149. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81150. // Segmenting space
  81151. for (var x = 0; x < 2; x++) {
  81152. for (var y = 0; y < 2; y++) {
  81153. for (var z = 0; z < 2; z++) {
  81154. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81155. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81156. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81157. block.addEntries(entries);
  81158. target.blocks.push(block);
  81159. }
  81160. }
  81161. }
  81162. };
  81163. Octree.CreationFuncForMeshes = function (entry, block) {
  81164. var boundingInfo = entry.getBoundingInfo();
  81165. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81166. block.entries.push(entry);
  81167. }
  81168. };
  81169. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81170. var boundingInfo = entry.getBoundingInfo();
  81171. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81172. block.entries.push(entry);
  81173. }
  81174. };
  81175. return Octree;
  81176. }());
  81177. BABYLON.Octree = Octree;
  81178. })(BABYLON || (BABYLON = {}));
  81179. //# sourceMappingURL=babylon.octree.js.map
  81180. "use strict";
  81181. var BABYLON;
  81182. (function (BABYLON) {
  81183. var OctreeBlock = /** @class */ (function () {
  81184. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81185. this.entries = new Array();
  81186. this._boundingVectors = new Array();
  81187. this._capacity = capacity;
  81188. this._depth = depth;
  81189. this._maxDepth = maxDepth;
  81190. this._creationFunc = creationFunc;
  81191. this._minPoint = minPoint;
  81192. this._maxPoint = maxPoint;
  81193. this._boundingVectors.push(minPoint.clone());
  81194. this._boundingVectors.push(maxPoint.clone());
  81195. this._boundingVectors.push(minPoint.clone());
  81196. this._boundingVectors[2].x = maxPoint.x;
  81197. this._boundingVectors.push(minPoint.clone());
  81198. this._boundingVectors[3].y = maxPoint.y;
  81199. this._boundingVectors.push(minPoint.clone());
  81200. this._boundingVectors[4].z = maxPoint.z;
  81201. this._boundingVectors.push(maxPoint.clone());
  81202. this._boundingVectors[5].z = minPoint.z;
  81203. this._boundingVectors.push(maxPoint.clone());
  81204. this._boundingVectors[6].x = minPoint.x;
  81205. this._boundingVectors.push(maxPoint.clone());
  81206. this._boundingVectors[7].y = minPoint.y;
  81207. }
  81208. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81209. // Property
  81210. get: function () {
  81211. return this._capacity;
  81212. },
  81213. enumerable: true,
  81214. configurable: true
  81215. });
  81216. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81217. get: function () {
  81218. return this._minPoint;
  81219. },
  81220. enumerable: true,
  81221. configurable: true
  81222. });
  81223. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81224. get: function () {
  81225. return this._maxPoint;
  81226. },
  81227. enumerable: true,
  81228. configurable: true
  81229. });
  81230. // Methods
  81231. OctreeBlock.prototype.addEntry = function (entry) {
  81232. if (this.blocks) {
  81233. for (var index = 0; index < this.blocks.length; index++) {
  81234. var block = this.blocks[index];
  81235. block.addEntry(entry);
  81236. }
  81237. return;
  81238. }
  81239. this._creationFunc(entry, this);
  81240. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81241. this.createInnerBlocks();
  81242. }
  81243. };
  81244. OctreeBlock.prototype.addEntries = function (entries) {
  81245. for (var index = 0; index < entries.length; index++) {
  81246. var mesh = entries[index];
  81247. this.addEntry(mesh);
  81248. }
  81249. };
  81250. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81251. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81252. if (this.blocks) {
  81253. for (var index = 0; index < this.blocks.length; index++) {
  81254. var block = this.blocks[index];
  81255. block.select(frustumPlanes, selection, allowDuplicate);
  81256. }
  81257. return;
  81258. }
  81259. if (allowDuplicate) {
  81260. selection.concat(this.entries);
  81261. }
  81262. else {
  81263. selection.concatWithNoDuplicate(this.entries);
  81264. }
  81265. }
  81266. };
  81267. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81268. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81269. if (this.blocks) {
  81270. for (var index = 0; index < this.blocks.length; index++) {
  81271. var block = this.blocks[index];
  81272. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81273. }
  81274. return;
  81275. }
  81276. if (allowDuplicate) {
  81277. selection.concat(this.entries);
  81278. }
  81279. else {
  81280. selection.concatWithNoDuplicate(this.entries);
  81281. }
  81282. }
  81283. };
  81284. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81285. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81286. if (this.blocks) {
  81287. for (var index = 0; index < this.blocks.length; index++) {
  81288. var block = this.blocks[index];
  81289. block.intersectsRay(ray, selection);
  81290. }
  81291. return;
  81292. }
  81293. selection.concatWithNoDuplicate(this.entries);
  81294. }
  81295. };
  81296. OctreeBlock.prototype.createInnerBlocks = function () {
  81297. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81298. };
  81299. return OctreeBlock;
  81300. }());
  81301. BABYLON.OctreeBlock = OctreeBlock;
  81302. })(BABYLON || (BABYLON = {}));
  81303. //# sourceMappingURL=babylon.octreeBlock.js.map
  81304. "use strict";
  81305. var BABYLON;
  81306. (function (BABYLON) {
  81307. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81308. __extends(VRDistortionCorrectionPostProcess, _super);
  81309. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81310. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81311. 'LensCenter',
  81312. 'Scale',
  81313. 'ScaleIn',
  81314. 'HmdWarpParam'
  81315. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81316. _this._isRightEye = isRightEye;
  81317. _this._distortionFactors = vrMetrics.distortionK;
  81318. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81319. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81320. _this.adaptScaleToCurrentViewport = true;
  81321. _this.onSizeChangedObservable.add(function () {
  81322. _this.aspectRatio = _this.width * .5 / _this.height;
  81323. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81324. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81325. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81326. });
  81327. _this.onApplyObservable.add(function (effect) {
  81328. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81329. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81330. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81331. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81332. });
  81333. return _this;
  81334. }
  81335. return VRDistortionCorrectionPostProcess;
  81336. }(BABYLON.PostProcess));
  81337. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81338. })(BABYLON || (BABYLON = {}));
  81339. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81340. "use strict";
  81341. var BABYLON;
  81342. (function (BABYLON) {
  81343. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81344. __extends(AnaglyphPostProcess, _super);
  81345. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81346. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81347. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81348. _this.onApplyObservable.add(function (effect) {
  81349. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81350. });
  81351. return _this;
  81352. }
  81353. return AnaglyphPostProcess;
  81354. }(BABYLON.PostProcess));
  81355. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81356. })(BABYLON || (BABYLON = {}));
  81357. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81358. "use strict";
  81359. var BABYLON;
  81360. (function (BABYLON) {
  81361. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81362. __extends(StereoscopicInterlacePostProcess, _super);
  81363. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81364. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81365. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81366. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81367. _this.onSizeChangedObservable.add(function () {
  81368. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81369. });
  81370. _this.onApplyObservable.add(function (effect) {
  81371. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81372. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81373. });
  81374. return _this;
  81375. }
  81376. return StereoscopicInterlacePostProcess;
  81377. }(BABYLON.PostProcess));
  81378. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81379. })(BABYLON || (BABYLON = {}));
  81380. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81381. "use strict";
  81382. var BABYLON;
  81383. (function (BABYLON) {
  81384. /**
  81385. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81386. * Screen rotation is taken into account.
  81387. */
  81388. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81389. function FreeCameraDeviceOrientationInput() {
  81390. var _this = this;
  81391. this._screenOrientationAngle = 0;
  81392. this._screenQuaternion = new BABYLON.Quaternion();
  81393. this._alpha = 0;
  81394. this._beta = 0;
  81395. this._gamma = 0;
  81396. this._orientationChanged = function () {
  81397. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81398. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81399. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81400. };
  81401. this._deviceOrientation = function (evt) {
  81402. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81403. _this._beta = evt.beta !== null ? evt.beta : 0;
  81404. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81405. };
  81406. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81407. this._orientationChanged();
  81408. }
  81409. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81410. get: function () {
  81411. return this._camera;
  81412. },
  81413. set: function (camera) {
  81414. this._camera = camera;
  81415. if (this._camera != null && !this._camera.rotationQuaternion) {
  81416. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81417. }
  81418. },
  81419. enumerable: true,
  81420. configurable: true
  81421. });
  81422. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81423. window.addEventListener("orientationchange", this._orientationChanged);
  81424. window.addEventListener("deviceorientation", this._deviceOrientation);
  81425. //In certain cases, the attach control is called AFTER orientation was changed,
  81426. //So this is needed.
  81427. this._orientationChanged();
  81428. };
  81429. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81430. window.removeEventListener("orientationchange", this._orientationChanged);
  81431. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81432. };
  81433. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81434. //if no device orientation provided, don't update the rotation.
  81435. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81436. if (!this._alpha)
  81437. return;
  81438. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81439. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81440. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81441. //Mirror on XY Plane
  81442. this._camera.rotationQuaternion.z *= -1;
  81443. this._camera.rotationQuaternion.w *= -1;
  81444. };
  81445. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81446. return "FreeCameraDeviceOrientationInput";
  81447. };
  81448. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81449. return "deviceOrientation";
  81450. };
  81451. return FreeCameraDeviceOrientationInput;
  81452. }());
  81453. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81454. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81455. })(BABYLON || (BABYLON = {}));
  81456. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81457. "use strict";
  81458. var BABYLON;
  81459. (function (BABYLON) {
  81460. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81461. function ArcRotateCameraVRDeviceOrientationInput() {
  81462. this.alphaCorrection = 1;
  81463. this.betaCorrection = 1;
  81464. this.gammaCorrection = 1;
  81465. this._alpha = 0;
  81466. this._gamma = 0;
  81467. this._dirty = false;
  81468. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81469. }
  81470. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81471. this.camera.attachControl(element, noPreventDefault);
  81472. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81473. };
  81474. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81475. if (evt.alpha !== null) {
  81476. this._alpha = +evt.alpha | 0;
  81477. }
  81478. if (evt.gamma !== null) {
  81479. this._gamma = +evt.gamma | 0;
  81480. }
  81481. this._dirty = true;
  81482. };
  81483. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81484. if (this._dirty) {
  81485. this._dirty = false;
  81486. if (this._gamma < 0) {
  81487. this._gamma = 180 + this._gamma;
  81488. }
  81489. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81490. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81491. }
  81492. };
  81493. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81494. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81495. };
  81496. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81497. return "ArcRotateCameraVRDeviceOrientationInput";
  81498. };
  81499. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81500. return "VRDeviceOrientation";
  81501. };
  81502. return ArcRotateCameraVRDeviceOrientationInput;
  81503. }());
  81504. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81505. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81506. })(BABYLON || (BABYLON = {}));
  81507. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81508. "use strict";
  81509. var BABYLON;
  81510. (function (BABYLON) {
  81511. var VRCameraMetrics = /** @class */ (function () {
  81512. function VRCameraMetrics() {
  81513. this.compensateDistortion = true;
  81514. }
  81515. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81516. get: function () {
  81517. return this.hResolution / (2 * this.vResolution);
  81518. },
  81519. enumerable: true,
  81520. configurable: true
  81521. });
  81522. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81523. get: function () {
  81524. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81525. },
  81526. enumerable: true,
  81527. configurable: true
  81528. });
  81529. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81530. get: function () {
  81531. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81532. var h = (4 * meters) / this.hScreenSize;
  81533. return BABYLON.Matrix.Translation(h, 0, 0);
  81534. },
  81535. enumerable: true,
  81536. configurable: true
  81537. });
  81538. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81539. get: function () {
  81540. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81541. var h = (4 * meters) / this.hScreenSize;
  81542. return BABYLON.Matrix.Translation(-h, 0, 0);
  81543. },
  81544. enumerable: true,
  81545. configurable: true
  81546. });
  81547. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81548. get: function () {
  81549. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81550. },
  81551. enumerable: true,
  81552. configurable: true
  81553. });
  81554. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81555. get: function () {
  81556. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81557. },
  81558. enumerable: true,
  81559. configurable: true
  81560. });
  81561. VRCameraMetrics.GetDefault = function () {
  81562. var result = new VRCameraMetrics();
  81563. result.hResolution = 1280;
  81564. result.vResolution = 800;
  81565. result.hScreenSize = 0.149759993;
  81566. result.vScreenSize = 0.0935999975;
  81567. result.vScreenCenter = 0.0467999987;
  81568. result.eyeToScreenDistance = 0.0410000011;
  81569. result.lensSeparationDistance = 0.0635000020;
  81570. result.interpupillaryDistance = 0.0640000030;
  81571. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81572. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81573. result.postProcessScaleFactor = 1.714605507808412;
  81574. result.lensCenterOffset = 0.151976421;
  81575. return result;
  81576. };
  81577. return VRCameraMetrics;
  81578. }());
  81579. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81580. })(BABYLON || (BABYLON = {}));
  81581. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81582. "use strict";
  81583. var BABYLON;
  81584. (function (BABYLON) {
  81585. /**
  81586. * This represents a WebVR camera.
  81587. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81588. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81589. */
  81590. var WebVRFreeCamera = /** @class */ (function (_super) {
  81591. __extends(WebVRFreeCamera, _super);
  81592. /**
  81593. * Instantiates a WebVRFreeCamera.
  81594. * @param name The name of the WebVRFreeCamera
  81595. * @param position The starting anchor position for the camera
  81596. * @param scene The scene the camera belongs to
  81597. * @param webVROptions a set of customizable options for the webVRCamera
  81598. */
  81599. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81600. if (webVROptions === void 0) { webVROptions = {}; }
  81601. var _this = _super.call(this, name, position, scene) || this;
  81602. _this.webVROptions = webVROptions;
  81603. /**
  81604. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81605. */
  81606. _this._vrDevice = null;
  81607. /**
  81608. * The rawPose of the vrDevice.
  81609. */
  81610. _this.rawPose = null;
  81611. _this._specsVersion = "1.1";
  81612. _this._attached = false;
  81613. _this._descendants = [];
  81614. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81615. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81616. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81617. _this._standingMatrix = null;
  81618. /**
  81619. * Represents device position in babylon space.
  81620. */
  81621. _this.devicePosition = BABYLON.Vector3.Zero();
  81622. /**
  81623. * Represents device rotation in babylon space.
  81624. */
  81625. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81626. /**
  81627. * The scale of the device to be used when translating from device space to babylon space.
  81628. */
  81629. _this.deviceScaleFactor = 1;
  81630. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81631. _this._worldToDevice = BABYLON.Matrix.Identity();
  81632. /**
  81633. * References to the webVR controllers for the vrDevice.
  81634. */
  81635. _this.controllers = [];
  81636. /**
  81637. * Emits an event when a controller is attached.
  81638. */
  81639. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81640. /**
  81641. * Emits an event when a controller's mesh has been loaded;
  81642. */
  81643. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81644. /**
  81645. * If the rig cameras be used as parent instead of this camera.
  81646. */
  81647. _this.rigParenting = true;
  81648. _this._defaultHeight = undefined;
  81649. _this._workingVector = BABYLON.Vector3.Zero();
  81650. _this._oneVector = BABYLON.Vector3.One();
  81651. _this._workingMatrix = BABYLON.Matrix.Identity();
  81652. _this._cache.position = BABYLON.Vector3.Zero();
  81653. if (webVROptions.defaultHeight) {
  81654. _this._defaultHeight = webVROptions.defaultHeight;
  81655. _this.position.y = _this._defaultHeight;
  81656. }
  81657. _this.minZ = 0.1;
  81658. //legacy support - the compensation boolean was removed.
  81659. if (arguments.length === 5) {
  81660. _this.webVROptions = arguments[4];
  81661. }
  81662. // default webVR options
  81663. if (_this.webVROptions.trackPosition == undefined) {
  81664. _this.webVROptions.trackPosition = true;
  81665. }
  81666. if (_this.webVROptions.controllerMeshes == undefined) {
  81667. _this.webVROptions.controllerMeshes = true;
  81668. }
  81669. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81670. _this.webVROptions.defaultLightingOnControllers = true;
  81671. }
  81672. _this.rotationQuaternion = new BABYLON.Quaternion();
  81673. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81674. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81675. }
  81676. //enable VR
  81677. var engine = _this.getEngine();
  81678. _this._onVREnabled = function (success) { if (success) {
  81679. _this.initControllers();
  81680. } };
  81681. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  81682. engine.initWebVR().add(function (event) {
  81683. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  81684. return;
  81685. }
  81686. _this._vrDevice = event.vrDisplay;
  81687. //reset the rig parameters.
  81688. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81689. if (_this._attached) {
  81690. _this.getEngine().enableVR();
  81691. }
  81692. });
  81693. if (typeof (VRFrameData) !== "undefined")
  81694. _this._frameData = new VRFrameData();
  81695. /**
  81696. * The idea behind the following lines:
  81697. * objects that have the camera as parent should actually have the rig cameras as a parent.
  81698. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  81699. * the second will not show it correctly.
  81700. *
  81701. * To solve this - each object that has the camera as parent will be added to a protected array.
  81702. * When the rig camera renders, it will take this array and set all of those to be its children.
  81703. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  81704. * Amazing!
  81705. */
  81706. scene.onBeforeCameraRenderObservable.add(function (camera) {
  81707. if (camera.parent === _this && _this.rigParenting) {
  81708. _this._descendants = _this.getDescendants(true, function (n) {
  81709. // don't take the cameras or the controllers!
  81710. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  81711. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  81712. return !isController && !isRigCamera;
  81713. });
  81714. _this._descendants.forEach(function (node) {
  81715. node.parent = camera;
  81716. });
  81717. }
  81718. });
  81719. scene.onAfterCameraRenderObservable.add(function (camera) {
  81720. if (camera.parent === _this && _this.rigParenting) {
  81721. _this._descendants.forEach(function (node) {
  81722. node.parent = _this;
  81723. });
  81724. }
  81725. });
  81726. return _this;
  81727. }
  81728. /**
  81729. * Gets the device distance from the ground in meters.
  81730. * @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.
  81731. */
  81732. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  81733. if (this._standingMatrix) {
  81734. // Add standing matrix offset to get real offset from ground in room
  81735. this._standingMatrix.getTranslationToRef(this._workingVector);
  81736. return this._deviceRoomPosition.y + this._workingVector.y;
  81737. }
  81738. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  81739. return this._defaultHeight || 0;
  81740. };
  81741. /**
  81742. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81743. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  81744. */
  81745. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  81746. var _this = this;
  81747. if (callback === void 0) { callback = function (bool) { }; }
  81748. // Use standing matrix if available
  81749. this.getEngine().initWebVRAsync().then(function (result) {
  81750. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  81751. callback(false);
  81752. }
  81753. else {
  81754. _this._standingMatrix = new BABYLON.Matrix();
  81755. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  81756. if (!_this.getScene().useRightHandedSystem) {
  81757. [2, 6, 8, 9, 14].forEach(function (num) {
  81758. if (_this._standingMatrix) {
  81759. _this._standingMatrix.m[num] *= -1;
  81760. }
  81761. });
  81762. }
  81763. callback(true);
  81764. }
  81765. });
  81766. };
  81767. /**
  81768. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81769. * @returns A promise with a boolean set to if the standing matrix is supported.
  81770. */
  81771. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81772. var _this = this;
  81773. return new Promise(function (res, rej) {
  81774. _this.useStandingMatrix(function (supported) {
  81775. res(supported);
  81776. });
  81777. });
  81778. };
  81779. /**
  81780. * Disposes the camera
  81781. */
  81782. WebVRFreeCamera.prototype.dispose = function () {
  81783. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81784. _super.prototype.dispose.call(this);
  81785. };
  81786. /**
  81787. * Gets a vrController by name.
  81788. * @param name The name of the controller to retreive
  81789. * @returns the controller matching the name specified or null if not found
  81790. */
  81791. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81792. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81793. var gp = _a[_i];
  81794. if (gp.hand === name) {
  81795. return gp;
  81796. }
  81797. }
  81798. return null;
  81799. };
  81800. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81801. /**
  81802. * The controller corrisponding to the users left hand.
  81803. */
  81804. get: function () {
  81805. if (!this._leftController) {
  81806. this._leftController = this.getControllerByName("left");
  81807. }
  81808. return this._leftController;
  81809. },
  81810. enumerable: true,
  81811. configurable: true
  81812. });
  81813. ;
  81814. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81815. /**
  81816. * The controller corrisponding to the users right hand.
  81817. */
  81818. get: function () {
  81819. if (!this._rightController) {
  81820. this._rightController = this.getControllerByName("right");
  81821. }
  81822. return this._rightController;
  81823. },
  81824. enumerable: true,
  81825. configurable: true
  81826. });
  81827. ;
  81828. /**
  81829. * Casts a ray forward from the vrCamera's gaze.
  81830. * @param length Length of the ray (default: 100)
  81831. * @returns the ray corrisponding to the gaze
  81832. */
  81833. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81834. if (length === void 0) { length = 100; }
  81835. if (this.leftCamera) {
  81836. // Use left eye to avoid computation to compute center on every call
  81837. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81838. }
  81839. else {
  81840. return _super.prototype.getForwardRay.call(this, length);
  81841. }
  81842. };
  81843. /**
  81844. * Updates the camera based on device's frame data
  81845. */
  81846. WebVRFreeCamera.prototype._checkInputs = function () {
  81847. if (this._vrDevice && this._vrDevice.isPresenting) {
  81848. this._vrDevice.getFrameData(this._frameData);
  81849. this.updateFromDevice(this._frameData.pose);
  81850. }
  81851. _super.prototype._checkInputs.call(this);
  81852. };
  81853. /**
  81854. * Updates the poseControlled values based on the input device pose.
  81855. * @param poseData Pose coming from the device
  81856. */
  81857. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81858. if (poseData && poseData.orientation) {
  81859. this.rawPose = poseData;
  81860. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81861. if (this.getScene().useRightHandedSystem) {
  81862. this._deviceRoomRotationQuaternion.z *= -1;
  81863. this._deviceRoomRotationQuaternion.w *= -1;
  81864. }
  81865. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81866. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81867. if (this.getScene().useRightHandedSystem) {
  81868. this._deviceRoomPosition.z *= -1;
  81869. }
  81870. }
  81871. }
  81872. };
  81873. /**
  81874. * WebVR's attach control will start broadcasting frames to the device.
  81875. * Note that in certain browsers (chrome for example) this function must be called
  81876. * within a user-interaction callback. Example:
  81877. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81878. *
  81879. * @param element html element to attach the vrDevice to
  81880. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81881. */
  81882. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81883. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81884. this._attached = true;
  81885. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81886. if (this._vrDevice) {
  81887. this.getEngine().enableVR();
  81888. }
  81889. };
  81890. /**
  81891. * Detaches the camera from the html element and disables VR
  81892. *
  81893. * @param element html element to detach from
  81894. */
  81895. WebVRFreeCamera.prototype.detachControl = function (element) {
  81896. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81897. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81898. _super.prototype.detachControl.call(this, element);
  81899. this._attached = false;
  81900. this.getEngine().disableVR();
  81901. };
  81902. /**
  81903. * @returns the name of this class
  81904. */
  81905. WebVRFreeCamera.prototype.getClassName = function () {
  81906. return "WebVRFreeCamera";
  81907. };
  81908. /**
  81909. * Calls resetPose on the vrDisplay
  81910. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81911. */
  81912. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81913. //uses the vrDisplay's "resetPose()".
  81914. //pitch and roll won't be affected.
  81915. this._vrDevice.resetPose();
  81916. };
  81917. /**
  81918. * Updates the rig cameras (left and right eye)
  81919. */
  81920. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81921. var camLeft = this._rigCameras[0];
  81922. var camRight = this._rigCameras[1];
  81923. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81924. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81925. camLeft.position.copyFrom(this._deviceRoomPosition);
  81926. camRight.position.copyFrom(this._deviceRoomPosition);
  81927. };
  81928. /**
  81929. * Updates the cached values of the camera
  81930. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81931. */
  81932. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81933. var _this = this;
  81934. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81935. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81936. if (!this.updateCacheCalled) {
  81937. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81938. this.updateCacheCalled = true;
  81939. this.update();
  81940. }
  81941. // Set working vector to the device position in room space rotated by the new rotation
  81942. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81943. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81944. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81945. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81946. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81947. // Add translation from anchor position
  81948. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81949. this._workingVector.addInPlace(this.position);
  81950. this._workingVector.subtractInPlace(this._cache.position);
  81951. this._deviceToWorld.setTranslation(this._workingVector);
  81952. // Set an inverted matrix to be used when updating the camera
  81953. this._deviceToWorld.invertToRef(this._worldToDevice);
  81954. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81955. this.controllers.forEach(function (controller) {
  81956. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81957. controller.update();
  81958. });
  81959. }
  81960. if (!ignoreParentClass) {
  81961. _super.prototype._updateCache.call(this);
  81962. }
  81963. this.updateCacheCalled = false;
  81964. };
  81965. /**
  81966. * Updates the current device position and rotation in the babylon world
  81967. */
  81968. WebVRFreeCamera.prototype.update = function () {
  81969. // Get current device position in babylon world
  81970. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81971. // Get current device rotation in babylon world
  81972. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81973. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81974. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81975. _super.prototype.update.call(this);
  81976. };
  81977. /**
  81978. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81979. * @returns an identity matrix
  81980. */
  81981. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81982. return BABYLON.Matrix.Identity();
  81983. };
  81984. /**
  81985. * This function is called by the two RIG cameras.
  81986. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81987. */
  81988. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81989. var _this = this;
  81990. // Update the parent camera prior to using a child camera to avoid desynchronization
  81991. var parentCamera = this._cameraRigParams["parentCamera"];
  81992. parentCamera._updateCache();
  81993. //WebVR 1.1
  81994. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81995. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81996. if (!this.getScene().useRightHandedSystem) {
  81997. [2, 6, 8, 9, 14].forEach(function (num) {
  81998. _this._webvrViewMatrix.m[num] *= -1;
  81999. });
  82000. }
  82001. // update the camera rotation matrix
  82002. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  82003. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  82004. // Computing target and final matrix
  82005. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  82006. // should the view matrix be updated with scale and position offset?
  82007. if (parentCamera.deviceScaleFactor !== 1) {
  82008. this._webvrViewMatrix.invert();
  82009. // scale the position, if set
  82010. if (parentCamera.deviceScaleFactor) {
  82011. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  82012. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  82013. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  82014. }
  82015. this._webvrViewMatrix.invert();
  82016. }
  82017. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82018. return this._webvrViewMatrix;
  82019. };
  82020. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82021. var _this = this;
  82022. var parentCamera = this.parent;
  82023. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82024. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82025. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82026. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82027. //babylon compatible matrix
  82028. if (!this.getScene().useRightHandedSystem) {
  82029. [8, 9, 10, 11].forEach(function (num) {
  82030. _this._projectionMatrix.m[num] *= -1;
  82031. });
  82032. }
  82033. return this._projectionMatrix;
  82034. };
  82035. /**
  82036. * Initializes the controllers and their meshes
  82037. */
  82038. WebVRFreeCamera.prototype.initControllers = function () {
  82039. var _this = this;
  82040. this.controllers = [];
  82041. var manager = this.getScene().gamepadManager;
  82042. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82043. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82044. var webVrController = gamepad;
  82045. if (webVrController.defaultModel) {
  82046. webVrController.defaultModel.setEnabled(false);
  82047. }
  82048. if (webVrController.hand === "right") {
  82049. _this._rightController = null;
  82050. }
  82051. if (webVrController.hand === "left") {
  82052. _this._leftController = null;
  82053. }
  82054. var controllerIndex = _this.controllers.indexOf(webVrController);
  82055. if (controllerIndex !== -1) {
  82056. _this.controllers.splice(controllerIndex, 1);
  82057. }
  82058. }
  82059. });
  82060. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82061. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82062. var webVrController_1 = gamepad;
  82063. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82064. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82065. if (_this.webVROptions.controllerMeshes) {
  82066. if (webVrController_1.defaultModel) {
  82067. webVrController_1.defaultModel.setEnabled(true);
  82068. }
  82069. else {
  82070. // Load the meshes
  82071. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82072. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82073. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82074. if (_this.webVROptions.defaultLightingOnControllers) {
  82075. if (!_this._lightOnControllers) {
  82076. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82077. }
  82078. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82079. var children = mesh.getChildren();
  82080. if (children.length !== 0) {
  82081. children.forEach(function (mesh) {
  82082. light.includedOnlyMeshes.push(mesh);
  82083. activateLightOnSubMeshes_1(mesh, light);
  82084. });
  82085. }
  82086. };
  82087. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82088. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82089. }
  82090. });
  82091. }
  82092. }
  82093. webVrController_1.attachToPoseControlledCamera(_this);
  82094. // since this is async - sanity check. Is the controller already stored?
  82095. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82096. //add to the controllers array
  82097. _this.controllers.push(webVrController_1);
  82098. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82099. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82100. // So we're overriding setting left & right manually to be sure
  82101. var firstViveWandDetected = false;
  82102. for (var i = 0; i < _this.controllers.length; i++) {
  82103. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82104. if (!firstViveWandDetected) {
  82105. firstViveWandDetected = true;
  82106. _this.controllers[i].hand = "left";
  82107. }
  82108. else {
  82109. _this.controllers[i].hand = "right";
  82110. }
  82111. }
  82112. }
  82113. //did we find enough controllers? Great! let the developer know.
  82114. if (_this.controllers.length >= 2) {
  82115. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82116. }
  82117. }
  82118. }
  82119. });
  82120. };
  82121. return WebVRFreeCamera;
  82122. }(BABYLON.FreeCamera));
  82123. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82124. })(BABYLON || (BABYLON = {}));
  82125. //# sourceMappingURL=babylon.webVRCamera.js.map
  82126. "use strict";
  82127. var BABYLON;
  82128. (function (BABYLON) {
  82129. // We're mainly based on the logic defined into the FreeCamera code
  82130. /**
  82131. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82132. * being tilted forward or back and left or right.
  82133. */
  82134. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82135. __extends(DeviceOrientationCamera, _super);
  82136. /**
  82137. * Creates a new device orientation camera. @see DeviceOrientationCamera
  82138. * @param name The name of the camera
  82139. * @param position The start position camera
  82140. * @param scene The scene the camera belongs to
  82141. */
  82142. function DeviceOrientationCamera(name, position, scene) {
  82143. var _this = _super.call(this, name, position, scene) || this;
  82144. _this._quaternionCache = new BABYLON.Quaternion();
  82145. _this.inputs.addDeviceOrientation();
  82146. return _this;
  82147. }
  82148. /**
  82149. * Gets the current instance class name ("DeviceOrientationCamera").
  82150. * This helps avoiding instanceof at run time.
  82151. * @returns the class name
  82152. */
  82153. DeviceOrientationCamera.prototype.getClassName = function () {
  82154. return "DeviceOrientationCamera";
  82155. };
  82156. /**
  82157. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82158. */
  82159. DeviceOrientationCamera.prototype._checkInputs = function () {
  82160. _super.prototype._checkInputs.call(this);
  82161. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82162. if (this._initialQuaternion) {
  82163. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82164. }
  82165. };
  82166. /**
  82167. * Reset the camera to its default orientation on the specified axis only.
  82168. * @param axis The axis to reset
  82169. */
  82170. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82171. var _this = this;
  82172. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82173. //can only work if this camera has a rotation quaternion already.
  82174. if (!this.rotationQuaternion)
  82175. return;
  82176. if (!this._initialQuaternion) {
  82177. this._initialQuaternion = new BABYLON.Quaternion();
  82178. }
  82179. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82180. ['x', 'y', 'z'].forEach(function (axisName) {
  82181. if (!axis[axisName]) {
  82182. _this._initialQuaternion[axisName] = 0;
  82183. }
  82184. else {
  82185. _this._initialQuaternion[axisName] *= -1;
  82186. }
  82187. });
  82188. this._initialQuaternion.normalize();
  82189. //force rotation update
  82190. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82191. };
  82192. return DeviceOrientationCamera;
  82193. }(BABYLON.FreeCamera));
  82194. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82195. })(BABYLON || (BABYLON = {}));
  82196. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82197. "use strict";
  82198. var BABYLON;
  82199. (function (BABYLON) {
  82200. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82201. __extends(VRDeviceOrientationFreeCamera, _super);
  82202. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82203. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82204. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82205. var _this = _super.call(this, name, position, scene) || this;
  82206. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82207. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82208. return _this;
  82209. }
  82210. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82211. return "VRDeviceOrientationFreeCamera";
  82212. };
  82213. return VRDeviceOrientationFreeCamera;
  82214. }(BABYLON.DeviceOrientationCamera));
  82215. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82216. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82217. __extends(VRDeviceOrientationGamepadCamera, _super);
  82218. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82219. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82220. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82221. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82222. _this.inputs.addGamepad();
  82223. return _this;
  82224. }
  82225. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82226. return "VRDeviceOrientationGamepadCamera";
  82227. };
  82228. return VRDeviceOrientationGamepadCamera;
  82229. }(VRDeviceOrientationFreeCamera));
  82230. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82231. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82232. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82233. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82234. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82235. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82236. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82237. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82238. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82239. _this.inputs.addVRDeviceOrientation();
  82240. return _this;
  82241. }
  82242. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82243. return "VRDeviceOrientationArcRotateCamera";
  82244. };
  82245. return VRDeviceOrientationArcRotateCamera;
  82246. }(BABYLON.ArcRotateCamera));
  82247. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82248. })(BABYLON || (BABYLON = {}));
  82249. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82250. "use strict";
  82251. var BABYLON;
  82252. (function (BABYLON) {
  82253. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82254. __extends(AnaglyphFreeCamera, _super);
  82255. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82256. var _this = _super.call(this, name, position, scene) || this;
  82257. _this.interaxialDistance = interaxialDistance;
  82258. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82259. return _this;
  82260. }
  82261. AnaglyphFreeCamera.prototype.getClassName = function () {
  82262. return "AnaglyphFreeCamera";
  82263. };
  82264. return AnaglyphFreeCamera;
  82265. }(BABYLON.FreeCamera));
  82266. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82267. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82268. __extends(AnaglyphArcRotateCamera, _super);
  82269. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82270. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82271. _this.interaxialDistance = interaxialDistance;
  82272. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82273. return _this;
  82274. }
  82275. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82276. return "AnaglyphArcRotateCamera";
  82277. };
  82278. return AnaglyphArcRotateCamera;
  82279. }(BABYLON.ArcRotateCamera));
  82280. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82281. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82282. __extends(AnaglyphGamepadCamera, _super);
  82283. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82284. var _this = _super.call(this, name, position, scene) || this;
  82285. _this.interaxialDistance = interaxialDistance;
  82286. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82287. return _this;
  82288. }
  82289. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82290. return "AnaglyphGamepadCamera";
  82291. };
  82292. return AnaglyphGamepadCamera;
  82293. }(BABYLON.GamepadCamera));
  82294. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82295. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82296. __extends(AnaglyphUniversalCamera, _super);
  82297. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82298. var _this = _super.call(this, name, position, scene) || this;
  82299. _this.interaxialDistance = interaxialDistance;
  82300. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82301. return _this;
  82302. }
  82303. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82304. return "AnaglyphUniversalCamera";
  82305. };
  82306. return AnaglyphUniversalCamera;
  82307. }(BABYLON.UniversalCamera));
  82308. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82309. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82310. __extends(StereoscopicFreeCamera, _super);
  82311. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82312. var _this = _super.call(this, name, position, scene) || this;
  82313. _this.interaxialDistance = interaxialDistance;
  82314. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82315. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82316. return _this;
  82317. }
  82318. StereoscopicFreeCamera.prototype.getClassName = function () {
  82319. return "StereoscopicFreeCamera";
  82320. };
  82321. return StereoscopicFreeCamera;
  82322. }(BABYLON.FreeCamera));
  82323. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82324. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82325. __extends(StereoscopicArcRotateCamera, _super);
  82326. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82327. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82328. _this.interaxialDistance = interaxialDistance;
  82329. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82330. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82331. return _this;
  82332. }
  82333. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82334. return "StereoscopicArcRotateCamera";
  82335. };
  82336. return StereoscopicArcRotateCamera;
  82337. }(BABYLON.ArcRotateCamera));
  82338. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82339. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82340. __extends(StereoscopicGamepadCamera, _super);
  82341. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82342. var _this = _super.call(this, name, position, scene) || this;
  82343. _this.interaxialDistance = interaxialDistance;
  82344. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82345. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82346. return _this;
  82347. }
  82348. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82349. return "StereoscopicGamepadCamera";
  82350. };
  82351. return StereoscopicGamepadCamera;
  82352. }(BABYLON.GamepadCamera));
  82353. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82354. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82355. __extends(StereoscopicUniversalCamera, _super);
  82356. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82357. var _this = _super.call(this, name, position, scene) || this;
  82358. _this.interaxialDistance = interaxialDistance;
  82359. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82360. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82361. return _this;
  82362. }
  82363. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82364. return "StereoscopicUniversalCamera";
  82365. };
  82366. return StereoscopicUniversalCamera;
  82367. }(BABYLON.UniversalCamera));
  82368. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82369. })(BABYLON || (BABYLON = {}));
  82370. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82371. "use strict";
  82372. var BABYLON;
  82373. (function (BABYLON) {
  82374. var VRExperienceHelperGazer = /** @class */ (function () {
  82375. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82376. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82377. this.scene = scene;
  82378. this._pointerDownOnMeshAsked = false;
  82379. this._isActionableMesh = false;
  82380. this._teleportationRequestInitiated = false;
  82381. this._teleportationBackRequestInitiated = false;
  82382. this._dpadPressed = true;
  82383. this._activePointer = false;
  82384. this._id = VRExperienceHelperGazer._idCounter++;
  82385. // Gaze tracker
  82386. if (!gazeTrackerToClone) {
  82387. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82388. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82389. this._gazeTracker.isPickable = false;
  82390. this._gazeTracker.isVisible = false;
  82391. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82392. targetMat.specularColor = BABYLON.Color3.Black();
  82393. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82394. targetMat.backFaceCulling = false;
  82395. this._gazeTracker.material = targetMat;
  82396. }
  82397. else {
  82398. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82399. }
  82400. }
  82401. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82402. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82403. };
  82404. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82405. this._pointerDownOnMeshAsked = true;
  82406. if (this._currentMeshSelected && this._currentHit) {
  82407. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82408. }
  82409. };
  82410. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82411. if (this._currentMeshSelected && this._currentHit) {
  82412. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82413. }
  82414. this._pointerDownOnMeshAsked = false;
  82415. };
  82416. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82417. this._activePointer = true;
  82418. };
  82419. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82420. this._activePointer = false;
  82421. };
  82422. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82423. };
  82424. VRExperienceHelperGazer.prototype.dispose = function () {
  82425. this._interactionsEnabled = false;
  82426. this._teleportationEnabled = false;
  82427. };
  82428. VRExperienceHelperGazer._idCounter = 0;
  82429. return VRExperienceHelperGazer;
  82430. }());
  82431. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82432. __extends(VRExperienceHelperControllerGazer, _super);
  82433. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82434. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82435. _this.webVRController = webVRController;
  82436. // Laser pointer
  82437. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82438. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82439. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82440. laserPointerMaterial.alpha = 0.6;
  82441. _this._laserPointer.material = laserPointerMaterial;
  82442. _this._laserPointer.rotation.x = Math.PI / 2;
  82443. _this._laserPointer.position.z = -0.5;
  82444. _this._laserPointer.isVisible = false;
  82445. if (!webVRController.mesh) {
  82446. // Create an empty mesh that is used prior to loading the high quality model
  82447. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82448. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82449. preloadPointerPose.rotation.x = -0.7;
  82450. preloadMesh.addChild(preloadPointerPose);
  82451. webVRController.attachToMesh(preloadMesh);
  82452. }
  82453. _this._setLaserPointerParent(webVRController.mesh);
  82454. return _this;
  82455. }
  82456. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82457. return this.webVRController.getForwardRay(length);
  82458. };
  82459. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82460. _super.prototype._activatePointer.call(this);
  82461. this._laserPointer.isVisible = true;
  82462. };
  82463. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82464. _super.prototype._deactivatePointer.call(this);
  82465. this._laserPointer.isVisible = false;
  82466. };
  82467. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82468. this._laserPointer.material.emissiveColor = color;
  82469. };
  82470. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82471. var makeNotPick = function (root) {
  82472. root.name += " laserPointer";
  82473. root.getChildMeshes().forEach(function (c) {
  82474. makeNotPick(c);
  82475. });
  82476. };
  82477. makeNotPick(mesh);
  82478. var childMeshes = mesh.getChildMeshes();
  82479. this.webVRController._pointingPoseNode = null;
  82480. for (var i = 0; i < childMeshes.length; i++) {
  82481. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82482. mesh = childMeshes[i];
  82483. this.webVRController._pointingPoseNode = mesh;
  82484. break;
  82485. }
  82486. }
  82487. this._laserPointer.parent = mesh;
  82488. };
  82489. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82490. this._laserPointer.scaling.y = distance;
  82491. this._laserPointer.position.z = -distance / 2;
  82492. };
  82493. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82494. _super.prototype.dispose.call(this);
  82495. this._laserPointer.dispose();
  82496. };
  82497. return VRExperienceHelperControllerGazer;
  82498. }(VRExperienceHelperGazer));
  82499. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82500. __extends(VRExperienceHelperCameraGazer, _super);
  82501. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82502. var _this = _super.call(this, scene) || this;
  82503. _this.getCamera = getCamera;
  82504. return _this;
  82505. }
  82506. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82507. var camera = this.getCamera();
  82508. if (camera) {
  82509. return camera.getForwardRay(length);
  82510. }
  82511. else {
  82512. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82513. }
  82514. };
  82515. return VRExperienceHelperCameraGazer;
  82516. }(VRExperienceHelperGazer));
  82517. /**
  82518. * Helps to quickly add VR support to an existing scene.
  82519. * See http://doc.babylonjs.com/how_to/webvr_helper
  82520. */
  82521. var VRExperienceHelper = /** @class */ (function () {
  82522. /**
  82523. * Instantiates a VRExperienceHelper.
  82524. * Helps to quickly add VR support to an existing scene.
  82525. * @param scene The scene the VRExperienceHelper belongs to.
  82526. * @param webVROptions Options to modify the vr experience helper's behavior.
  82527. */
  82528. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82529. if (webVROptions === void 0) { webVROptions = {}; }
  82530. var _this = this;
  82531. this.webVROptions = webVROptions;
  82532. // Can the system support WebVR, even if a headset isn't plugged in?
  82533. this._webVRsupported = false;
  82534. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82535. this._webVRready = false;
  82536. // Are we waiting for the requestPresent callback to complete?
  82537. this._webVRrequesting = false;
  82538. // Are we presenting to the headset right now?
  82539. this._webVRpresenting = false;
  82540. // Are we presenting in the fullscreen fallback?
  82541. this._fullscreenVRpresenting = false;
  82542. /**
  82543. * Observable raised when entering VR.
  82544. */
  82545. this.onEnteringVRObservable = new BABYLON.Observable();
  82546. /**
  82547. * Observable raised when exiting VR.
  82548. */
  82549. this.onExitingVRObservable = new BABYLON.Observable();
  82550. /**
  82551. * Observable raised when controller mesh is loaded.
  82552. */
  82553. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82554. this._useCustomVRButton = false;
  82555. this._teleportationRequested = false;
  82556. this._teleportActive = false;
  82557. this._floorMeshesCollection = [];
  82558. this._rotationAllowed = true;
  82559. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82560. this._rotationRightAsked = false;
  82561. this._rotationLeftAsked = false;
  82562. this._isDefaultTeleportationTarget = true;
  82563. this._teleportationFillColor = "#444444";
  82564. this._teleportationBorderColor = "#FFFFFF";
  82565. this._rotationAngle = 0;
  82566. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82567. this._padSensibilityUp = 0.65;
  82568. this._padSensibilityDown = 0.35;
  82569. this.leftController = null;
  82570. this.rightController = null;
  82571. /**
  82572. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82573. */
  82574. this.onNewMeshSelected = new BABYLON.Observable();
  82575. /**
  82576. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82577. */
  82578. this.onNewMeshPicked = new BABYLON.Observable();
  82579. /**
  82580. * Observable raised before camera teleportation
  82581. */
  82582. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82583. /**
  82584. * Observable raised after camera teleportation
  82585. */
  82586. this.onAfterCameraTeleport = new BABYLON.Observable();
  82587. /**
  82588. * Observable raised when current selected mesh gets unselected
  82589. */
  82590. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82591. /**
  82592. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82593. */
  82594. this.teleportationEnabled = true;
  82595. this._teleportationInitialized = false;
  82596. this._interactionsEnabled = false;
  82597. this._interactionsRequested = false;
  82598. this._displayGaze = true;
  82599. this._displayLaserPointer = true;
  82600. this._onResize = function () {
  82601. _this.moveButtonToBottomRight();
  82602. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82603. _this.exitVR();
  82604. }
  82605. };
  82606. this._onFullscreenChange = function () {
  82607. if (document.fullscreen !== undefined) {
  82608. _this._fullscreenVRpresenting = document.fullscreen;
  82609. }
  82610. else if (document.mozFullScreen !== undefined) {
  82611. _this._fullscreenVRpresenting = document.mozFullScreen;
  82612. }
  82613. else if (document.webkitIsFullScreen !== undefined) {
  82614. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82615. }
  82616. else if (document.msIsFullScreen !== undefined) {
  82617. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82618. }
  82619. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82620. _this.exitVR();
  82621. if (!_this._useCustomVRButton) {
  82622. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82623. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82624. }
  82625. }
  82626. };
  82627. this.beforeRender = function () {
  82628. if (_this.leftController && _this.leftController._activePointer) {
  82629. _this._castRayAndSelectObject(_this.leftController);
  82630. }
  82631. if (_this.rightController && _this.rightController._activePointer) {
  82632. _this._castRayAndSelectObject(_this.rightController);
  82633. }
  82634. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82635. _this._castRayAndSelectObject(_this._cameraGazer);
  82636. }
  82637. else {
  82638. _this._cameraGazer._gazeTracker.isVisible = false;
  82639. }
  82640. };
  82641. this._onNewGamepadConnected = function (gamepad) {
  82642. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82643. if (gamepad.leftStick) {
  82644. gamepad.onleftstickchanged(function (stickValues) {
  82645. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82646. // Listening to classic/xbox gamepad only if no VR controller is active
  82647. if ((!_this.leftController && !_this.rightController) ||
  82648. ((_this.leftController && !_this.leftController._activePointer) &&
  82649. (_this.rightController && !_this.rightController._activePointer))) {
  82650. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82651. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82652. }
  82653. }
  82654. });
  82655. }
  82656. if (gamepad.rightStick) {
  82657. gamepad.onrightstickchanged(function (stickValues) {
  82658. if (_this._teleportationInitialized) {
  82659. _this._checkRotate(stickValues, _this._cameraGazer);
  82660. }
  82661. });
  82662. }
  82663. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82664. gamepad.onbuttondown(function (buttonPressed) {
  82665. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82666. _this._cameraGazer._selectionPointerDown();
  82667. }
  82668. });
  82669. gamepad.onbuttonup(function (buttonPressed) {
  82670. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82671. _this._cameraGazer._selectionPointerUp();
  82672. }
  82673. });
  82674. }
  82675. }
  82676. else {
  82677. var webVRController = gamepad;
  82678. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  82679. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  82680. _this.rightController = controller;
  82681. }
  82682. else {
  82683. _this.leftController = controller;
  82684. }
  82685. _this._tryEnableInteractionOnController(controller);
  82686. }
  82687. };
  82688. // 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
  82689. this._tryEnableInteractionOnController = function (controller) {
  82690. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82691. _this._enableInteractionOnController(controller);
  82692. }
  82693. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82694. _this._enableTeleportationOnController(controller);
  82695. }
  82696. };
  82697. this._onNewGamepadDisconnected = function (gamepad) {
  82698. if (gamepad instanceof BABYLON.WebVRController) {
  82699. if (gamepad.hand === "left" && _this.leftController != null) {
  82700. _this.leftController.dispose();
  82701. _this.leftController = null;
  82702. }
  82703. if (gamepad.hand === "right" && _this.rightController != null) {
  82704. _this.rightController.dispose();
  82705. _this.rightController = null;
  82706. }
  82707. }
  82708. };
  82709. this._workingVector = BABYLON.Vector3.Zero();
  82710. this._workingQuaternion = BABYLON.Quaternion.Identity();
  82711. this._workingMatrix = BABYLON.Matrix.Identity();
  82712. this._scene = scene;
  82713. this._canvas = scene.getEngine().getRenderingCanvas();
  82714. // Parse options
  82715. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  82716. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  82717. }
  82718. if (webVROptions.createDeviceOrientationCamera === undefined) {
  82719. webVROptions.createDeviceOrientationCamera = true;
  82720. }
  82721. if (webVROptions.defaultHeight === undefined) {
  82722. webVROptions.defaultHeight = 1.7;
  82723. }
  82724. if (webVROptions.useCustomVRButton) {
  82725. this._useCustomVRButton = true;
  82726. if (webVROptions.customVRButton) {
  82727. this._btnVR = webVROptions.customVRButton;
  82728. }
  82729. }
  82730. if (webVROptions.rayLength) {
  82731. this._rayLength = webVROptions.rayLength;
  82732. }
  82733. this._defaultHeight = webVROptions.defaultHeight;
  82734. if (webVROptions.positionScale) {
  82735. this._rayLength *= webVROptions.positionScale;
  82736. this._defaultHeight *= webVROptions.positionScale;
  82737. }
  82738. // Set position
  82739. if (this._scene.activeCamera) {
  82740. this._position = this._scene.activeCamera.position.clone();
  82741. }
  82742. else {
  82743. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  82744. }
  82745. // Set non-vr camera
  82746. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  82747. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  82748. // Copy data from existing camera
  82749. if (this._scene.activeCamera) {
  82750. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  82751. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  82752. // Set rotation from previous camera
  82753. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  82754. var targetCamera = this._scene.activeCamera;
  82755. if (targetCamera.rotationQuaternion) {
  82756. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  82757. }
  82758. else {
  82759. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82760. }
  82761. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82762. }
  82763. }
  82764. this._scene.activeCamera = this._deviceOrientationCamera;
  82765. if (this._canvas) {
  82766. this._scene.activeCamera.attachControl(this._canvas);
  82767. }
  82768. }
  82769. else {
  82770. this._existingCamera = this._scene.activeCamera;
  82771. }
  82772. // Create VR cameras
  82773. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82774. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82775. }
  82776. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82777. this._webVRCamera.useStandingMatrix();
  82778. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82779. // Create default button
  82780. if (!this._useCustomVRButton) {
  82781. this._btnVR = document.createElement("BUTTON");
  82782. this._btnVR.className = "babylonVRicon";
  82783. this._btnVR.id = "babylonVRiconbtn";
  82784. this._btnVR.title = "Click to switch to VR";
  82785. 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) }";
  82786. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82787. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82788. // css += ".babylonVRicon.vrdisplaysupported { }";
  82789. // css += ".babylonVRicon.vrdisplayready { }";
  82790. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82791. var style = document.createElement('style');
  82792. style.appendChild(document.createTextNode(css));
  82793. document.getElementsByTagName('head')[0].appendChild(style);
  82794. this.moveButtonToBottomRight();
  82795. }
  82796. // VR button click event
  82797. if (this._btnVR) {
  82798. this._btnVR.addEventListener("click", function () {
  82799. if (!_this.isInVRMode) {
  82800. _this.enterVR();
  82801. }
  82802. else {
  82803. _this.exitVR();
  82804. }
  82805. });
  82806. }
  82807. // Window events
  82808. window.addEventListener("resize", this._onResize);
  82809. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82810. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82811. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82812. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82813. // Display vr button when headset is connected
  82814. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82815. this.displayVRButton();
  82816. }
  82817. else {
  82818. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82819. if (e.vrDisplay) {
  82820. _this.displayVRButton();
  82821. }
  82822. });
  82823. }
  82824. // Exiting VR mode using 'ESC' key on desktop
  82825. this._onKeyDown = function (event) {
  82826. if (event.keyCode === 27 && _this.isInVRMode) {
  82827. _this.exitVR();
  82828. }
  82829. };
  82830. document.addEventListener("keydown", this._onKeyDown);
  82831. // Exiting VR mode double tapping the touch screen
  82832. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82833. if (_this.isInVRMode) {
  82834. _this.exitVR();
  82835. if (_this._fullscreenVRpresenting) {
  82836. _this._scene.getEngine().switchFullscreen(true);
  82837. }
  82838. }
  82839. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82840. // Listen for WebVR display changes
  82841. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82842. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82843. this._onVRRequestPresentStart = function () {
  82844. _this._webVRrequesting = true;
  82845. _this.updateButtonVisibility();
  82846. };
  82847. this._onVRRequestPresentComplete = function (success) {
  82848. _this._webVRrequesting = false;
  82849. _this.updateButtonVisibility();
  82850. };
  82851. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82852. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82853. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82854. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82855. scene.onDisposeObservable.add(function () {
  82856. _this.dispose();
  82857. });
  82858. // Gamepad connection events
  82859. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82860. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82861. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82862. this.updateButtonVisibility();
  82863. //create easing functions
  82864. this._circleEase = new BABYLON.CircleEase();
  82865. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82866. }
  82867. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82868. /** Return this.onEnteringVRObservable
  82869. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82870. */
  82871. get: function () {
  82872. return this.onEnteringVRObservable;
  82873. },
  82874. enumerable: true,
  82875. configurable: true
  82876. });
  82877. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82878. /** Return this.onExitingVRObservable
  82879. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82880. */
  82881. get: function () {
  82882. return this.onExitingVRObservable;
  82883. },
  82884. enumerable: true,
  82885. configurable: true
  82886. });
  82887. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82888. /** Return this.onControllerMeshLoadedObservable
  82889. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82890. */
  82891. get: function () {
  82892. return this.onControllerMeshLoadedObservable;
  82893. },
  82894. enumerable: true,
  82895. configurable: true
  82896. });
  82897. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82898. /**
  82899. * The mesh used to display where the user is going to teleport.
  82900. */
  82901. get: function () {
  82902. return this._teleportationTarget;
  82903. },
  82904. /**
  82905. * Sets the mesh to be used to display where the user is going to teleport.
  82906. */
  82907. set: function (value) {
  82908. if (value) {
  82909. value.name = "teleportationTarget";
  82910. this._isDefaultTeleportationTarget = false;
  82911. this._teleportationTarget = value;
  82912. }
  82913. },
  82914. enumerable: true,
  82915. configurable: true
  82916. });
  82917. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82918. /**
  82919. * The mesh used to display where the user is selecting,
  82920. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82921. * See http://doc.babylonjs.com/resources/baking_transformations
  82922. */
  82923. get: function () {
  82924. return this._cameraGazer._gazeTracker;
  82925. },
  82926. set: function (value) {
  82927. if (value) {
  82928. this._cameraGazer._gazeTracker = value;
  82929. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82930. this._cameraGazer._gazeTracker.isPickable = false;
  82931. this._cameraGazer._gazeTracker.isVisible = false;
  82932. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82933. if (this.leftController) {
  82934. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82935. }
  82936. if (this.rightController) {
  82937. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82938. }
  82939. }
  82940. },
  82941. enumerable: true,
  82942. configurable: true
  82943. });
  82944. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82945. /**
  82946. * If the ray of the gaze should be displayed.
  82947. */
  82948. get: function () {
  82949. return this._displayGaze;
  82950. },
  82951. /**
  82952. * Sets if the ray of the gaze should be displayed.
  82953. */
  82954. set: function (value) {
  82955. this._displayGaze = value;
  82956. if (!value) {
  82957. this._cameraGazer._gazeTracker.isVisible = false;
  82958. if (this.leftController) {
  82959. this.leftController._gazeTracker.isVisible = false;
  82960. }
  82961. if (this.rightController) {
  82962. this.rightController._gazeTracker.isVisible = false;
  82963. }
  82964. }
  82965. },
  82966. enumerable: true,
  82967. configurable: true
  82968. });
  82969. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82970. /**
  82971. * If the ray of the LaserPointer should be displayed.
  82972. */
  82973. get: function () {
  82974. return this._displayLaserPointer;
  82975. },
  82976. /**
  82977. * Sets if the ray of the LaserPointer should be displayed.
  82978. */
  82979. set: function (value) {
  82980. this._displayLaserPointer = value;
  82981. if (!value) {
  82982. if (this.rightController) {
  82983. this.rightController._deactivatePointer();
  82984. this.rightController._gazeTracker.isVisible = false;
  82985. }
  82986. if (this.leftController) {
  82987. this.leftController._deactivatePointer();
  82988. this.leftController._gazeTracker.isVisible = false;
  82989. }
  82990. }
  82991. else {
  82992. if (this.rightController) {
  82993. this.rightController._activatePointer();
  82994. }
  82995. else if (this.leftController) {
  82996. this.leftController._activatePointer();
  82997. }
  82998. }
  82999. },
  83000. enumerable: true,
  83001. configurable: true
  83002. });
  83003. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  83004. /**
  83005. * The deviceOrientationCamera used as the camera when not in VR.
  83006. */
  83007. get: function () {
  83008. return this._deviceOrientationCamera;
  83009. },
  83010. enumerable: true,
  83011. configurable: true
  83012. });
  83013. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  83014. /**
  83015. * Based on the current WebVR support, returns the current VR camera used.
  83016. */
  83017. get: function () {
  83018. if (this._webVRready) {
  83019. return this._webVRCamera;
  83020. }
  83021. else {
  83022. return this._scene.activeCamera;
  83023. }
  83024. },
  83025. enumerable: true,
  83026. configurable: true
  83027. });
  83028. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83029. /**
  83030. * The webVRCamera which is used when in VR.
  83031. */
  83032. get: function () {
  83033. return this._webVRCamera;
  83034. },
  83035. enumerable: true,
  83036. configurable: true
  83037. });
  83038. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83039. /**
  83040. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83041. */
  83042. get: function () {
  83043. return this._vrDeviceOrientationCamera;
  83044. },
  83045. enumerable: true,
  83046. configurable: true
  83047. });
  83048. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83049. get: function () {
  83050. var result = this._cameraGazer._teleportationRequestInitiated
  83051. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83052. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83053. return result;
  83054. },
  83055. enumerable: true,
  83056. configurable: true
  83057. });
  83058. // Raised when one of the controller has loaded successfully its associated default mesh
  83059. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83060. if (this.leftController && this.leftController.webVRController == webVRController) {
  83061. if (webVRController.mesh) {
  83062. this.leftController._setLaserPointerParent(webVRController.mesh);
  83063. }
  83064. }
  83065. if (this.rightController && this.rightController.webVRController == webVRController) {
  83066. if (webVRController.mesh) {
  83067. this.rightController._setLaserPointerParent(webVRController.mesh);
  83068. }
  83069. }
  83070. try {
  83071. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83072. }
  83073. catch (err) {
  83074. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83075. }
  83076. };
  83077. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83078. /**
  83079. * Gets a value indicating if we are currently in VR mode.
  83080. */
  83081. get: function () {
  83082. return this._webVRpresenting || this._fullscreenVRpresenting;
  83083. },
  83084. enumerable: true,
  83085. configurable: true
  83086. });
  83087. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83088. var vrDisplay = this._scene.getEngine().getVRDevice();
  83089. if (vrDisplay) {
  83090. var wasPresenting = this._webVRpresenting;
  83091. // A VR display is connected
  83092. this._webVRpresenting = vrDisplay.isPresenting;
  83093. if (wasPresenting && !this._webVRpresenting)
  83094. this.exitVR();
  83095. }
  83096. else {
  83097. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83098. }
  83099. this.updateButtonVisibility();
  83100. };
  83101. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83102. this._webVRsupported = eventArgs.vrSupported;
  83103. this._webVRready = !!eventArgs.vrDisplay;
  83104. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83105. this.updateButtonVisibility();
  83106. };
  83107. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83108. if (this._canvas && !this._useCustomVRButton) {
  83109. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83110. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83111. }
  83112. };
  83113. VRExperienceHelper.prototype.displayVRButton = function () {
  83114. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83115. document.body.appendChild(this._btnVR);
  83116. this._btnVRDisplayed = true;
  83117. }
  83118. };
  83119. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83120. if (!this._btnVR || this._useCustomVRButton) {
  83121. return;
  83122. }
  83123. this._btnVR.className = "babylonVRicon";
  83124. if (this.isInVRMode) {
  83125. this._btnVR.className += " vrdisplaypresenting";
  83126. }
  83127. else {
  83128. if (this._webVRready)
  83129. this._btnVR.className += " vrdisplayready";
  83130. if (this._webVRsupported)
  83131. this._btnVR.className += " vrdisplaysupported";
  83132. if (this._webVRrequesting)
  83133. this._btnVR.className += " vrdisplayrequesting";
  83134. }
  83135. };
  83136. /**
  83137. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83138. * Otherwise, will use the fullscreen API.
  83139. */
  83140. VRExperienceHelper.prototype.enterVR = function () {
  83141. if (this.onEnteringVRObservable) {
  83142. try {
  83143. this.onEnteringVRObservable.notifyObservers(this);
  83144. }
  83145. catch (err) {
  83146. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83147. }
  83148. }
  83149. if (this._scene.activeCamera) {
  83150. this._position = this._scene.activeCamera.position.clone();
  83151. // make sure that we return to the last active camera
  83152. this._existingCamera = this._scene.activeCamera;
  83153. }
  83154. if (this._webVRrequesting)
  83155. return;
  83156. // If WebVR is supported and a headset is connected
  83157. if (this._webVRready) {
  83158. if (!this._webVRpresenting) {
  83159. this._webVRCamera.position = this._position;
  83160. this._scene.activeCamera = this._webVRCamera;
  83161. }
  83162. }
  83163. else if (this._vrDeviceOrientationCamera) {
  83164. this._vrDeviceOrientationCamera.position = this._position;
  83165. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83166. this._scene.getEngine().switchFullscreen(true);
  83167. this.updateButtonVisibility();
  83168. }
  83169. if (this._scene.activeCamera && this._canvas) {
  83170. this._scene.activeCamera.attachControl(this._canvas);
  83171. }
  83172. if (this._interactionsEnabled) {
  83173. this._scene.registerBeforeRender(this.beforeRender);
  83174. }
  83175. };
  83176. /**
  83177. * Attempt to exit VR, or fullscreen.
  83178. */
  83179. VRExperienceHelper.prototype.exitVR = function () {
  83180. if (this.onExitingVRObservable) {
  83181. try {
  83182. this.onExitingVRObservable.notifyObservers(this);
  83183. }
  83184. catch (err) {
  83185. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83186. }
  83187. }
  83188. if (this._webVRpresenting) {
  83189. this._scene.getEngine().disableVR();
  83190. }
  83191. if (this._scene.activeCamera) {
  83192. this._position = this._scene.activeCamera.position.clone();
  83193. }
  83194. if (this._deviceOrientationCamera) {
  83195. this._deviceOrientationCamera.position = this._position;
  83196. this._scene.activeCamera = this._deviceOrientationCamera;
  83197. if (this._canvas) {
  83198. this._scene.activeCamera.attachControl(this._canvas);
  83199. }
  83200. }
  83201. else if (this._existingCamera) {
  83202. this._existingCamera.position = this._position;
  83203. this._scene.activeCamera = this._existingCamera;
  83204. }
  83205. this.updateButtonVisibility();
  83206. if (this._interactionsEnabled) {
  83207. this._scene.unregisterBeforeRender(this.beforeRender);
  83208. }
  83209. };
  83210. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83211. /**
  83212. * The position of the vr experience helper.
  83213. */
  83214. get: function () {
  83215. return this._position;
  83216. },
  83217. /**
  83218. * Sets the position of the vr experience helper.
  83219. */
  83220. set: function (value) {
  83221. this._position = value;
  83222. if (this._scene.activeCamera) {
  83223. this._scene.activeCamera.position = value;
  83224. }
  83225. },
  83226. enumerable: true,
  83227. configurable: true
  83228. });
  83229. /**
  83230. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83231. */
  83232. VRExperienceHelper.prototype.enableInteractions = function () {
  83233. var _this = this;
  83234. if (!this._interactionsEnabled) {
  83235. this._interactionsRequested = true;
  83236. if (this.leftController) {
  83237. this._enableInteractionOnController(this.leftController);
  83238. }
  83239. if (this.rightController) {
  83240. this._enableInteractionOnController(this.rightController);
  83241. }
  83242. this.raySelectionPredicate = function (mesh) {
  83243. return mesh.isVisible;
  83244. };
  83245. this.meshSelectionPredicate = function (mesh) {
  83246. return true;
  83247. };
  83248. this._raySelectionPredicate = function (mesh) {
  83249. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83250. && mesh.name.indexOf("teleportationTarget") === -1
  83251. && mesh.name.indexOf("torusTeleportation") === -1
  83252. && mesh.name.indexOf("laserPointer") === -1)) {
  83253. return _this.raySelectionPredicate(mesh);
  83254. }
  83255. return false;
  83256. };
  83257. this._interactionsEnabled = true;
  83258. }
  83259. };
  83260. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83261. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83262. if (this._floorMeshesCollection[i].id === mesh.id) {
  83263. return true;
  83264. }
  83265. }
  83266. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83267. return true;
  83268. }
  83269. return false;
  83270. };
  83271. /**
  83272. * Adds a floor mesh to be used for teleportation.
  83273. * @param floorMesh the mesh to be used for teleportation.
  83274. */
  83275. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83276. if (!this._floorMeshesCollection) {
  83277. return;
  83278. }
  83279. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83280. return;
  83281. }
  83282. this._floorMeshesCollection.push(floorMesh);
  83283. };
  83284. /**
  83285. * Removes a floor mesh from being used for teleportation.
  83286. * @param floorMesh the mesh to be removed.
  83287. */
  83288. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83289. if (!this._floorMeshesCollection) {
  83290. return;
  83291. }
  83292. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83293. if (meshIndex !== -1) {
  83294. this._floorMeshesCollection.splice(meshIndex, 1);
  83295. }
  83296. };
  83297. /**
  83298. * Enables interactions and teleportation using the VR controllers and gaze.
  83299. * @param vrTeleportationOptions options to modify teleportation behavior.
  83300. */
  83301. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83302. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83303. if (!this._teleportationInitialized) {
  83304. this._teleportationRequested = true;
  83305. this.enableInteractions();
  83306. if (vrTeleportationOptions.floorMeshName) {
  83307. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83308. }
  83309. if (vrTeleportationOptions.floorMeshes) {
  83310. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83311. }
  83312. if (this.leftController != null) {
  83313. this._enableTeleportationOnController(this.leftController);
  83314. }
  83315. if (this.rightController != null) {
  83316. this._enableTeleportationOnController(this.rightController);
  83317. }
  83318. // Creates an image processing post process for the vignette not relying
  83319. // on the main scene configuration for image processing to reduce setup and spaces
  83320. // (gamma/linear) conflicts.
  83321. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83322. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83323. imageProcessingConfiguration.vignetteEnabled = true;
  83324. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83325. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83326. this._teleportationInitialized = true;
  83327. if (this._isDefaultTeleportationTarget) {
  83328. this._createTeleportationCircles();
  83329. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83330. }
  83331. }
  83332. };
  83333. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83334. var _this = this;
  83335. var controllerMesh = controller.webVRController.mesh;
  83336. if (controllerMesh) {
  83337. controller._interactionsEnabled = true;
  83338. controller._activatePointer();
  83339. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83340. // Enabling / disabling laserPointer
  83341. if (_this._displayLaserPointer && stateObject.value === 1) {
  83342. if (controller._activePointer) {
  83343. controller._deactivatePointer();
  83344. }
  83345. else {
  83346. controller._activatePointer();
  83347. }
  83348. if (_this.displayGaze) {
  83349. controller._gazeTracker.isVisible = controller._activePointer;
  83350. }
  83351. }
  83352. });
  83353. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83354. if (!controller._pointerDownOnMeshAsked) {
  83355. if (stateObject.value > _this._padSensibilityUp) {
  83356. controller._selectionPointerDown();
  83357. }
  83358. }
  83359. else if (stateObject.value < _this._padSensibilityDown) {
  83360. controller._selectionPointerUp();
  83361. }
  83362. });
  83363. }
  83364. };
  83365. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83366. // Dont teleport if another gaze already requested teleportation
  83367. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83368. return;
  83369. }
  83370. if (!gazer._teleportationRequestInitiated) {
  83371. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83372. gazer._activatePointer();
  83373. gazer._teleportationRequestInitiated = true;
  83374. }
  83375. }
  83376. else {
  83377. // Listening to the proper controller values changes to confirm teleportation
  83378. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83379. if (this._teleportActive) {
  83380. this._teleportCamera(this._haloCenter);
  83381. }
  83382. gazer._teleportationRequestInitiated = false;
  83383. }
  83384. }
  83385. };
  83386. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83387. // Only rotate when user is not currently selecting a teleportation location
  83388. if (gazer._teleportationRequestInitiated) {
  83389. return;
  83390. }
  83391. if (!this._rotationLeftAsked) {
  83392. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83393. this._rotationLeftAsked = true;
  83394. if (this._rotationAllowed) {
  83395. this._rotateCamera(false);
  83396. }
  83397. }
  83398. }
  83399. else {
  83400. if (stateObject.x > -this._padSensibilityDown) {
  83401. this._rotationLeftAsked = false;
  83402. }
  83403. }
  83404. if (!this._rotationRightAsked) {
  83405. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83406. this._rotationRightAsked = true;
  83407. if (this._rotationAllowed) {
  83408. this._rotateCamera(true);
  83409. }
  83410. }
  83411. }
  83412. else {
  83413. if (stateObject.x < this._padSensibilityDown) {
  83414. this._rotationRightAsked = false;
  83415. }
  83416. }
  83417. };
  83418. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83419. // Only teleport backwards when user is not currently selecting a teleportation location
  83420. if (gazer._teleportationRequestInitiated) {
  83421. return;
  83422. }
  83423. // Teleport backwards
  83424. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83425. if (!gazer._teleportationBackRequestInitiated) {
  83426. if (!this.currentVRCamera) {
  83427. return;
  83428. }
  83429. // Get rotation and position of the current camera
  83430. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83431. var position = this.currentVRCamera.position;
  83432. // If the camera has device position, use that instead
  83433. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83434. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83435. position = this.currentVRCamera.devicePosition;
  83436. }
  83437. // Get matrix with only the y rotation of the device rotation
  83438. rotation.toEulerAnglesToRef(this._workingVector);
  83439. this._workingVector.z = 0;
  83440. this._workingVector.x = 0;
  83441. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83442. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83443. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83444. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83445. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83446. var ray = new BABYLON.Ray(position, this._workingVector);
  83447. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83448. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83449. this._teleportCamera(hit.pickedPoint);
  83450. }
  83451. gazer._teleportationBackRequestInitiated = true;
  83452. }
  83453. }
  83454. else {
  83455. gazer._teleportationBackRequestInitiated = false;
  83456. }
  83457. };
  83458. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83459. var _this = this;
  83460. var controllerMesh = controller.webVRController.mesh;
  83461. if (controllerMesh) {
  83462. if (!controller._interactionsEnabled) {
  83463. this._enableInteractionOnController(controller);
  83464. }
  83465. controller._interactionsEnabled = true;
  83466. controller._teleportationEnabled = true;
  83467. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83468. controller._dpadPressed = false;
  83469. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83470. controller._dpadPressed = stateObject.pressed;
  83471. if (!controller._dpadPressed) {
  83472. _this._rotationLeftAsked = false;
  83473. _this._rotationRightAsked = false;
  83474. controller._teleportationBackRequestInitiated = false;
  83475. }
  83476. });
  83477. }
  83478. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83479. if (_this.teleportationEnabled) {
  83480. _this._checkTeleportBackwards(stateObject, controller);
  83481. _this._checkTeleportWithRay(stateObject, controller);
  83482. }
  83483. _this._checkRotate(stateObject, controller);
  83484. });
  83485. }
  83486. };
  83487. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83488. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83489. this._teleportationTarget.isPickable = false;
  83490. var length = 512;
  83491. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83492. dynamicTexture.hasAlpha = true;
  83493. var context = dynamicTexture.getContext();
  83494. var centerX = length / 2;
  83495. var centerY = length / 2;
  83496. var radius = 200;
  83497. context.beginPath();
  83498. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83499. context.fillStyle = this._teleportationFillColor;
  83500. context.fill();
  83501. context.lineWidth = 10;
  83502. context.strokeStyle = this._teleportationBorderColor;
  83503. context.stroke();
  83504. context.closePath();
  83505. dynamicTexture.update();
  83506. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83507. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83508. this._teleportationTarget.material = teleportationCircleMaterial;
  83509. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83510. torus.isPickable = false;
  83511. torus.parent = this._teleportationTarget;
  83512. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83513. var keys = [];
  83514. keys.push({
  83515. frame: 0,
  83516. value: 0
  83517. });
  83518. keys.push({
  83519. frame: 30,
  83520. value: 0.4
  83521. });
  83522. keys.push({
  83523. frame: 60,
  83524. value: 0
  83525. });
  83526. animationInnerCircle.setKeys(keys);
  83527. var easingFunction = new BABYLON.SineEase();
  83528. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83529. animationInnerCircle.setEasingFunction(easingFunction);
  83530. torus.animations = [];
  83531. torus.animations.push(animationInnerCircle);
  83532. this._scene.beginAnimation(torus, 0, 60, true);
  83533. this._hideTeleportationTarget();
  83534. };
  83535. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83536. this._teleportActive = true;
  83537. if (this._teleportationInitialized) {
  83538. this._teleportationTarget.isVisible = true;
  83539. if (this._isDefaultTeleportationTarget) {
  83540. this._teleportationTarget.getChildren()[0].isVisible = true;
  83541. }
  83542. }
  83543. };
  83544. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83545. this._teleportActive = false;
  83546. if (this._teleportationInitialized) {
  83547. this._teleportationTarget.isVisible = false;
  83548. if (this._isDefaultTeleportationTarget) {
  83549. this._teleportationTarget.getChildren()[0].isVisible = false;
  83550. }
  83551. }
  83552. };
  83553. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83554. var _this = this;
  83555. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83556. return;
  83557. }
  83558. if (right) {
  83559. this._rotationAngle++;
  83560. }
  83561. else {
  83562. this._rotationAngle--;
  83563. }
  83564. this.currentVRCamera.animations = [];
  83565. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83566. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83567. var animationRotationKeys = [];
  83568. animationRotationKeys.push({
  83569. frame: 0,
  83570. value: this.currentVRCamera.rotationQuaternion
  83571. });
  83572. animationRotationKeys.push({
  83573. frame: 6,
  83574. value: target
  83575. });
  83576. animationRotation.setKeys(animationRotationKeys);
  83577. animationRotation.setEasingFunction(this._circleEase);
  83578. this.currentVRCamera.animations.push(animationRotation);
  83579. this._postProcessMove.animations = [];
  83580. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83581. var vignetteWeightKeys = [];
  83582. vignetteWeightKeys.push({
  83583. frame: 0,
  83584. value: 0
  83585. });
  83586. vignetteWeightKeys.push({
  83587. frame: 3,
  83588. value: 4
  83589. });
  83590. vignetteWeightKeys.push({
  83591. frame: 6,
  83592. value: 0
  83593. });
  83594. animationPP.setKeys(vignetteWeightKeys);
  83595. animationPP.setEasingFunction(this._circleEase);
  83596. this._postProcessMove.animations.push(animationPP);
  83597. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83598. var vignetteStretchKeys = [];
  83599. vignetteStretchKeys.push({
  83600. frame: 0,
  83601. value: 0
  83602. });
  83603. vignetteStretchKeys.push({
  83604. frame: 3,
  83605. value: 10
  83606. });
  83607. vignetteStretchKeys.push({
  83608. frame: 6,
  83609. value: 0
  83610. });
  83611. animationPP2.setKeys(vignetteStretchKeys);
  83612. animationPP2.setEasingFunction(this._circleEase);
  83613. this._postProcessMove.animations.push(animationPP2);
  83614. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83615. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83616. this._postProcessMove.samples = 4;
  83617. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83618. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83619. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83620. });
  83621. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83622. };
  83623. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83624. if (hit.pickedPoint) {
  83625. if (gazer._teleportationRequestInitiated) {
  83626. this._displayTeleportationTarget();
  83627. this._haloCenter.copyFrom(hit.pickedPoint);
  83628. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83629. }
  83630. var pickNormal = hit.getNormal(true, false);
  83631. if (pickNormal) {
  83632. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83633. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83634. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83635. }
  83636. this._teleportationTarget.position.y += 0.1;
  83637. }
  83638. };
  83639. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83640. var _this = this;
  83641. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83642. return;
  83643. }
  83644. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83645. // offset of the headset from the anchor.
  83646. if (this.webVRCamera.leftCamera) {
  83647. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83648. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83649. location.subtractToRef(this._workingVector, this._workingVector);
  83650. }
  83651. else {
  83652. this._workingVector.copyFrom(location);
  83653. }
  83654. // Add height to account for user's height offset
  83655. if (this.isInVRMode) {
  83656. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83657. }
  83658. else {
  83659. this._workingVector.y += this._defaultHeight;
  83660. }
  83661. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83662. // Create animation from the camera's position to the new location
  83663. this.currentVRCamera.animations = [];
  83664. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83665. var animationCameraTeleportationKeys = [{
  83666. frame: 0,
  83667. value: this.currentVRCamera.position
  83668. },
  83669. {
  83670. frame: 11,
  83671. value: this._workingVector
  83672. }
  83673. ];
  83674. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83675. animationCameraTeleportation.setEasingFunction(this._circleEase);
  83676. this.currentVRCamera.animations.push(animationCameraTeleportation);
  83677. this._postProcessMove.animations = [];
  83678. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83679. var vignetteWeightKeys = [];
  83680. vignetteWeightKeys.push({
  83681. frame: 0,
  83682. value: 0
  83683. });
  83684. vignetteWeightKeys.push({
  83685. frame: 5,
  83686. value: 8
  83687. });
  83688. vignetteWeightKeys.push({
  83689. frame: 11,
  83690. value: 0
  83691. });
  83692. animationPP.setKeys(vignetteWeightKeys);
  83693. this._postProcessMove.animations.push(animationPP);
  83694. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83695. var vignetteStretchKeys = [];
  83696. vignetteStretchKeys.push({
  83697. frame: 0,
  83698. value: 0
  83699. });
  83700. vignetteStretchKeys.push({
  83701. frame: 5,
  83702. value: 10
  83703. });
  83704. vignetteStretchKeys.push({
  83705. frame: 11,
  83706. value: 0
  83707. });
  83708. animationPP2.setKeys(vignetteStretchKeys);
  83709. this._postProcessMove.animations.push(animationPP2);
  83710. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83711. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83712. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83713. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  83714. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83715. });
  83716. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  83717. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  83718. });
  83719. this._hideTeleportationTarget();
  83720. };
  83721. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  83722. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83723. return;
  83724. }
  83725. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  83726. // Moving the gazeTracker on the mesh face targetted
  83727. if (hit && hit.pickedPoint) {
  83728. if (this._displayGaze) {
  83729. var multiplier = 1;
  83730. gazer._gazeTracker.isVisible = true;
  83731. if (gazer._isActionableMesh) {
  83732. multiplier = 3;
  83733. }
  83734. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  83735. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  83736. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  83737. var pickNormal = hit.getNormal();
  83738. // To avoid z-fighting
  83739. var deltaFighting = 0.002;
  83740. if (pickNormal) {
  83741. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83742. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83743. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  83744. }
  83745. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  83746. if (gazer._gazeTracker.position.x < 0) {
  83747. gazer._gazeTracker.position.x += deltaFighting;
  83748. }
  83749. else {
  83750. gazer._gazeTracker.position.x -= deltaFighting;
  83751. }
  83752. if (gazer._gazeTracker.position.y < 0) {
  83753. gazer._gazeTracker.position.y += deltaFighting;
  83754. }
  83755. else {
  83756. gazer._gazeTracker.position.y -= deltaFighting;
  83757. }
  83758. if (gazer._gazeTracker.position.z < 0) {
  83759. gazer._gazeTracker.position.z += deltaFighting;
  83760. }
  83761. else {
  83762. gazer._gazeTracker.position.z -= deltaFighting;
  83763. }
  83764. }
  83765. // Changing the size of the laser pointer based on the distance from the targetted point
  83766. gazer._updatePointerDistance(hit.distance);
  83767. }
  83768. else {
  83769. gazer._gazeTracker.isVisible = false;
  83770. }
  83771. if (hit && hit.pickedMesh) {
  83772. gazer._currentHit = hit;
  83773. if (gazer._pointerDownOnMeshAsked) {
  83774. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83775. }
  83776. // The object selected is the floor, we're in a teleportation scenario
  83777. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83778. // Moving the teleportation area to this targetted point
  83779. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83780. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83781. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83782. }
  83783. gazer._currentMeshSelected = null;
  83784. if (gazer._teleportationRequestInitiated) {
  83785. this._moveTeleportationSelectorTo(hit, gazer);
  83786. }
  83787. return;
  83788. }
  83789. // If not, we're in a selection scenario
  83790. //this._teleportationAllowed = false;
  83791. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83792. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83793. this.onNewMeshPicked.notifyObservers(hit);
  83794. gazer._currentMeshSelected = hit.pickedMesh;
  83795. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83796. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83797. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83798. gazer._isActionableMesh = true;
  83799. }
  83800. else {
  83801. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83802. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83803. gazer._isActionableMesh = false;
  83804. }
  83805. try {
  83806. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83807. }
  83808. catch (err) {
  83809. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83810. }
  83811. }
  83812. else {
  83813. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83814. gazer._currentMeshSelected = null;
  83815. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83816. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83817. }
  83818. }
  83819. }
  83820. else {
  83821. gazer._currentHit = null;
  83822. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83823. gazer._currentMeshSelected = null;
  83824. //this._teleportationAllowed = false;
  83825. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83826. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83827. }
  83828. };
  83829. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83830. if (mesh) {
  83831. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83832. }
  83833. };
  83834. /**
  83835. * Sets the color of the laser ray from the vr controllers.
  83836. * @param color new color for the ray.
  83837. */
  83838. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83839. if (this.leftController) {
  83840. this.leftController._setLaserPointerColor(color);
  83841. }
  83842. if (this.rightController) {
  83843. this.rightController._setLaserPointerColor(color);
  83844. }
  83845. };
  83846. /**
  83847. * Sets the color of the ray from the vr headsets gaze.
  83848. * @param color new color for the ray.
  83849. */
  83850. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83851. if (!this._cameraGazer._gazeTracker.material) {
  83852. return;
  83853. }
  83854. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83855. if (this.leftController) {
  83856. this.leftController._gazeTracker.material.emissiveColor = color;
  83857. }
  83858. if (this.rightController) {
  83859. this.rightController._gazeTracker.material.emissiveColor = color;
  83860. }
  83861. };
  83862. /**
  83863. * Exits VR and disposes of the vr experience helper
  83864. */
  83865. VRExperienceHelper.prototype.dispose = function () {
  83866. if (this.isInVRMode) {
  83867. this.exitVR();
  83868. }
  83869. if (this._postProcessMove) {
  83870. this._postProcessMove.dispose();
  83871. }
  83872. if (this._webVRCamera) {
  83873. this._webVRCamera.dispose();
  83874. }
  83875. if (this._vrDeviceOrientationCamera) {
  83876. this._vrDeviceOrientationCamera.dispose();
  83877. }
  83878. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83879. document.body.removeChild(this._btnVR);
  83880. }
  83881. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83882. this._deviceOrientationCamera.dispose();
  83883. }
  83884. if (this._cameraGazer) {
  83885. this._cameraGazer.dispose();
  83886. }
  83887. if (this.leftController) {
  83888. this.leftController.dispose();
  83889. }
  83890. if (this.rightController) {
  83891. this.rightController.dispose();
  83892. }
  83893. if (this._teleportationTarget) {
  83894. this._teleportationTarget.dispose();
  83895. }
  83896. this._floorMeshesCollection = [];
  83897. document.removeEventListener("keydown", this._onKeyDown);
  83898. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83899. window.removeEventListener("resize", this._onResize);
  83900. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83901. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83902. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83903. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83904. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83905. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83906. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83907. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83908. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83909. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83910. this._scene.unregisterBeforeRender(this.beforeRender);
  83911. };
  83912. /**
  83913. * Gets the name of the VRExperienceHelper class
  83914. * @returns "VRExperienceHelper"
  83915. */
  83916. VRExperienceHelper.prototype.getClassName = function () {
  83917. return "VRExperienceHelper";
  83918. };
  83919. return VRExperienceHelper;
  83920. }());
  83921. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83922. })(BABYLON || (BABYLON = {}));
  83923. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83924. "use strict";
  83925. // Mainly based on these 2 articles :
  83926. // 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
  83927. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83928. var BABYLON;
  83929. (function (BABYLON) {
  83930. var JoystickAxis;
  83931. (function (JoystickAxis) {
  83932. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83933. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83934. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83935. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83936. var VirtualJoystick = /** @class */ (function () {
  83937. function VirtualJoystick(leftJoystick) {
  83938. var _this = this;
  83939. if (leftJoystick) {
  83940. this._leftJoystick = true;
  83941. }
  83942. else {
  83943. this._leftJoystick = false;
  83944. }
  83945. VirtualJoystick._globalJoystickIndex++;
  83946. // By default left & right arrow keys are moving the X
  83947. // and up & down keys are moving the Y
  83948. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83949. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83950. this.reverseLeftRight = false;
  83951. this.reverseUpDown = false;
  83952. // collections of pointers
  83953. this._touches = new BABYLON.StringDictionary();
  83954. this.deltaPosition = BABYLON.Vector3.Zero();
  83955. this._joystickSensibility = 25;
  83956. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83957. this._onResize = function (evt) {
  83958. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83959. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83960. if (VirtualJoystick.vjCanvas) {
  83961. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83962. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83963. }
  83964. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83965. };
  83966. // injecting a canvas element on top of the canvas 3D game
  83967. if (!VirtualJoystick.vjCanvas) {
  83968. window.addEventListener("resize", this._onResize, false);
  83969. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83970. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83971. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83972. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83973. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83974. VirtualJoystick.vjCanvas.style.width = "100%";
  83975. VirtualJoystick.vjCanvas.style.height = "100%";
  83976. VirtualJoystick.vjCanvas.style.position = "absolute";
  83977. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83978. VirtualJoystick.vjCanvas.style.top = "0px";
  83979. VirtualJoystick.vjCanvas.style.left = "0px";
  83980. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83981. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83982. // Support for jQuery PEP polyfill
  83983. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83984. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83985. if (!context) {
  83986. throw new Error("Unable to create canvas for virtual joystick");
  83987. }
  83988. VirtualJoystick.vjCanvasContext = context;
  83989. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83990. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83991. document.body.appendChild(VirtualJoystick.vjCanvas);
  83992. }
  83993. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83994. this.pressed = false;
  83995. // default joystick color
  83996. this._joystickColor = "cyan";
  83997. this._joystickPointerID = -1;
  83998. // current joystick position
  83999. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  84000. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  84001. // origin joystick position
  84002. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  84003. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  84004. this._onPointerDownHandlerRef = function (evt) {
  84005. _this._onPointerDown(evt);
  84006. };
  84007. this._onPointerMoveHandlerRef = function (evt) {
  84008. _this._onPointerMove(evt);
  84009. };
  84010. this._onPointerUpHandlerRef = function (evt) {
  84011. _this._onPointerUp(evt);
  84012. };
  84013. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  84014. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  84015. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84016. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84017. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84018. evt.preventDefault(); // Disables system menu
  84019. }, false);
  84020. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84021. }
  84022. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84023. this._joystickSensibility = newJoystickSensibility;
  84024. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84025. };
  84026. VirtualJoystick.prototype._onPointerDown = function (e) {
  84027. var positionOnScreenCondition;
  84028. e.preventDefault();
  84029. if (this._leftJoystick === true) {
  84030. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84031. }
  84032. else {
  84033. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84034. }
  84035. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84036. // First contact will be dedicated to the virtual joystick
  84037. this._joystickPointerID = e.pointerId;
  84038. this._joystickPointerStartPos.x = e.clientX;
  84039. this._joystickPointerStartPos.y = e.clientY;
  84040. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84041. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84042. this._deltaJoystickVector.x = 0;
  84043. this._deltaJoystickVector.y = 0;
  84044. this.pressed = true;
  84045. this._touches.add(e.pointerId.toString(), e);
  84046. }
  84047. else {
  84048. // You can only trigger the action buttons with a joystick declared
  84049. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84050. this._action();
  84051. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84052. }
  84053. }
  84054. };
  84055. VirtualJoystick.prototype._onPointerMove = function (e) {
  84056. // If the current pointer is the one associated to the joystick (first touch contact)
  84057. if (this._joystickPointerID == e.pointerId) {
  84058. this._joystickPointerPos.x = e.clientX;
  84059. this._joystickPointerPos.y = e.clientY;
  84060. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84061. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84062. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84063. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84064. switch (this._axisTargetedByLeftAndRight) {
  84065. case JoystickAxis.X:
  84066. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84067. break;
  84068. case JoystickAxis.Y:
  84069. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84070. break;
  84071. case JoystickAxis.Z:
  84072. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84073. break;
  84074. }
  84075. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84076. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84077. switch (this._axisTargetedByUpAndDown) {
  84078. case JoystickAxis.X:
  84079. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84080. break;
  84081. case JoystickAxis.Y:
  84082. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84083. break;
  84084. case JoystickAxis.Z:
  84085. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84086. break;
  84087. }
  84088. }
  84089. else {
  84090. var data = this._touches.get(e.pointerId.toString());
  84091. if (data) {
  84092. data.x = e.clientX;
  84093. data.y = e.clientY;
  84094. }
  84095. }
  84096. };
  84097. VirtualJoystick.prototype._onPointerUp = function (e) {
  84098. if (this._joystickPointerID == e.pointerId) {
  84099. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84100. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84101. this._joystickPointerID = -1;
  84102. this.pressed = false;
  84103. }
  84104. else {
  84105. var touch = this._touches.get(e.pointerId.toString());
  84106. if (touch) {
  84107. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84108. }
  84109. }
  84110. this._deltaJoystickVector.x = 0;
  84111. this._deltaJoystickVector.y = 0;
  84112. this._touches.remove(e.pointerId.toString());
  84113. };
  84114. /**
  84115. * Change the color of the virtual joystick
  84116. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84117. */
  84118. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84119. this._joystickColor = newColor;
  84120. };
  84121. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84122. this._action = action;
  84123. };
  84124. // Define which axis you'd like to control for left & right
  84125. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84126. switch (axis) {
  84127. case JoystickAxis.X:
  84128. case JoystickAxis.Y:
  84129. case JoystickAxis.Z:
  84130. this._axisTargetedByLeftAndRight = axis;
  84131. break;
  84132. default:
  84133. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84134. break;
  84135. }
  84136. };
  84137. // Define which axis you'd like to control for up & down
  84138. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84139. switch (axis) {
  84140. case JoystickAxis.X:
  84141. case JoystickAxis.Y:
  84142. case JoystickAxis.Z:
  84143. this._axisTargetedByUpAndDown = axis;
  84144. break;
  84145. default:
  84146. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84147. break;
  84148. }
  84149. };
  84150. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84151. var _this = this;
  84152. if (this.pressed) {
  84153. this._touches.forEach(function (key, touch) {
  84154. if (touch.pointerId === _this._joystickPointerID) {
  84155. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84156. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84157. VirtualJoystick.vjCanvasContext.beginPath();
  84158. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84159. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84160. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84161. VirtualJoystick.vjCanvasContext.stroke();
  84162. VirtualJoystick.vjCanvasContext.closePath();
  84163. VirtualJoystick.vjCanvasContext.beginPath();
  84164. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84165. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84166. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84167. VirtualJoystick.vjCanvasContext.stroke();
  84168. VirtualJoystick.vjCanvasContext.closePath();
  84169. VirtualJoystick.vjCanvasContext.beginPath();
  84170. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84171. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84172. VirtualJoystick.vjCanvasContext.stroke();
  84173. VirtualJoystick.vjCanvasContext.closePath();
  84174. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84175. }
  84176. else {
  84177. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84178. VirtualJoystick.vjCanvasContext.beginPath();
  84179. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84180. VirtualJoystick.vjCanvasContext.beginPath();
  84181. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84182. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84183. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84184. VirtualJoystick.vjCanvasContext.stroke();
  84185. VirtualJoystick.vjCanvasContext.closePath();
  84186. touch.prevX = touch.x;
  84187. touch.prevY = touch.y;
  84188. }
  84189. ;
  84190. });
  84191. }
  84192. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84193. };
  84194. VirtualJoystick.prototype.releaseCanvas = function () {
  84195. if (VirtualJoystick.vjCanvas) {
  84196. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84197. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84198. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84199. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84200. window.removeEventListener("resize", this._onResize);
  84201. document.body.removeChild(VirtualJoystick.vjCanvas);
  84202. VirtualJoystick.vjCanvas = null;
  84203. }
  84204. };
  84205. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84206. VirtualJoystick._globalJoystickIndex = 0;
  84207. return VirtualJoystick;
  84208. }());
  84209. BABYLON.VirtualJoystick = VirtualJoystick;
  84210. })(BABYLON || (BABYLON = {}));
  84211. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84212. "use strict";
  84213. var BABYLON;
  84214. (function (BABYLON) {
  84215. // We're mainly based on the logic defined into the FreeCamera code
  84216. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84217. __extends(VirtualJoysticksCamera, _super);
  84218. function VirtualJoysticksCamera(name, position, scene) {
  84219. var _this = _super.call(this, name, position, scene) || this;
  84220. _this.inputs.addVirtualJoystick();
  84221. return _this;
  84222. }
  84223. VirtualJoysticksCamera.prototype.getClassName = function () {
  84224. return "VirtualJoysticksCamera";
  84225. };
  84226. return VirtualJoysticksCamera;
  84227. }(BABYLON.FreeCamera));
  84228. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84229. })(BABYLON || (BABYLON = {}));
  84230. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84231. "use strict";
  84232. var BABYLON;
  84233. (function (BABYLON) {
  84234. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84235. function FreeCameraVirtualJoystickInput() {
  84236. }
  84237. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84238. return this._leftjoystick;
  84239. };
  84240. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84241. return this._rightjoystick;
  84242. };
  84243. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84244. if (this._leftjoystick) {
  84245. var camera = this.camera;
  84246. var speed = camera._computeLocalCameraSpeed() * 50;
  84247. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84248. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84249. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84250. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84251. if (!this._leftjoystick.pressed) {
  84252. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84253. }
  84254. if (!this._rightjoystick.pressed) {
  84255. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84256. }
  84257. }
  84258. };
  84259. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84260. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84261. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84262. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84263. this._leftjoystick.setJoystickSensibility(0.15);
  84264. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84265. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84266. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84267. this._rightjoystick.reverseUpDown = true;
  84268. this._rightjoystick.setJoystickSensibility(0.05);
  84269. this._rightjoystick.setJoystickColor("yellow");
  84270. };
  84271. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84272. this._leftjoystick.releaseCanvas();
  84273. this._rightjoystick.releaseCanvas();
  84274. };
  84275. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84276. return "FreeCameraVirtualJoystickInput";
  84277. };
  84278. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84279. return "virtualJoystick";
  84280. };
  84281. return FreeCameraVirtualJoystickInput;
  84282. }());
  84283. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84284. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84285. })(BABYLON || (BABYLON = {}));
  84286. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84287. "use strict";
  84288. var BABYLON;
  84289. (function (BABYLON) {
  84290. var SimplificationSettings = /** @class */ (function () {
  84291. function SimplificationSettings(quality, distance, optimizeMesh) {
  84292. this.quality = quality;
  84293. this.distance = distance;
  84294. this.optimizeMesh = optimizeMesh;
  84295. }
  84296. return SimplificationSettings;
  84297. }());
  84298. BABYLON.SimplificationSettings = SimplificationSettings;
  84299. var SimplificationQueue = /** @class */ (function () {
  84300. function SimplificationQueue() {
  84301. this.running = false;
  84302. this._simplificationArray = [];
  84303. }
  84304. SimplificationQueue.prototype.addTask = function (task) {
  84305. this._simplificationArray.push(task);
  84306. };
  84307. SimplificationQueue.prototype.executeNext = function () {
  84308. var task = this._simplificationArray.pop();
  84309. if (task) {
  84310. this.running = true;
  84311. this.runSimplification(task);
  84312. }
  84313. else {
  84314. this.running = false;
  84315. }
  84316. };
  84317. SimplificationQueue.prototype.runSimplification = function (task) {
  84318. var _this = this;
  84319. if (task.parallelProcessing) {
  84320. //parallel simplifier
  84321. task.settings.forEach(function (setting) {
  84322. var simplifier = _this.getSimplifier(task);
  84323. simplifier.simplify(setting, function (newMesh) {
  84324. task.mesh.addLODLevel(setting.distance, newMesh);
  84325. newMesh.isVisible = true;
  84326. //check if it is the last
  84327. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84328. //all done, run the success callback.
  84329. task.successCallback();
  84330. }
  84331. _this.executeNext();
  84332. });
  84333. });
  84334. }
  84335. else {
  84336. //single simplifier.
  84337. var simplifier = this.getSimplifier(task);
  84338. var runDecimation = function (setting, callback) {
  84339. simplifier.simplify(setting, function (newMesh) {
  84340. task.mesh.addLODLevel(setting.distance, newMesh);
  84341. newMesh.isVisible = true;
  84342. //run the next quality level
  84343. callback();
  84344. });
  84345. };
  84346. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84347. runDecimation(task.settings[loop.index], function () {
  84348. loop.executeNext();
  84349. });
  84350. }, function () {
  84351. //execution ended, run the success callback.
  84352. if (task.successCallback) {
  84353. task.successCallback();
  84354. }
  84355. _this.executeNext();
  84356. });
  84357. }
  84358. };
  84359. SimplificationQueue.prototype.getSimplifier = function (task) {
  84360. switch (task.simplificationType) {
  84361. case SimplificationType.QUADRATIC:
  84362. default:
  84363. return new QuadraticErrorSimplification(task.mesh);
  84364. }
  84365. };
  84366. return SimplificationQueue;
  84367. }());
  84368. BABYLON.SimplificationQueue = SimplificationQueue;
  84369. /**
  84370. * The implemented types of simplification.
  84371. * At the moment only Quadratic Error Decimation is implemented.
  84372. */
  84373. var SimplificationType;
  84374. (function (SimplificationType) {
  84375. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84376. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84377. var DecimationTriangle = /** @class */ (function () {
  84378. function DecimationTriangle(vertices) {
  84379. this.vertices = vertices;
  84380. this.error = new Array(4);
  84381. this.deleted = false;
  84382. this.isDirty = false;
  84383. this.deletePending = false;
  84384. this.borderFactor = 0;
  84385. }
  84386. return DecimationTriangle;
  84387. }());
  84388. BABYLON.DecimationTriangle = DecimationTriangle;
  84389. var DecimationVertex = /** @class */ (function () {
  84390. function DecimationVertex(position, id) {
  84391. this.position = position;
  84392. this.id = id;
  84393. this.isBorder = true;
  84394. this.q = new QuadraticMatrix();
  84395. this.triangleCount = 0;
  84396. this.triangleStart = 0;
  84397. this.originalOffsets = [];
  84398. }
  84399. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84400. this.position.copyFrom(newPosition);
  84401. };
  84402. return DecimationVertex;
  84403. }());
  84404. BABYLON.DecimationVertex = DecimationVertex;
  84405. var QuadraticMatrix = /** @class */ (function () {
  84406. function QuadraticMatrix(data) {
  84407. this.data = new Array(10);
  84408. for (var i = 0; i < 10; ++i) {
  84409. if (data && data[i]) {
  84410. this.data[i] = data[i];
  84411. }
  84412. else {
  84413. this.data[i] = 0;
  84414. }
  84415. }
  84416. }
  84417. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84418. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84419. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84420. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84421. return det;
  84422. };
  84423. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84424. for (var i = 0; i < 10; ++i) {
  84425. this.data[i] += matrix.data[i];
  84426. }
  84427. };
  84428. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84429. for (var i = 0; i < 10; ++i) {
  84430. this.data[i] += data[i];
  84431. }
  84432. };
  84433. QuadraticMatrix.prototype.add = function (matrix) {
  84434. var m = new QuadraticMatrix();
  84435. for (var i = 0; i < 10; ++i) {
  84436. m.data[i] = this.data[i] + matrix.data[i];
  84437. }
  84438. return m;
  84439. };
  84440. QuadraticMatrix.FromData = function (a, b, c, d) {
  84441. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84442. };
  84443. //returning an array to avoid garbage collection
  84444. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84445. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84446. };
  84447. return QuadraticMatrix;
  84448. }());
  84449. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84450. var Reference = /** @class */ (function () {
  84451. function Reference(vertexId, triangleId) {
  84452. this.vertexId = vertexId;
  84453. this.triangleId = triangleId;
  84454. }
  84455. return Reference;
  84456. }());
  84457. BABYLON.Reference = Reference;
  84458. /**
  84459. * An implementation of the Quadratic Error simplification algorithm.
  84460. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84461. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84462. * @author RaananW
  84463. */
  84464. var QuadraticErrorSimplification = /** @class */ (function () {
  84465. function QuadraticErrorSimplification(_mesh) {
  84466. this._mesh = _mesh;
  84467. this.syncIterations = 5000;
  84468. this.aggressiveness = 7;
  84469. this.decimationIterations = 100;
  84470. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84471. }
  84472. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84473. var _this = this;
  84474. this.initDecimatedMesh();
  84475. //iterating through the submeshes array, one after the other.
  84476. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84477. _this.initWithMesh(loop.index, function () {
  84478. _this.runDecimation(settings, loop.index, function () {
  84479. loop.executeNext();
  84480. });
  84481. }, settings.optimizeMesh);
  84482. }, function () {
  84483. setTimeout(function () {
  84484. successCallback(_this._reconstructedMesh);
  84485. }, 0);
  84486. });
  84487. };
  84488. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84489. var _this = this;
  84490. var targetCount = ~~(this.triangles.length * settings.quality);
  84491. var deletedTriangles = 0;
  84492. var triangleCount = this.triangles.length;
  84493. var iterationFunction = function (iteration, callback) {
  84494. setTimeout(function () {
  84495. if (iteration % 5 === 0) {
  84496. _this.updateMesh(iteration === 0);
  84497. }
  84498. for (var i = 0; i < _this.triangles.length; ++i) {
  84499. _this.triangles[i].isDirty = false;
  84500. }
  84501. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84502. var trianglesIterator = function (i) {
  84503. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84504. var t = _this.triangles[tIdx];
  84505. if (!t)
  84506. return;
  84507. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84508. return;
  84509. }
  84510. for (var j = 0; j < 3; ++j) {
  84511. if (t.error[j] < threshold) {
  84512. var deleted0 = [];
  84513. var deleted1 = [];
  84514. var v0 = t.vertices[j];
  84515. var v1 = t.vertices[(j + 1) % 3];
  84516. if (v0.isBorder || v1.isBorder)
  84517. continue;
  84518. var p = BABYLON.Vector3.Zero();
  84519. var n = BABYLON.Vector3.Zero();
  84520. var uv = BABYLON.Vector2.Zero();
  84521. var color = new BABYLON.Color4(0, 0, 0, 1);
  84522. _this.calculateError(v0, v1, p, n, uv, color);
  84523. var delTr = new Array();
  84524. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84525. continue;
  84526. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84527. continue;
  84528. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84529. continue;
  84530. var uniqueArray = new Array();
  84531. delTr.forEach(function (deletedT) {
  84532. if (uniqueArray.indexOf(deletedT) === -1) {
  84533. deletedT.deletePending = true;
  84534. uniqueArray.push(deletedT);
  84535. }
  84536. });
  84537. if (uniqueArray.length % 2 !== 0) {
  84538. continue;
  84539. }
  84540. v0.q = v1.q.add(v0.q);
  84541. v0.updatePosition(p);
  84542. var tStart = _this.references.length;
  84543. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84544. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84545. var tCount = _this.references.length - tStart;
  84546. if (tCount <= v0.triangleCount) {
  84547. if (tCount) {
  84548. for (var c = 0; c < tCount; c++) {
  84549. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84550. }
  84551. }
  84552. }
  84553. else {
  84554. v0.triangleStart = tStart;
  84555. }
  84556. v0.triangleCount = tCount;
  84557. break;
  84558. }
  84559. }
  84560. };
  84561. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84562. }, 0);
  84563. };
  84564. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84565. if (triangleCount - deletedTriangles <= targetCount)
  84566. loop.breakLoop();
  84567. else {
  84568. iterationFunction(loop.index, function () {
  84569. loop.executeNext();
  84570. });
  84571. }
  84572. }, function () {
  84573. setTimeout(function () {
  84574. //reconstruct this part of the mesh
  84575. _this.reconstructMesh(submeshIndex);
  84576. successCallback();
  84577. }, 0);
  84578. });
  84579. };
  84580. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84581. var _this = this;
  84582. this.vertices = [];
  84583. this.triangles = [];
  84584. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84585. var indices = this._mesh.getIndices();
  84586. var submesh = this._mesh.subMeshes[submeshIndex];
  84587. var findInVertices = function (positionToSearch) {
  84588. if (optimizeMesh) {
  84589. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84590. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84591. return _this.vertices[ii];
  84592. }
  84593. }
  84594. }
  84595. return null;
  84596. };
  84597. var vertexReferences = [];
  84598. var vertexInit = function (i) {
  84599. if (!positionData) {
  84600. return;
  84601. }
  84602. var offset = i + submesh.verticesStart;
  84603. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84604. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84605. vertex.originalOffsets.push(offset);
  84606. if (vertex.id === _this.vertices.length) {
  84607. _this.vertices.push(vertex);
  84608. }
  84609. vertexReferences.push(vertex.id);
  84610. };
  84611. //var totalVertices = mesh.getTotalVertices();
  84612. var totalVertices = submesh.verticesCount;
  84613. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84614. var indicesInit = function (i) {
  84615. if (!indices) {
  84616. return;
  84617. }
  84618. var offset = (submesh.indexStart / 3) + i;
  84619. var pos = (offset * 3);
  84620. var i0 = indices[pos + 0];
  84621. var i1 = indices[pos + 1];
  84622. var i2 = indices[pos + 2];
  84623. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84624. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84625. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84626. var triangle = new DecimationTriangle([v0, v1, v2]);
  84627. triangle.originalOffset = pos;
  84628. _this.triangles.push(triangle);
  84629. };
  84630. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84631. _this.init(callback);
  84632. });
  84633. });
  84634. };
  84635. QuadraticErrorSimplification.prototype.init = function (callback) {
  84636. var _this = this;
  84637. var triangleInit1 = function (i) {
  84638. var t = _this.triangles[i];
  84639. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84640. for (var j = 0; j < 3; j++) {
  84641. 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))));
  84642. }
  84643. };
  84644. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84645. var triangleInit2 = function (i) {
  84646. var t = _this.triangles[i];
  84647. for (var j = 0; j < 3; ++j) {
  84648. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84649. }
  84650. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84651. };
  84652. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84653. callback();
  84654. });
  84655. });
  84656. };
  84657. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84658. var newTriangles = [];
  84659. var i;
  84660. for (i = 0; i < this.vertices.length; ++i) {
  84661. this.vertices[i].triangleCount = 0;
  84662. }
  84663. var t;
  84664. var j;
  84665. for (i = 0; i < this.triangles.length; ++i) {
  84666. if (!this.triangles[i].deleted) {
  84667. t = this.triangles[i];
  84668. for (j = 0; j < 3; ++j) {
  84669. t.vertices[j].triangleCount = 1;
  84670. }
  84671. newTriangles.push(t);
  84672. }
  84673. }
  84674. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84675. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  84676. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  84677. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  84678. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  84679. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84680. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  84681. var vertexCount = 0;
  84682. for (i = 0; i < this.vertices.length; ++i) {
  84683. var vertex = this.vertices[i];
  84684. vertex.id = vertexCount;
  84685. if (vertex.triangleCount) {
  84686. vertex.originalOffsets.forEach(function (originalOffset) {
  84687. if (!normalData) {
  84688. return;
  84689. }
  84690. newPositionData.push(vertex.position.x);
  84691. newPositionData.push(vertex.position.y);
  84692. newPositionData.push(vertex.position.z);
  84693. newNormalData.push(normalData[originalOffset * 3]);
  84694. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84695. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84696. if (uvs && uvs.length) {
  84697. newUVsData.push(uvs[(originalOffset * 2)]);
  84698. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  84699. }
  84700. else if (colorsData && colorsData.length) {
  84701. newColorsData.push(colorsData[(originalOffset * 4)]);
  84702. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  84703. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  84704. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  84705. }
  84706. ++vertexCount;
  84707. });
  84708. }
  84709. }
  84710. var startingIndex = this._reconstructedMesh.getTotalIndices();
  84711. var startingVertex = this._reconstructedMesh.getTotalVertices();
  84712. var submeshesArray = this._reconstructedMesh.subMeshes;
  84713. this._reconstructedMesh.subMeshes = [];
  84714. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  84715. var originalIndices = this._mesh.getIndices();
  84716. for (i = 0; i < newTriangles.length; ++i) {
  84717. t = newTriangles[i]; //now get the new referencing point for each vertex
  84718. [0, 1, 2].forEach(function (idx) {
  84719. var id = originalIndices[t.originalOffset + idx];
  84720. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  84721. if (offset < 0)
  84722. offset = 0;
  84723. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  84724. });
  84725. }
  84726. //overwriting the old vertex buffers and indices.
  84727. this._reconstructedMesh.setIndices(newIndicesArray);
  84728. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  84729. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  84730. if (newUVsData.length > 0)
  84731. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  84732. if (newColorsData.length > 0)
  84733. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  84734. //create submesh
  84735. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  84736. if (submeshIndex > 0) {
  84737. this._reconstructedMesh.subMeshes = [];
  84738. submeshesArray.forEach(function (submesh) {
  84739. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  84740. });
  84741. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  84742. }
  84743. };
  84744. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  84745. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  84746. this._reconstructedMesh.material = this._mesh.material;
  84747. this._reconstructedMesh.parent = this._mesh.parent;
  84748. this._reconstructedMesh.isVisible = false;
  84749. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  84750. };
  84751. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  84752. for (var i = 0; i < vertex1.triangleCount; ++i) {
  84753. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  84754. if (t.deleted)
  84755. continue;
  84756. var s = this.references[vertex1.triangleStart + i].vertexId;
  84757. var v1 = t.vertices[(s + 1) % 3];
  84758. var v2 = t.vertices[(s + 2) % 3];
  84759. if ((v1 === vertex2 || v2 === vertex2)) {
  84760. deletedArray[i] = true;
  84761. delTr.push(t);
  84762. continue;
  84763. }
  84764. var d1 = v1.position.subtract(point);
  84765. d1 = d1.normalize();
  84766. var d2 = v2.position.subtract(point);
  84767. d2 = d2.normalize();
  84768. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84769. return true;
  84770. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84771. deletedArray[i] = false;
  84772. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84773. return true;
  84774. }
  84775. return false;
  84776. };
  84777. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84778. var newDeleted = deletedTriangles;
  84779. for (var i = 0; i < vertex.triangleCount; ++i) {
  84780. var ref = this.references[vertex.triangleStart + i];
  84781. var t = this.triangles[ref.triangleId];
  84782. if (t.deleted)
  84783. continue;
  84784. if (deletedArray[i] && t.deletePending) {
  84785. t.deleted = true;
  84786. newDeleted++;
  84787. continue;
  84788. }
  84789. t.vertices[ref.vertexId] = origVertex;
  84790. t.isDirty = true;
  84791. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84792. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84793. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84794. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84795. this.references.push(ref);
  84796. }
  84797. return newDeleted;
  84798. };
  84799. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84800. for (var i = 0; i < this.vertices.length; ++i) {
  84801. var vCount = [];
  84802. var vId = [];
  84803. var v = this.vertices[i];
  84804. var j;
  84805. for (j = 0; j < v.triangleCount; ++j) {
  84806. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84807. for (var ii = 0; ii < 3; ii++) {
  84808. var ofs = 0;
  84809. var vv = triangle.vertices[ii];
  84810. while (ofs < vCount.length) {
  84811. if (vId[ofs] === vv.id)
  84812. break;
  84813. ++ofs;
  84814. }
  84815. if (ofs === vCount.length) {
  84816. vCount.push(1);
  84817. vId.push(vv.id);
  84818. }
  84819. else {
  84820. vCount[ofs]++;
  84821. }
  84822. }
  84823. }
  84824. for (j = 0; j < vCount.length; ++j) {
  84825. if (vCount[j] === 1) {
  84826. this.vertices[vId[j]].isBorder = true;
  84827. }
  84828. else {
  84829. this.vertices[vId[j]].isBorder = false;
  84830. }
  84831. }
  84832. }
  84833. };
  84834. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84835. if (identifyBorders === void 0) { identifyBorders = false; }
  84836. var i;
  84837. if (!identifyBorders) {
  84838. var newTrianglesVector = [];
  84839. for (i = 0; i < this.triangles.length; ++i) {
  84840. if (!this.triangles[i].deleted) {
  84841. newTrianglesVector.push(this.triangles[i]);
  84842. }
  84843. }
  84844. this.triangles = newTrianglesVector;
  84845. }
  84846. for (i = 0; i < this.vertices.length; ++i) {
  84847. this.vertices[i].triangleCount = 0;
  84848. this.vertices[i].triangleStart = 0;
  84849. }
  84850. var t;
  84851. var j;
  84852. var v;
  84853. for (i = 0; i < this.triangles.length; ++i) {
  84854. t = this.triangles[i];
  84855. for (j = 0; j < 3; ++j) {
  84856. v = t.vertices[j];
  84857. v.triangleCount++;
  84858. }
  84859. }
  84860. var tStart = 0;
  84861. for (i = 0; i < this.vertices.length; ++i) {
  84862. this.vertices[i].triangleStart = tStart;
  84863. tStart += this.vertices[i].triangleCount;
  84864. this.vertices[i].triangleCount = 0;
  84865. }
  84866. var newReferences = new Array(this.triangles.length * 3);
  84867. for (i = 0; i < this.triangles.length; ++i) {
  84868. t = this.triangles[i];
  84869. for (j = 0; j < 3; ++j) {
  84870. v = t.vertices[j];
  84871. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84872. v.triangleCount++;
  84873. }
  84874. }
  84875. this.references = newReferences;
  84876. if (identifyBorders) {
  84877. this.identifyBorder();
  84878. }
  84879. };
  84880. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84881. var x = point.x;
  84882. var y = point.y;
  84883. var z = point.z;
  84884. 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
  84885. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84886. };
  84887. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84888. var q = vertex1.q.add(vertex2.q);
  84889. var border = vertex1.isBorder && vertex2.isBorder;
  84890. var error = 0;
  84891. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84892. if (qDet !== 0 && !border) {
  84893. if (!pointResult) {
  84894. pointResult = BABYLON.Vector3.Zero();
  84895. }
  84896. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84897. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84898. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84899. error = this.vertexError(q, pointResult);
  84900. }
  84901. else {
  84902. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84903. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84904. var error1 = this.vertexError(q, vertex1.position);
  84905. var error2 = this.vertexError(q, vertex2.position);
  84906. var error3 = this.vertexError(q, p3);
  84907. error = Math.min(error1, error2, error3);
  84908. if (error === error1) {
  84909. if (pointResult) {
  84910. pointResult.copyFrom(vertex1.position);
  84911. }
  84912. }
  84913. else if (error === error2) {
  84914. if (pointResult) {
  84915. pointResult.copyFrom(vertex2.position);
  84916. }
  84917. }
  84918. else {
  84919. if (pointResult) {
  84920. pointResult.copyFrom(p3);
  84921. }
  84922. }
  84923. }
  84924. return error;
  84925. };
  84926. return QuadraticErrorSimplification;
  84927. }());
  84928. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84929. })(BABYLON || (BABYLON = {}));
  84930. //# sourceMappingURL=babylon.meshSimplification.js.map
  84931. "use strict";
  84932. var BABYLON;
  84933. (function (BABYLON) {
  84934. var MeshLODLevel = /** @class */ (function () {
  84935. function MeshLODLevel(distance, mesh) {
  84936. this.distance = distance;
  84937. this.mesh = mesh;
  84938. }
  84939. return MeshLODLevel;
  84940. }());
  84941. BABYLON.MeshLODLevel = MeshLODLevel;
  84942. })(BABYLON || (BABYLON = {}));
  84943. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84944. "use strict";
  84945. var BABYLON;
  84946. (function (BABYLON) {
  84947. /**
  84948. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84949. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84950. */
  84951. var SceneOptimization = /** @class */ (function () {
  84952. /**
  84953. * Creates the SceneOptimization object
  84954. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84955. * @param desc defines the description associated with the optimization
  84956. */
  84957. function SceneOptimization(
  84958. /**
  84959. * Defines the priority of this optimization (0 by default which means first in the list)
  84960. */
  84961. priority) {
  84962. if (priority === void 0) { priority = 0; }
  84963. this.priority = priority;
  84964. }
  84965. /**
  84966. * Gets a string describing the action executed by the current optimization
  84967. * @returns description string
  84968. */
  84969. SceneOptimization.prototype.getDescription = function () {
  84970. return "";
  84971. };
  84972. /**
  84973. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84974. * @param scene defines the current scene where to apply this optimization
  84975. * @param optimizer defines the current optimizer
  84976. * @returns true if everything that can be done was applied
  84977. */
  84978. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84979. return true;
  84980. };
  84981. ;
  84982. return SceneOptimization;
  84983. }());
  84984. BABYLON.SceneOptimization = SceneOptimization;
  84985. /**
  84986. * Defines an optimization used to reduce the size of render target textures
  84987. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84988. */
  84989. var TextureOptimization = /** @class */ (function (_super) {
  84990. __extends(TextureOptimization, _super);
  84991. /**
  84992. * Creates the TextureOptimization object
  84993. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84994. * @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
  84995. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84996. */
  84997. function TextureOptimization(
  84998. /**
  84999. * Defines the priority of this optimization (0 by default which means first in the list)
  85000. */
  85001. priority,
  85002. /**
  85003. * 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
  85004. */
  85005. maximumSize,
  85006. /**
  85007. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85008. */
  85009. step) {
  85010. if (priority === void 0) { priority = 0; }
  85011. if (maximumSize === void 0) { maximumSize = 1024; }
  85012. if (step === void 0) { step = 0.5; }
  85013. var _this = _super.call(this, priority) || this;
  85014. _this.priority = priority;
  85015. _this.maximumSize = maximumSize;
  85016. _this.step = step;
  85017. return _this;
  85018. }
  85019. /**
  85020. * Gets a string describing the action executed by the current optimization
  85021. * @returns description string
  85022. */
  85023. TextureOptimization.prototype.getDescription = function () {
  85024. return "Reducing render target texture size to " + this.maximumSize;
  85025. };
  85026. /**
  85027. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85028. * @param scene defines the current scene where to apply this optimization
  85029. * @param optimizer defines the current optimizer
  85030. * @returns true if everything that can be done was applied
  85031. */
  85032. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85033. var allDone = true;
  85034. for (var index = 0; index < scene.textures.length; index++) {
  85035. var texture = scene.textures[index];
  85036. if (!texture.canRescale || texture.getContext) {
  85037. continue;
  85038. }
  85039. var currentSize = texture.getSize();
  85040. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85041. if (maxDimension > this.maximumSize) {
  85042. texture.scale(this.step);
  85043. allDone = false;
  85044. }
  85045. }
  85046. return allDone;
  85047. };
  85048. return TextureOptimization;
  85049. }(SceneOptimization));
  85050. BABYLON.TextureOptimization = TextureOptimization;
  85051. /**
  85052. * Defines an optimization used to increase or decrease the rendering resolution
  85053. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85054. */
  85055. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85056. __extends(HardwareScalingOptimization, _super);
  85057. /**
  85058. * Creates the HardwareScalingOptimization object
  85059. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85060. * @param maximumScale defines the maximum scale to use (2 by default)
  85061. * @param step defines the step to use between two passes (0.5 by default)
  85062. */
  85063. function HardwareScalingOptimization(
  85064. /**
  85065. * Defines the priority of this optimization (0 by default which means first in the list)
  85066. */
  85067. priority,
  85068. /**
  85069. * Defines the maximum scale to use (2 by default)
  85070. */
  85071. maximumScale,
  85072. /**
  85073. * Defines the step to use between two passes (0.5 by default)
  85074. */
  85075. step) {
  85076. if (priority === void 0) { priority = 0; }
  85077. if (maximumScale === void 0) { maximumScale = 2; }
  85078. if (step === void 0) { step = 0.25; }
  85079. var _this = _super.call(this, priority) || this;
  85080. _this.priority = priority;
  85081. _this.maximumScale = maximumScale;
  85082. _this.step = step;
  85083. _this._currentScale = -1;
  85084. _this._directionOffset = 1;
  85085. return _this;
  85086. }
  85087. /**
  85088. * Gets a string describing the action executed by the current optimization
  85089. * @return description string
  85090. */
  85091. HardwareScalingOptimization.prototype.getDescription = function () {
  85092. return "Setting hardware scaling level to " + this._currentScale;
  85093. };
  85094. /**
  85095. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85096. * @param scene defines the current scene where to apply this optimization
  85097. * @param optimizer defines the current optimizer
  85098. * @returns true if everything that can be done was applied
  85099. */
  85100. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85101. if (this._currentScale === -1) {
  85102. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85103. if (this._currentScale > this.maximumScale) {
  85104. this._directionOffset = -1;
  85105. }
  85106. }
  85107. this._currentScale += this._directionOffset * this.step;
  85108. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85109. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85110. };
  85111. ;
  85112. return HardwareScalingOptimization;
  85113. }(SceneOptimization));
  85114. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85115. /**
  85116. * Defines an optimization used to remove shadows
  85117. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85118. */
  85119. var ShadowsOptimization = /** @class */ (function (_super) {
  85120. __extends(ShadowsOptimization, _super);
  85121. function ShadowsOptimization() {
  85122. return _super !== null && _super.apply(this, arguments) || this;
  85123. }
  85124. /**
  85125. * Gets a string describing the action executed by the current optimization
  85126. * @return description string
  85127. */
  85128. ShadowsOptimization.prototype.getDescription = function () {
  85129. return "Turning shadows on/off";
  85130. };
  85131. /**
  85132. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85133. * @param scene defines the current scene where to apply this optimization
  85134. * @param optimizer defines the current optimizer
  85135. * @returns true if everything that can be done was applied
  85136. */
  85137. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85138. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85139. return true;
  85140. };
  85141. ;
  85142. return ShadowsOptimization;
  85143. }(SceneOptimization));
  85144. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85145. /**
  85146. * Defines an optimization used to turn post-processes off
  85147. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85148. */
  85149. var PostProcessesOptimization = /** @class */ (function (_super) {
  85150. __extends(PostProcessesOptimization, _super);
  85151. function PostProcessesOptimization() {
  85152. return _super !== null && _super.apply(this, arguments) || this;
  85153. }
  85154. /**
  85155. * Gets a string describing the action executed by the current optimization
  85156. * @return description string
  85157. */
  85158. PostProcessesOptimization.prototype.getDescription = function () {
  85159. return "Turning post-processes on/off";
  85160. };
  85161. /**
  85162. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85163. * @param scene defines the current scene where to apply this optimization
  85164. * @param optimizer defines the current optimizer
  85165. * @returns true if everything that can be done was applied
  85166. */
  85167. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85168. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85169. return true;
  85170. };
  85171. ;
  85172. return PostProcessesOptimization;
  85173. }(SceneOptimization));
  85174. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85175. /**
  85176. * Defines an optimization used to turn lens flares off
  85177. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85178. */
  85179. var LensFlaresOptimization = /** @class */ (function (_super) {
  85180. __extends(LensFlaresOptimization, _super);
  85181. function LensFlaresOptimization() {
  85182. return _super !== null && _super.apply(this, arguments) || this;
  85183. }
  85184. /**
  85185. * Gets a string describing the action executed by the current optimization
  85186. * @return description string
  85187. */
  85188. LensFlaresOptimization.prototype.getDescription = function () {
  85189. return "Turning lens flares on/off";
  85190. };
  85191. /**
  85192. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85193. * @param scene defines the current scene where to apply this optimization
  85194. * @param optimizer defines the current optimizer
  85195. * @returns true if everything that can be done was applied
  85196. */
  85197. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85198. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85199. return true;
  85200. };
  85201. ;
  85202. return LensFlaresOptimization;
  85203. }(SceneOptimization));
  85204. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85205. /**
  85206. * Defines an optimization based on user defined callback.
  85207. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85208. */
  85209. var CustomOptimization = /** @class */ (function (_super) {
  85210. __extends(CustomOptimization, _super);
  85211. function CustomOptimization() {
  85212. return _super !== null && _super.apply(this, arguments) || this;
  85213. }
  85214. /**
  85215. * Gets a string describing the action executed by the current optimization
  85216. * @returns description string
  85217. */
  85218. CustomOptimization.prototype.getDescription = function () {
  85219. if (this.onGetDescription) {
  85220. return this.onGetDescription();
  85221. }
  85222. return "Running user defined callback";
  85223. };
  85224. /**
  85225. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85226. * @param scene defines the current scene where to apply this optimization
  85227. * @param optimizer defines the current optimizer
  85228. * @returns true if everything that can be done was applied
  85229. */
  85230. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85231. if (this.onApply) {
  85232. return this.onApply(scene, optimizer);
  85233. }
  85234. return true;
  85235. };
  85236. ;
  85237. return CustomOptimization;
  85238. }(SceneOptimization));
  85239. BABYLON.CustomOptimization = CustomOptimization;
  85240. /**
  85241. * Defines an optimization used to turn particles off
  85242. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85243. */
  85244. var ParticlesOptimization = /** @class */ (function (_super) {
  85245. __extends(ParticlesOptimization, _super);
  85246. function ParticlesOptimization() {
  85247. return _super !== null && _super.apply(this, arguments) || this;
  85248. }
  85249. /**
  85250. * Gets a string describing the action executed by the current optimization
  85251. * @return description string
  85252. */
  85253. ParticlesOptimization.prototype.getDescription = function () {
  85254. return "Turning particles on/off";
  85255. };
  85256. /**
  85257. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85258. * @param scene defines the current scene where to apply this optimization
  85259. * @param optimizer defines the current optimizer
  85260. * @returns true if everything that can be done was applied
  85261. */
  85262. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85263. scene.particlesEnabled = optimizer.isInImprovementMode;
  85264. return true;
  85265. };
  85266. ;
  85267. return ParticlesOptimization;
  85268. }(SceneOptimization));
  85269. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85270. /**
  85271. * Defines an optimization used to turn render targets off
  85272. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85273. */
  85274. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85275. __extends(RenderTargetsOptimization, _super);
  85276. function RenderTargetsOptimization() {
  85277. return _super !== null && _super.apply(this, arguments) || this;
  85278. }
  85279. /**
  85280. * Gets a string describing the action executed by the current optimization
  85281. * @return description string
  85282. */
  85283. RenderTargetsOptimization.prototype.getDescription = function () {
  85284. return "Turning render targets off";
  85285. };
  85286. /**
  85287. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85288. * @param scene defines the current scene where to apply this optimization
  85289. * @param optimizer defines the current optimizer
  85290. * @returns true if everything that can be done was applied
  85291. */
  85292. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85293. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85294. return true;
  85295. };
  85296. ;
  85297. return RenderTargetsOptimization;
  85298. }(SceneOptimization));
  85299. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85300. /**
  85301. * Defines an optimization used to merge meshes with compatible materials
  85302. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85303. */
  85304. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85305. __extends(MergeMeshesOptimization, _super);
  85306. function MergeMeshesOptimization() {
  85307. var _this = _super !== null && _super.apply(this, arguments) || this;
  85308. _this._canBeMerged = function (abstractMesh) {
  85309. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85310. return false;
  85311. }
  85312. var mesh = abstractMesh;
  85313. if (!mesh.isVisible || !mesh.isEnabled()) {
  85314. return false;
  85315. }
  85316. if (mesh.instances.length > 0) {
  85317. return false;
  85318. }
  85319. if (mesh.skeleton || mesh.hasLODLevels) {
  85320. return false;
  85321. }
  85322. if (mesh.parent) {
  85323. return false;
  85324. }
  85325. return true;
  85326. };
  85327. return _this;
  85328. }
  85329. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85330. /**
  85331. * Gets or sets a boolean which defines if optimization octree has to be updated
  85332. */
  85333. get: function () {
  85334. return MergeMeshesOptimization._UpdateSelectionTree;
  85335. },
  85336. /**
  85337. * Gets or sets a boolean which defines if optimization octree has to be updated
  85338. */
  85339. set: function (value) {
  85340. MergeMeshesOptimization._UpdateSelectionTree = value;
  85341. },
  85342. enumerable: true,
  85343. configurable: true
  85344. });
  85345. /**
  85346. * Gets a string describing the action executed by the current optimization
  85347. * @return description string
  85348. */
  85349. MergeMeshesOptimization.prototype.getDescription = function () {
  85350. return "Merging similar meshes together";
  85351. };
  85352. /**
  85353. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85354. * @param scene defines the current scene where to apply this optimization
  85355. * @param optimizer defines the current optimizer
  85356. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85357. * @returns true if everything that can be done was applied
  85358. */
  85359. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85360. var globalPool = scene.meshes.slice(0);
  85361. var globalLength = globalPool.length;
  85362. for (var index = 0; index < globalLength; index++) {
  85363. var currentPool = new Array();
  85364. var current = globalPool[index];
  85365. // Checks
  85366. if (!this._canBeMerged(current)) {
  85367. continue;
  85368. }
  85369. currentPool.push(current);
  85370. // Find compatible meshes
  85371. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85372. var otherMesh = globalPool[subIndex];
  85373. if (!this._canBeMerged(otherMesh)) {
  85374. continue;
  85375. }
  85376. if (otherMesh.material !== current.material) {
  85377. continue;
  85378. }
  85379. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85380. continue;
  85381. }
  85382. currentPool.push(otherMesh);
  85383. globalLength--;
  85384. globalPool.splice(subIndex, 1);
  85385. subIndex--;
  85386. }
  85387. if (currentPool.length < 2) {
  85388. continue;
  85389. }
  85390. // Merge meshes
  85391. BABYLON.Mesh.MergeMeshes(currentPool);
  85392. }
  85393. if (updateSelectionTree != undefined) {
  85394. if (updateSelectionTree) {
  85395. scene.createOrUpdateSelectionOctree();
  85396. }
  85397. }
  85398. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85399. scene.createOrUpdateSelectionOctree();
  85400. }
  85401. return true;
  85402. };
  85403. ;
  85404. MergeMeshesOptimization._UpdateSelectionTree = false;
  85405. return MergeMeshesOptimization;
  85406. }(SceneOptimization));
  85407. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85408. /**
  85409. * Defines a list of options used by SceneOptimizer
  85410. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85411. */
  85412. var SceneOptimizerOptions = /** @class */ (function () {
  85413. /**
  85414. * Creates a new list of options used by SceneOptimizer
  85415. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85416. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85417. */
  85418. function SceneOptimizerOptions(
  85419. /**
  85420. * Defines the target frame rate to reach (60 by default)
  85421. */
  85422. targetFrameRate,
  85423. /**
  85424. * Defines the interval between two checkes (2000ms by default)
  85425. */
  85426. trackerDuration) {
  85427. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85428. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85429. this.targetFrameRate = targetFrameRate;
  85430. this.trackerDuration = trackerDuration;
  85431. /**
  85432. * Gets the list of optimizations to apply
  85433. */
  85434. this.optimizations = new Array();
  85435. }
  85436. /**
  85437. * Add a new optimization
  85438. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85439. * @returns the current SceneOptimizerOptions
  85440. */
  85441. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85442. this.optimizations.push(optimization);
  85443. return this;
  85444. };
  85445. /**
  85446. * Add a new custom optimization
  85447. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85448. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85449. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85450. * @returns the current SceneOptimizerOptions
  85451. */
  85452. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85453. if (priority === void 0) { priority = 0; }
  85454. var optimization = new CustomOptimization(priority);
  85455. optimization.onApply = onApply;
  85456. optimization.onGetDescription = onGetDescription;
  85457. this.optimizations.push(optimization);
  85458. return this;
  85459. };
  85460. /**
  85461. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85462. * @param targetFrameRate defines the target frame rate (60 by default)
  85463. * @returns a SceneOptimizerOptions object
  85464. */
  85465. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85466. var result = new SceneOptimizerOptions(targetFrameRate);
  85467. var priority = 0;
  85468. result.addOptimization(new MergeMeshesOptimization(priority));
  85469. result.addOptimization(new ShadowsOptimization(priority));
  85470. result.addOptimization(new LensFlaresOptimization(priority));
  85471. // Next priority
  85472. priority++;
  85473. result.addOptimization(new PostProcessesOptimization(priority));
  85474. result.addOptimization(new ParticlesOptimization(priority));
  85475. // Next priority
  85476. priority++;
  85477. result.addOptimization(new TextureOptimization(priority, 1024));
  85478. return result;
  85479. };
  85480. /**
  85481. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85482. * @param targetFrameRate defines the target frame rate (60 by default)
  85483. * @returns a SceneOptimizerOptions object
  85484. */
  85485. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85486. var result = new SceneOptimizerOptions(targetFrameRate);
  85487. var priority = 0;
  85488. result.addOptimization(new MergeMeshesOptimization(priority));
  85489. result.addOptimization(new ShadowsOptimization(priority));
  85490. result.addOptimization(new LensFlaresOptimization(priority));
  85491. // Next priority
  85492. priority++;
  85493. result.addOptimization(new PostProcessesOptimization(priority));
  85494. result.addOptimization(new ParticlesOptimization(priority));
  85495. // Next priority
  85496. priority++;
  85497. result.addOptimization(new TextureOptimization(priority, 512));
  85498. // Next priority
  85499. priority++;
  85500. result.addOptimization(new RenderTargetsOptimization(priority));
  85501. // Next priority
  85502. priority++;
  85503. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85504. return result;
  85505. };
  85506. /**
  85507. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85508. * @param targetFrameRate defines the target frame rate (60 by default)
  85509. * @returns a SceneOptimizerOptions object
  85510. */
  85511. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85512. var result = new SceneOptimizerOptions(targetFrameRate);
  85513. var priority = 0;
  85514. result.addOptimization(new MergeMeshesOptimization(priority));
  85515. result.addOptimization(new ShadowsOptimization(priority));
  85516. result.addOptimization(new LensFlaresOptimization(priority));
  85517. // Next priority
  85518. priority++;
  85519. result.addOptimization(new PostProcessesOptimization(priority));
  85520. result.addOptimization(new ParticlesOptimization(priority));
  85521. // Next priority
  85522. priority++;
  85523. result.addOptimization(new TextureOptimization(priority, 256));
  85524. // Next priority
  85525. priority++;
  85526. result.addOptimization(new RenderTargetsOptimization(priority));
  85527. // Next priority
  85528. priority++;
  85529. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85530. return result;
  85531. };
  85532. return SceneOptimizerOptions;
  85533. }());
  85534. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85535. /**
  85536. * Class used to run optimizations in order to reach a target frame rate
  85537. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85538. */
  85539. var SceneOptimizer = /** @class */ (function () {
  85540. /**
  85541. * Creates a new SceneOptimizer
  85542. * @param scene defines the scene to work on
  85543. * @param options defines the options to use with the SceneOptimizer
  85544. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85545. * @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)
  85546. */
  85547. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85548. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85549. if (improvementMode === void 0) { improvementMode = false; }
  85550. var _this = this;
  85551. this._isRunning = false;
  85552. this._currentPriorityLevel = 0;
  85553. this._targetFrameRate = 60;
  85554. this._trackerDuration = 2000;
  85555. this._currentFrameRate = 0;
  85556. this._improvementMode = false;
  85557. /**
  85558. * Defines an observable called when the optimizer reaches the target frame rate
  85559. */
  85560. this.onSuccessObservable = new BABYLON.Observable();
  85561. /**
  85562. * Defines an observable called when the optimizer enables an optimization
  85563. */
  85564. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85565. /**
  85566. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85567. */
  85568. this.onFailureObservable = new BABYLON.Observable();
  85569. if (!options) {
  85570. this._options = new SceneOptimizerOptions();
  85571. }
  85572. else {
  85573. this._options = options;
  85574. }
  85575. if (this._options.targetFrameRate) {
  85576. this._targetFrameRate = this._options.targetFrameRate;
  85577. }
  85578. if (this._options.trackerDuration) {
  85579. this._trackerDuration = this._options.trackerDuration;
  85580. }
  85581. if (autoGeneratePriorities) {
  85582. var priority = 0;
  85583. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85584. var optim = _a[_i];
  85585. optim.priority = priority++;
  85586. }
  85587. }
  85588. this._improvementMode = improvementMode;
  85589. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85590. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85591. _this._sceneDisposeObserver = null;
  85592. _this.dispose();
  85593. });
  85594. }
  85595. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85596. /**
  85597. * Gets a boolean indicating if the optimizer is in improvement mode
  85598. */
  85599. get: function () {
  85600. return this._improvementMode;
  85601. },
  85602. enumerable: true,
  85603. configurable: true
  85604. });
  85605. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85606. /**
  85607. * Gets the current priority level (0 at start)
  85608. */
  85609. get: function () {
  85610. return this._currentPriorityLevel;
  85611. },
  85612. enumerable: true,
  85613. configurable: true
  85614. });
  85615. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85616. /**
  85617. * Gets the current frame rate checked by the SceneOptimizer
  85618. */
  85619. get: function () {
  85620. return this._currentFrameRate;
  85621. },
  85622. enumerable: true,
  85623. configurable: true
  85624. });
  85625. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85626. /**
  85627. * Gets or sets the current target frame rate (60 by default)
  85628. */
  85629. get: function () {
  85630. return this._targetFrameRate;
  85631. },
  85632. /**
  85633. * Gets or sets the current target frame rate (60 by default)
  85634. */
  85635. set: function (value) {
  85636. this._targetFrameRate = value;
  85637. },
  85638. enumerable: true,
  85639. configurable: true
  85640. });
  85641. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85642. /**
  85643. * Gets or sets the current interval between two checks (every 2000ms by default)
  85644. */
  85645. get: function () {
  85646. return this._trackerDuration;
  85647. },
  85648. /**
  85649. * Gets or sets the current interval between two checks (every 2000ms by default)
  85650. */
  85651. set: function (value) {
  85652. this._trackerDuration = value;
  85653. },
  85654. enumerable: true,
  85655. configurable: true
  85656. });
  85657. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85658. /**
  85659. * Gets the list of active optimizations
  85660. */
  85661. get: function () {
  85662. return this._options.optimizations;
  85663. },
  85664. enumerable: true,
  85665. configurable: true
  85666. });
  85667. /**
  85668. * Stops the current optimizer
  85669. */
  85670. SceneOptimizer.prototype.stop = function () {
  85671. this._isRunning = false;
  85672. };
  85673. /**
  85674. * Reset the optimizer to initial step (current priority level = 0)
  85675. */
  85676. SceneOptimizer.prototype.reset = function () {
  85677. this._currentPriorityLevel = 0;
  85678. };
  85679. /**
  85680. * Start the optimizer. By default it will try to reach a specific framerate
  85681. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  85682. */
  85683. SceneOptimizer.prototype.start = function () {
  85684. var _this = this;
  85685. if (this._isRunning) {
  85686. return;
  85687. }
  85688. this._isRunning = true;
  85689. // Let's wait for the scene to be ready before running our check
  85690. this._scene.executeWhenReady(function () {
  85691. setTimeout(function () {
  85692. _this._checkCurrentState();
  85693. }, _this._trackerDuration);
  85694. });
  85695. };
  85696. SceneOptimizer.prototype._checkCurrentState = function () {
  85697. var _this = this;
  85698. if (!this._isRunning) {
  85699. return;
  85700. }
  85701. var scene = this._scene;
  85702. var options = this._options;
  85703. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  85704. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  85705. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  85706. this._isRunning = false;
  85707. this.onSuccessObservable.notifyObservers(this);
  85708. return;
  85709. }
  85710. // Apply current level of optimizations
  85711. var allDone = true;
  85712. var noOptimizationApplied = true;
  85713. for (var index = 0; index < options.optimizations.length; index++) {
  85714. var optimization = options.optimizations[index];
  85715. if (optimization.priority === this._currentPriorityLevel) {
  85716. noOptimizationApplied = false;
  85717. allDone = allDone && optimization.apply(scene, this);
  85718. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  85719. }
  85720. }
  85721. // If no optimization was applied, this is a failure :(
  85722. if (noOptimizationApplied) {
  85723. this._isRunning = false;
  85724. this.onFailureObservable.notifyObservers(this);
  85725. return;
  85726. }
  85727. // If all optimizations were done, move to next level
  85728. if (allDone) {
  85729. this._currentPriorityLevel++;
  85730. }
  85731. // Let's the system running for a specific amount of time before checking FPS
  85732. scene.executeWhenReady(function () {
  85733. setTimeout(function () {
  85734. _this._checkCurrentState();
  85735. }, _this._trackerDuration);
  85736. });
  85737. };
  85738. /**
  85739. * Release all resources
  85740. */
  85741. SceneOptimizer.prototype.dispose = function () {
  85742. this.stop();
  85743. this.onSuccessObservable.clear();
  85744. this.onFailureObservable.clear();
  85745. this.onNewOptimizationAppliedObservable.clear();
  85746. if (this._sceneDisposeObserver) {
  85747. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  85748. }
  85749. };
  85750. /**
  85751. * Helper function to create a SceneOptimizer with one single line of code
  85752. * @param scene defines the scene to work on
  85753. * @param options defines the options to use with the SceneOptimizer
  85754. * @param onSuccess defines a callback to call on success
  85755. * @param onFailure defines a callback to call on failure
  85756. * @returns the new SceneOptimizer object
  85757. */
  85758. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85759. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85760. if (onSuccess) {
  85761. optimizer.onSuccessObservable.add(function () {
  85762. onSuccess();
  85763. });
  85764. }
  85765. if (onFailure) {
  85766. optimizer.onFailureObservable.add(function () {
  85767. onFailure();
  85768. });
  85769. }
  85770. optimizer.start();
  85771. return optimizer;
  85772. };
  85773. return SceneOptimizer;
  85774. }());
  85775. BABYLON.SceneOptimizer = SceneOptimizer;
  85776. })(BABYLON || (BABYLON = {}));
  85777. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85778. "use strict";
  85779. var BABYLON;
  85780. (function (BABYLON) {
  85781. var OutlineRenderer = /** @class */ (function () {
  85782. function OutlineRenderer(scene) {
  85783. this.zOffset = 1;
  85784. this._scene = scene;
  85785. }
  85786. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85787. var _this = this;
  85788. if (useOverlay === void 0) { useOverlay = false; }
  85789. var scene = this._scene;
  85790. var engine = this._scene.getEngine();
  85791. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85792. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85793. return;
  85794. }
  85795. var mesh = subMesh.getRenderingMesh();
  85796. var material = subMesh.getMaterial();
  85797. if (!material || !scene.activeCamera) {
  85798. return;
  85799. }
  85800. engine.enableEffect(this._effect);
  85801. // Logarithmic depth
  85802. if (material.useLogarithmicDepth) {
  85803. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85804. }
  85805. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85806. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85807. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85808. // Bones
  85809. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85810. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85811. }
  85812. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85813. // Alpha test
  85814. if (material && material.needAlphaTesting()) {
  85815. var alphaTexture = material.getAlphaTestTexture();
  85816. if (alphaTexture) {
  85817. this._effect.setTexture("diffuseSampler", alphaTexture);
  85818. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85819. }
  85820. }
  85821. engine.setZOffset(-this.zOffset);
  85822. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85823. engine.setZOffset(0);
  85824. };
  85825. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85826. var defines = [];
  85827. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85828. var mesh = subMesh.getMesh();
  85829. var material = subMesh.getMaterial();
  85830. if (material) {
  85831. // Alpha test
  85832. if (material.needAlphaTesting()) {
  85833. defines.push("#define ALPHATEST");
  85834. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85835. attribs.push(BABYLON.VertexBuffer.UVKind);
  85836. defines.push("#define UV1");
  85837. }
  85838. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85839. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85840. defines.push("#define UV2");
  85841. }
  85842. }
  85843. //Logarithmic depth
  85844. if (material.useLogarithmicDepth) {
  85845. defines.push("#define LOGARITHMICDEPTH");
  85846. }
  85847. }
  85848. // Bones
  85849. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85850. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85851. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85852. if (mesh.numBoneInfluencers > 4) {
  85853. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85854. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85855. }
  85856. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85857. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85858. }
  85859. else {
  85860. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85861. }
  85862. // Instances
  85863. if (useInstances) {
  85864. defines.push("#define INSTANCES");
  85865. attribs.push("world0");
  85866. attribs.push("world1");
  85867. attribs.push("world2");
  85868. attribs.push("world3");
  85869. }
  85870. // Get correct effect
  85871. var join = defines.join("\n");
  85872. if (this._cachedDefines !== join) {
  85873. this._cachedDefines = join;
  85874. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85875. }
  85876. return this._effect.isReady();
  85877. };
  85878. return OutlineRenderer;
  85879. }());
  85880. BABYLON.OutlineRenderer = OutlineRenderer;
  85881. })(BABYLON || (BABYLON = {}));
  85882. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85883. "use strict";
  85884. var BABYLON;
  85885. (function (BABYLON) {
  85886. var FaceAdjacencies = /** @class */ (function () {
  85887. function FaceAdjacencies() {
  85888. this.edges = new Array();
  85889. this.edgesConnectedCount = 0;
  85890. }
  85891. return FaceAdjacencies;
  85892. }());
  85893. var EdgesRenderer = /** @class */ (function () {
  85894. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85895. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85896. if (epsilon === void 0) { epsilon = 0.95; }
  85897. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85898. this.edgesWidthScalerForOrthographic = 1000.0;
  85899. this.edgesWidthScalerForPerspective = 50.0;
  85900. this._linesPositions = new Array();
  85901. this._linesNormals = new Array();
  85902. this._linesIndices = new Array();
  85903. this._buffers = {};
  85904. this._checkVerticesInsteadOfIndices = false;
  85905. this._source = source;
  85906. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85907. this._epsilon = epsilon;
  85908. this._prepareRessources();
  85909. this._generateEdgesLines();
  85910. }
  85911. EdgesRenderer.prototype._prepareRessources = function () {
  85912. if (this._lineShader) {
  85913. return;
  85914. }
  85915. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85916. attributes: ["position", "normal"],
  85917. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85918. });
  85919. this._lineShader.disableDepthWrite = true;
  85920. this._lineShader.backFaceCulling = false;
  85921. };
  85922. EdgesRenderer.prototype._rebuild = function () {
  85923. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85924. if (buffer) {
  85925. buffer._rebuild();
  85926. }
  85927. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85928. if (buffer) {
  85929. buffer._rebuild();
  85930. }
  85931. var scene = this._source.getScene();
  85932. var engine = scene.getEngine();
  85933. this._ib = engine.createIndexBuffer(this._linesIndices);
  85934. };
  85935. EdgesRenderer.prototype.dispose = function () {
  85936. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85937. if (buffer) {
  85938. buffer.dispose();
  85939. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85940. }
  85941. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85942. if (buffer) {
  85943. buffer.dispose();
  85944. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85945. }
  85946. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85947. this._lineShader.dispose();
  85948. };
  85949. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85950. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85951. return 0;
  85952. }
  85953. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85954. return 1;
  85955. }
  85956. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85957. return 2;
  85958. }
  85959. return -1;
  85960. };
  85961. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85962. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85963. return 0;
  85964. }
  85965. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85966. return 1;
  85967. }
  85968. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85969. return 2;
  85970. }
  85971. return -1;
  85972. };
  85973. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85974. var needToCreateLine;
  85975. if (edge === undefined) {
  85976. needToCreateLine = true;
  85977. }
  85978. else {
  85979. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85980. needToCreateLine = dotProduct < this._epsilon;
  85981. }
  85982. if (needToCreateLine) {
  85983. var offset = this._linesPositions.length / 3;
  85984. var normal = p0.subtract(p1);
  85985. normal.normalize();
  85986. // Positions
  85987. this._linesPositions.push(p0.x);
  85988. this._linesPositions.push(p0.y);
  85989. this._linesPositions.push(p0.z);
  85990. this._linesPositions.push(p0.x);
  85991. this._linesPositions.push(p0.y);
  85992. this._linesPositions.push(p0.z);
  85993. this._linesPositions.push(p1.x);
  85994. this._linesPositions.push(p1.y);
  85995. this._linesPositions.push(p1.z);
  85996. this._linesPositions.push(p1.x);
  85997. this._linesPositions.push(p1.y);
  85998. this._linesPositions.push(p1.z);
  85999. // Normals
  86000. this._linesNormals.push(p1.x);
  86001. this._linesNormals.push(p1.y);
  86002. this._linesNormals.push(p1.z);
  86003. this._linesNormals.push(-1);
  86004. this._linesNormals.push(p1.x);
  86005. this._linesNormals.push(p1.y);
  86006. this._linesNormals.push(p1.z);
  86007. this._linesNormals.push(1);
  86008. this._linesNormals.push(p0.x);
  86009. this._linesNormals.push(p0.y);
  86010. this._linesNormals.push(p0.z);
  86011. this._linesNormals.push(-1);
  86012. this._linesNormals.push(p0.x);
  86013. this._linesNormals.push(p0.y);
  86014. this._linesNormals.push(p0.z);
  86015. this._linesNormals.push(1);
  86016. // Indices
  86017. this._linesIndices.push(offset);
  86018. this._linesIndices.push(offset + 1);
  86019. this._linesIndices.push(offset + 2);
  86020. this._linesIndices.push(offset);
  86021. this._linesIndices.push(offset + 2);
  86022. this._linesIndices.push(offset + 3);
  86023. }
  86024. };
  86025. EdgesRenderer.prototype._generateEdgesLines = function () {
  86026. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86027. var indices = this._source.getIndices();
  86028. if (!indices || !positions) {
  86029. return;
  86030. }
  86031. // First let's find adjacencies
  86032. var adjacencies = new Array();
  86033. var faceNormals = new Array();
  86034. var index;
  86035. var faceAdjacencies;
  86036. // Prepare faces
  86037. for (index = 0; index < indices.length; index += 3) {
  86038. faceAdjacencies = new FaceAdjacencies();
  86039. var p0Index = indices[index];
  86040. var p1Index = indices[index + 1];
  86041. var p2Index = indices[index + 2];
  86042. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86043. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86044. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86045. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86046. faceNormal.normalize();
  86047. faceNormals.push(faceNormal);
  86048. adjacencies.push(faceAdjacencies);
  86049. }
  86050. // Scan
  86051. for (index = 0; index < adjacencies.length; index++) {
  86052. faceAdjacencies = adjacencies[index];
  86053. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86054. var otherFaceAdjacencies = adjacencies[otherIndex];
  86055. if (faceAdjacencies.edgesConnectedCount === 3) {
  86056. break;
  86057. }
  86058. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86059. continue;
  86060. }
  86061. var otherP0 = indices[otherIndex * 3];
  86062. var otherP1 = indices[otherIndex * 3 + 1];
  86063. var otherP2 = indices[otherIndex * 3 + 2];
  86064. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86065. var otherEdgeIndex = 0;
  86066. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86067. continue;
  86068. }
  86069. switch (edgeIndex) {
  86070. case 0:
  86071. if (this._checkVerticesInsteadOfIndices) {
  86072. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86073. }
  86074. else {
  86075. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86076. }
  86077. break;
  86078. case 1:
  86079. if (this._checkVerticesInsteadOfIndices) {
  86080. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86081. }
  86082. else {
  86083. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86084. }
  86085. break;
  86086. case 2:
  86087. if (this._checkVerticesInsteadOfIndices) {
  86088. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86089. }
  86090. else {
  86091. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86092. }
  86093. break;
  86094. }
  86095. if (otherEdgeIndex === -1) {
  86096. continue;
  86097. }
  86098. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86099. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86100. faceAdjacencies.edgesConnectedCount++;
  86101. otherFaceAdjacencies.edgesConnectedCount++;
  86102. if (faceAdjacencies.edgesConnectedCount === 3) {
  86103. break;
  86104. }
  86105. }
  86106. }
  86107. }
  86108. // Create lines
  86109. for (index = 0; index < adjacencies.length; index++) {
  86110. // 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
  86111. var current = adjacencies[index];
  86112. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86113. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86114. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86115. }
  86116. // Merge into a single mesh
  86117. var engine = this._source.getScene().getEngine();
  86118. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86119. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86120. this._ib = engine.createIndexBuffer(this._linesIndices);
  86121. this._indicesCount = this._linesIndices.length;
  86122. };
  86123. EdgesRenderer.prototype.render = function () {
  86124. var scene = this._source.getScene();
  86125. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86126. return;
  86127. }
  86128. var engine = scene.getEngine();
  86129. this._lineShader._preBind();
  86130. // VBOs
  86131. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86132. scene.resetCachedMaterial();
  86133. this._lineShader.setColor4("color", this._source.edgesColor);
  86134. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86135. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86136. }
  86137. else {
  86138. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86139. }
  86140. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86141. this._lineShader.bind(this._source.getWorldMatrix());
  86142. // Draw order
  86143. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86144. this._lineShader.unbind();
  86145. engine.setDepthWrite(true);
  86146. };
  86147. return EdgesRenderer;
  86148. }());
  86149. BABYLON.EdgesRenderer = EdgesRenderer;
  86150. })(BABYLON || (BABYLON = {}));
  86151. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86152. "use strict";
  86153. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86154. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86155. s = arguments[i];
  86156. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86157. t[p] = s[p];
  86158. }
  86159. return t;
  86160. };
  86161. var BABYLON;
  86162. (function (BABYLON) {
  86163. /**
  86164. * The effect layer Helps adding post process effect blended with the main pass.
  86165. *
  86166. * This can be for instance use to generate glow or higlight effects on the scene.
  86167. *
  86168. * The effect layer class can not be used directly and is intented to inherited from to be
  86169. * customized per effects.
  86170. */
  86171. var EffectLayer = /** @class */ (function () {
  86172. /**
  86173. * Instantiates a new effect Layer and references it in the scene.
  86174. * @param name The name of the layer
  86175. * @param scene The scene to use the layer in
  86176. */
  86177. function EffectLayer(
  86178. /** The Friendly of the effect in the scene */
  86179. name, scene) {
  86180. this.name = name;
  86181. this._vertexBuffers = {};
  86182. this._maxSize = 0;
  86183. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86184. this._shouldRender = true;
  86185. this._postProcesses = [];
  86186. this._textures = [];
  86187. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86188. /**
  86189. * The clear color of the texture used to generate the glow map.
  86190. */
  86191. this.neutralColor = new BABYLON.Color4();
  86192. /**
  86193. * Specifies wether the highlight layer is enabled or not.
  86194. */
  86195. this.isEnabled = true;
  86196. /**
  86197. * An event triggered when the effect layer has been disposed.
  86198. */
  86199. this.onDisposeObservable = new BABYLON.Observable();
  86200. /**
  86201. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86202. */
  86203. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86204. /**
  86205. * An event triggered when the generated texture is being merged in the scene.
  86206. */
  86207. this.onBeforeComposeObservable = new BABYLON.Observable();
  86208. /**
  86209. * An event triggered when the generated texture has been merged in the scene.
  86210. */
  86211. this.onAfterComposeObservable = new BABYLON.Observable();
  86212. /**
  86213. * An event triggered when the efffect layer changes its size.
  86214. */
  86215. this.onSizeChangedObservable = new BABYLON.Observable();
  86216. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86217. this._engine = scene.getEngine();
  86218. this._maxSize = this._engine.getCaps().maxTextureSize;
  86219. this._scene.effectLayers.push(this);
  86220. // Generate Buffers
  86221. this._generateIndexBuffer();
  86222. this._genrateVertexBuffer();
  86223. }
  86224. Object.defineProperty(EffectLayer.prototype, "camera", {
  86225. /**
  86226. * Gets the camera attached to the layer.
  86227. */
  86228. get: function () {
  86229. return this._effectLayerOptions.camera;
  86230. },
  86231. enumerable: true,
  86232. configurable: true
  86233. });
  86234. /**
  86235. * Initializes the effect layer with the required options.
  86236. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86237. */
  86238. EffectLayer.prototype._init = function (options) {
  86239. // Adapt options
  86240. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86241. this._setMainTextureSize();
  86242. this._createMainTexture();
  86243. this._createTextureAndPostProcesses();
  86244. this._mergeEffect = this._createMergeEffect();
  86245. };
  86246. /**
  86247. * Generates the index buffer of the full screen quad blending to the main canvas.
  86248. */
  86249. EffectLayer.prototype._generateIndexBuffer = function () {
  86250. // Indices
  86251. var indices = [];
  86252. indices.push(0);
  86253. indices.push(1);
  86254. indices.push(2);
  86255. indices.push(0);
  86256. indices.push(2);
  86257. indices.push(3);
  86258. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86259. };
  86260. /**
  86261. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86262. */
  86263. EffectLayer.prototype._genrateVertexBuffer = function () {
  86264. // VBO
  86265. var vertices = [];
  86266. vertices.push(1, 1);
  86267. vertices.push(-1, 1);
  86268. vertices.push(-1, -1);
  86269. vertices.push(1, -1);
  86270. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86271. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86272. };
  86273. /**
  86274. * Sets the main texture desired size which is the closest power of two
  86275. * of the engine canvas size.
  86276. */
  86277. EffectLayer.prototype._setMainTextureSize = function () {
  86278. if (this._effectLayerOptions.mainTextureFixedSize) {
  86279. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86280. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86281. }
  86282. else {
  86283. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86284. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86285. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86286. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86287. }
  86288. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86289. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86290. };
  86291. /**
  86292. * Creates the main texture for the effect layer.
  86293. */
  86294. EffectLayer.prototype._createMainTexture = function () {
  86295. var _this = this;
  86296. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86297. width: this._mainTextureDesiredSize.width,
  86298. height: this._mainTextureDesiredSize.height
  86299. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86300. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86301. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86302. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86303. this._mainTexture.anisotropicFilteringLevel = 1;
  86304. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86305. this._mainTexture.renderParticles = false;
  86306. this._mainTexture.renderList = null;
  86307. this._mainTexture.ignoreCameraViewport = true;
  86308. // Custom render function
  86309. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86310. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86311. var index;
  86312. var engine = _this._scene.getEngine();
  86313. if (depthOnlySubMeshes.length) {
  86314. engine.setColorWrite(false);
  86315. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86316. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86317. }
  86318. engine.setColorWrite(true);
  86319. }
  86320. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86321. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86322. }
  86323. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86324. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86325. }
  86326. for (index = 0; index < transparentSubMeshes.length; index++) {
  86327. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86328. }
  86329. };
  86330. this._mainTexture.onClearObservable.add(function (engine) {
  86331. engine.clear(_this.neutralColor, true, true, true);
  86332. });
  86333. };
  86334. /**
  86335. * Checks for the readiness of the element composing the layer.
  86336. * @param subMesh the mesh to check for
  86337. * @param useInstances specify wether or not to use instances to render the mesh
  86338. * @param emissiveTexture the associated emissive texture used to generate the glow
  86339. * @return true if ready otherwise, false
  86340. */
  86341. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86342. var material = subMesh.getMaterial();
  86343. if (!material) {
  86344. return false;
  86345. }
  86346. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86347. return false;
  86348. }
  86349. var defines = [];
  86350. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86351. var mesh = subMesh.getMesh();
  86352. var uv1 = false;
  86353. var uv2 = false;
  86354. // Alpha test
  86355. if (material && material.needAlphaTesting()) {
  86356. var alphaTexture = material.getAlphaTestTexture();
  86357. if (alphaTexture) {
  86358. defines.push("#define ALPHATEST");
  86359. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86360. alphaTexture.coordinatesIndex === 1) {
  86361. defines.push("#define DIFFUSEUV2");
  86362. uv2 = true;
  86363. }
  86364. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86365. defines.push("#define DIFFUSEUV1");
  86366. uv1 = true;
  86367. }
  86368. }
  86369. }
  86370. // Emissive
  86371. if (emissiveTexture) {
  86372. defines.push("#define EMISSIVE");
  86373. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86374. emissiveTexture.coordinatesIndex === 1) {
  86375. defines.push("#define EMISSIVEUV2");
  86376. uv2 = true;
  86377. }
  86378. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86379. defines.push("#define EMISSIVEUV1");
  86380. uv1 = true;
  86381. }
  86382. }
  86383. if (uv1) {
  86384. attribs.push(BABYLON.VertexBuffer.UVKind);
  86385. defines.push("#define UV1");
  86386. }
  86387. if (uv2) {
  86388. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86389. defines.push("#define UV2");
  86390. }
  86391. // Bones
  86392. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86393. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86394. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86395. if (mesh.numBoneInfluencers > 4) {
  86396. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86397. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86398. }
  86399. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86400. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86401. }
  86402. else {
  86403. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86404. }
  86405. // Instances
  86406. if (useInstances) {
  86407. defines.push("#define INSTANCES");
  86408. attribs.push("world0");
  86409. attribs.push("world1");
  86410. attribs.push("world2");
  86411. attribs.push("world3");
  86412. }
  86413. // Get correct effect
  86414. var join = defines.join("\n");
  86415. if (this._cachedDefines !== join) {
  86416. this._cachedDefines = join;
  86417. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  86418. }
  86419. return this._effectLayerMapGenerationEffect.isReady();
  86420. };
  86421. /**
  86422. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86423. */
  86424. EffectLayer.prototype.render = function () {
  86425. var currentEffect = this._mergeEffect;
  86426. // Check
  86427. if (!currentEffect.isReady())
  86428. return;
  86429. for (var i = 0; i < this._postProcesses.length; i++) {
  86430. if (!this._postProcesses[i].isReady()) {
  86431. return;
  86432. }
  86433. }
  86434. var engine = this._scene.getEngine();
  86435. this.onBeforeComposeObservable.notifyObservers(this);
  86436. // Render
  86437. engine.enableEffect(currentEffect);
  86438. engine.setState(false);
  86439. // VBOs
  86440. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86441. // Cache
  86442. var previousAlphaMode = engine.getAlphaMode();
  86443. // Go Blend.
  86444. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86445. // Blends the map on the main canvas.
  86446. this._internalRender(currentEffect);
  86447. // Restore Alpha
  86448. engine.setAlphaMode(previousAlphaMode);
  86449. this.onAfterComposeObservable.notifyObservers(this);
  86450. // Handle size changes.
  86451. var size = this._mainTexture.getSize();
  86452. this._setMainTextureSize();
  86453. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86454. // Recreate RTT and post processes on size change.
  86455. this.onSizeChangedObservable.notifyObservers(this);
  86456. this._disposeTextureAndPostProcesses();
  86457. this._createMainTexture();
  86458. this._createTextureAndPostProcesses();
  86459. }
  86460. };
  86461. /**
  86462. * Determine if a given mesh will be used in the current effect.
  86463. * @param mesh mesh to test
  86464. * @returns true if the mesh will be used
  86465. */
  86466. EffectLayer.prototype.hasMesh = function (mesh) {
  86467. return true;
  86468. };
  86469. /**
  86470. * Returns true if the layer contains information to display, otherwise false.
  86471. * @returns true if the glow layer should be rendered
  86472. */
  86473. EffectLayer.prototype.shouldRender = function () {
  86474. return this.isEnabled && this._shouldRender;
  86475. };
  86476. /**
  86477. * Returns true if the mesh should render, otherwise false.
  86478. * @param mesh The mesh to render
  86479. * @returns true if it should render otherwise false
  86480. */
  86481. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86482. return true;
  86483. };
  86484. /**
  86485. * Returns true if the mesh should render, otherwise false.
  86486. * @param mesh The mesh to render
  86487. * @returns true if it should render otherwise false
  86488. */
  86489. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86490. return true;
  86491. };
  86492. /**
  86493. * Renders the submesh passed in parameter to the generation map.
  86494. */
  86495. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86496. var _this = this;
  86497. if (!this.shouldRender()) {
  86498. return;
  86499. }
  86500. var material = subMesh.getMaterial();
  86501. var mesh = subMesh.getRenderingMesh();
  86502. var scene = this._scene;
  86503. var engine = scene.getEngine();
  86504. if (!material) {
  86505. return;
  86506. }
  86507. // Do not block in blend mode.
  86508. if (material.needAlphaBlendingForMesh(mesh)) {
  86509. return;
  86510. }
  86511. // Culling
  86512. engine.setState(material.backFaceCulling);
  86513. // Managing instances
  86514. var batch = mesh._getInstancesRenderList(subMesh._id);
  86515. if (batch.mustReturn) {
  86516. return;
  86517. }
  86518. // Early Exit per mesh
  86519. if (!this._shouldRenderMesh(mesh)) {
  86520. return;
  86521. }
  86522. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86523. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86524. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86525. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86526. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86527. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86528. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86529. // Alpha test
  86530. if (material && material.needAlphaTesting()) {
  86531. var alphaTexture = material.getAlphaTestTexture();
  86532. if (alphaTexture) {
  86533. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86534. var textureMatrix = alphaTexture.getTextureMatrix();
  86535. if (textureMatrix) {
  86536. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86537. }
  86538. }
  86539. }
  86540. // Glow emissive only
  86541. if (this._emissiveTextureAndColor.texture) {
  86542. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86543. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86544. }
  86545. // Bones
  86546. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86547. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86548. }
  86549. // Draw
  86550. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86551. }
  86552. else {
  86553. // Need to reset refresh rate of the shadowMap
  86554. this._mainTexture.resetRefreshCounter();
  86555. }
  86556. };
  86557. /**
  86558. * Rebuild the required buffers.
  86559. * @ignore Internal use only.
  86560. */
  86561. EffectLayer.prototype._rebuild = function () {
  86562. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86563. if (vb) {
  86564. vb._rebuild();
  86565. }
  86566. this._generateIndexBuffer();
  86567. };
  86568. /**
  86569. * Dispose only the render target textures and post process.
  86570. */
  86571. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86572. this._mainTexture.dispose();
  86573. for (var i = 0; i < this._postProcesses.length; i++) {
  86574. if (this._postProcesses[i]) {
  86575. this._postProcesses[i].dispose();
  86576. }
  86577. }
  86578. this._postProcesses = [];
  86579. for (var i = 0; i < this._textures.length; i++) {
  86580. if (this._textures[i]) {
  86581. this._textures[i].dispose();
  86582. }
  86583. }
  86584. this._textures = [];
  86585. };
  86586. /**
  86587. * Dispose the highlight layer and free resources.
  86588. */
  86589. EffectLayer.prototype.dispose = function () {
  86590. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86591. if (vertexBuffer) {
  86592. vertexBuffer.dispose();
  86593. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86594. }
  86595. if (this._indexBuffer) {
  86596. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86597. this._indexBuffer = null;
  86598. }
  86599. // Clean textures and post processes
  86600. this._disposeTextureAndPostProcesses();
  86601. // Remove from scene
  86602. var index = this._scene.effectLayers.indexOf(this, 0);
  86603. if (index > -1) {
  86604. this._scene.effectLayers.splice(index, 1);
  86605. }
  86606. // Callback
  86607. this.onDisposeObservable.notifyObservers(this);
  86608. this.onDisposeObservable.clear();
  86609. this.onBeforeRenderMainTextureObservable.clear();
  86610. this.onBeforeComposeObservable.clear();
  86611. this.onAfterComposeObservable.clear();
  86612. this.onSizeChangedObservable.clear();
  86613. };
  86614. return EffectLayer;
  86615. }());
  86616. BABYLON.EffectLayer = EffectLayer;
  86617. })(BABYLON || (BABYLON = {}));
  86618. //# sourceMappingURL=babylon.effectLayer.js.map
  86619. "use strict";
  86620. var BABYLON;
  86621. (function (BABYLON) {
  86622. /**
  86623. * Special Glow Blur post process only blurring the alpha channel
  86624. * It enforces keeping the most luminous color in the color channel.
  86625. */
  86626. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86627. __extends(GlowBlurPostProcess, _super);
  86628. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86629. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86630. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86631. _this.direction = direction;
  86632. _this.kernel = kernel;
  86633. _this.onApplyObservable.add(function (effect) {
  86634. effect.setFloat2("screenSize", _this.width, _this.height);
  86635. effect.setVector2("direction", _this.direction);
  86636. effect.setFloat("blurWidth", _this.kernel);
  86637. });
  86638. return _this;
  86639. }
  86640. return GlowBlurPostProcess;
  86641. }(BABYLON.PostProcess));
  86642. /**
  86643. * The highlight layer Helps adding a glow effect around a mesh.
  86644. *
  86645. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86646. * glowy meshes to your scene.
  86647. *
  86648. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86649. */
  86650. var HighlightLayer = /** @class */ (function (_super) {
  86651. __extends(HighlightLayer, _super);
  86652. /**
  86653. * Instantiates a new highlight Layer and references it to the scene..
  86654. * @param name The name of the layer
  86655. * @param scene The scene to use the layer in
  86656. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86657. */
  86658. function HighlightLayer(name, scene, options) {
  86659. var _this = _super.call(this, name, scene) || this;
  86660. _this.name = name;
  86661. /**
  86662. * Specifies whether or not the inner glow is ACTIVE in the layer.
  86663. */
  86664. _this.innerGlow = true;
  86665. /**
  86666. * Specifies whether or not the outer glow is ACTIVE in the layer.
  86667. */
  86668. _this.outerGlow = true;
  86669. /**
  86670. * An event triggered when the highlight layer is being blurred.
  86671. */
  86672. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86673. /**
  86674. * An event triggered when the highlight layer has been blurred.
  86675. */
  86676. _this.onAfterBlurObservable = new BABYLON.Observable();
  86677. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86678. _this._meshes = {};
  86679. _this._excludedMeshes = {};
  86680. _this.neutralColor = HighlightLayer.NeutralColor;
  86681. // Warn on stencil
  86682. if (!_this._engine.isStencilEnable) {
  86683. 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 }");
  86684. }
  86685. // Adapt options
  86686. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86687. // Initialize the layer
  86688. _this._init({
  86689. alphaBlendingMode: _this._options.alphaBlendingMode,
  86690. camera: _this._options.camera,
  86691. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86692. mainTextureRatio: _this._options.mainTextureRatio
  86693. });
  86694. // Do not render as long as no meshes have been added
  86695. _this._shouldRender = false;
  86696. return _this;
  86697. }
  86698. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  86699. /**
  86700. * Gets the horizontal size of the blur.
  86701. */
  86702. get: function () {
  86703. return this._horizontalBlurPostprocess.kernel;
  86704. },
  86705. /**
  86706. * Specifies the horizontal size of the blur.
  86707. */
  86708. set: function (value) {
  86709. this._horizontalBlurPostprocess.kernel = value;
  86710. },
  86711. enumerable: true,
  86712. configurable: true
  86713. });
  86714. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  86715. /**
  86716. * Gets the vertical size of the blur.
  86717. */
  86718. get: function () {
  86719. return this._verticalBlurPostprocess.kernel;
  86720. },
  86721. /**
  86722. * Specifies the vertical size of the blur.
  86723. */
  86724. set: function (value) {
  86725. this._verticalBlurPostprocess.kernel = value;
  86726. },
  86727. enumerable: true,
  86728. configurable: true
  86729. });
  86730. /**
  86731. * Get the effect name of the layer.
  86732. * @return The effect name
  86733. */
  86734. HighlightLayer.prototype.getEffectName = function () {
  86735. return HighlightLayer.EffectName;
  86736. };
  86737. /**
  86738. * Create the merge effect. This is the shader use to blit the information back
  86739. * to the main canvas at the end of the scene rendering.
  86740. */
  86741. HighlightLayer.prototype._createMergeEffect = function () {
  86742. // Effect
  86743. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  86744. };
  86745. /**
  86746. * Creates the render target textures and post processes used in the highlight layer.
  86747. */
  86748. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  86749. var _this = this;
  86750. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  86751. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  86752. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86753. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86754. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  86755. width: blurTextureWidth,
  86756. height: blurTextureHeight
  86757. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86758. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86759. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86760. this._blurTexture.anisotropicFilteringLevel = 16;
  86761. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86762. this._blurTexture.renderParticles = false;
  86763. this._blurTexture.ignoreCameraViewport = true;
  86764. this._textures = [this._blurTexture];
  86765. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86766. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86767. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86768. effect.setTexture("textureSampler", _this._mainTexture);
  86769. });
  86770. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86771. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86772. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86773. });
  86774. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86775. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86776. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86777. });
  86778. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86779. }
  86780. else {
  86781. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86782. width: blurTextureWidth,
  86783. height: blurTextureHeight
  86784. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86785. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86786. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86787. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86788. effect.setTexture("textureSampler", _this._mainTexture);
  86789. });
  86790. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86791. width: blurTextureWidth,
  86792. height: blurTextureHeight
  86793. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86794. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86795. }
  86796. this._mainTexture.onAfterUnbindObservable.add(function () {
  86797. _this.onBeforeBlurObservable.notifyObservers(_this);
  86798. var internalTexture = _this._blurTexture.getInternalTexture();
  86799. if (internalTexture) {
  86800. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86801. }
  86802. _this.onAfterBlurObservable.notifyObservers(_this);
  86803. });
  86804. // Prevent autoClear.
  86805. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86806. };
  86807. /**
  86808. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86809. */
  86810. HighlightLayer.prototype.needStencil = function () {
  86811. return true;
  86812. };
  86813. /**
  86814. * Checks for the readiness of the element composing the layer.
  86815. * @param subMesh the mesh to check for
  86816. * @param useInstances specify wether or not to use instances to render the mesh
  86817. * @param emissiveTexture the associated emissive texture used to generate the glow
  86818. * @return true if ready otherwise, false
  86819. */
  86820. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86821. var material = subMesh.getMaterial();
  86822. var mesh = subMesh.getRenderingMesh();
  86823. if (!material || !mesh || !this._meshes) {
  86824. return false;
  86825. }
  86826. var emissiveTexture = null;
  86827. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86828. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86829. emissiveTexture = material.emissiveTexture;
  86830. }
  86831. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86832. };
  86833. /**
  86834. * Implementation specific of rendering the generating effect on the main canvas.
  86835. * @param effect The effect used to render through
  86836. */
  86837. HighlightLayer.prototype._internalRender = function (effect) {
  86838. // Texture
  86839. effect.setTexture("textureSampler", this._blurTexture);
  86840. // Cache
  86841. var engine = this._engine;
  86842. var previousStencilBuffer = engine.getStencilBuffer();
  86843. var previousStencilFunction = engine.getStencilFunction();
  86844. var previousStencilMask = engine.getStencilMask();
  86845. var previousStencilOperationPass = engine.getStencilOperationPass();
  86846. var previousStencilOperationFail = engine.getStencilOperationFail();
  86847. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86848. var previousStencilReference = engine.getStencilFunctionReference();
  86849. // Stencil operations
  86850. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86851. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86852. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86853. // Draw order
  86854. engine.setStencilMask(0x00);
  86855. engine.setStencilBuffer(true);
  86856. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86857. // 2 passes inner outer
  86858. if (this.outerGlow) {
  86859. effect.setFloat("offset", 0);
  86860. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86861. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86862. }
  86863. if (this.innerGlow) {
  86864. effect.setFloat("offset", 1);
  86865. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86866. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86867. }
  86868. // Restore Cache
  86869. engine.setStencilFunction(previousStencilFunction);
  86870. engine.setStencilMask(previousStencilMask);
  86871. engine.setStencilBuffer(previousStencilBuffer);
  86872. engine.setStencilOperationPass(previousStencilOperationPass);
  86873. engine.setStencilOperationFail(previousStencilOperationFail);
  86874. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86875. engine.setStencilFunctionReference(previousStencilReference);
  86876. };
  86877. /**
  86878. * Returns true if the layer contains information to display, otherwise false.
  86879. */
  86880. HighlightLayer.prototype.shouldRender = function () {
  86881. if (_super.prototype.shouldRender.call(this)) {
  86882. return this._meshes ? true : false;
  86883. }
  86884. return false;
  86885. };
  86886. /**
  86887. * Returns true if the mesh should render, otherwise false.
  86888. * @param mesh The mesh to render
  86889. * @returns true if it should render otherwise false
  86890. */
  86891. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86892. // Excluded Mesh
  86893. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86894. return false;
  86895. }
  86896. ;
  86897. return true;
  86898. };
  86899. /**
  86900. * Sets the required values for both the emissive texture and and the main color.
  86901. */
  86902. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86903. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86904. if (highlightLayerMesh) {
  86905. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86906. }
  86907. else {
  86908. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86909. }
  86910. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86911. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86912. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86913. }
  86914. else {
  86915. this._emissiveTextureAndColor.texture = null;
  86916. }
  86917. };
  86918. /**
  86919. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86920. * @param mesh The mesh to exclude from the highlight layer
  86921. */
  86922. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86923. if (!this._excludedMeshes) {
  86924. return;
  86925. }
  86926. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86927. if (!meshExcluded) {
  86928. this._excludedMeshes[mesh.uniqueId] = {
  86929. mesh: mesh,
  86930. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86931. mesh.getEngine().setStencilBuffer(false);
  86932. }),
  86933. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86934. mesh.getEngine().setStencilBuffer(true);
  86935. }),
  86936. };
  86937. }
  86938. };
  86939. /**
  86940. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86941. * @param mesh The mesh to highlight
  86942. */
  86943. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86944. if (!this._excludedMeshes) {
  86945. return;
  86946. }
  86947. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86948. if (meshExcluded) {
  86949. if (meshExcluded.beforeRender) {
  86950. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86951. }
  86952. if (meshExcluded.afterRender) {
  86953. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86954. }
  86955. }
  86956. this._excludedMeshes[mesh.uniqueId] = null;
  86957. };
  86958. /**
  86959. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86960. * @param mesh mesh to test
  86961. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86962. */
  86963. HighlightLayer.prototype.hasMesh = function (mesh) {
  86964. if (!this._meshes) {
  86965. return false;
  86966. }
  86967. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86968. };
  86969. /**
  86970. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86971. * @param mesh The mesh to highlight
  86972. * @param color The color of the highlight
  86973. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86974. */
  86975. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86976. var _this = this;
  86977. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86978. if (!this._meshes) {
  86979. return;
  86980. }
  86981. var meshHighlight = this._meshes[mesh.uniqueId];
  86982. if (meshHighlight) {
  86983. meshHighlight.color = color;
  86984. }
  86985. else {
  86986. this._meshes[mesh.uniqueId] = {
  86987. mesh: mesh,
  86988. color: color,
  86989. // Lambda required for capture due to Observable this context
  86990. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86991. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86992. _this._defaultStencilReference(mesh);
  86993. }
  86994. else {
  86995. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86996. }
  86997. }),
  86998. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86999. glowEmissiveOnly: glowEmissiveOnly
  87000. };
  87001. }
  87002. this._shouldRender = true;
  87003. };
  87004. /**
  87005. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87006. * @param mesh The mesh to highlight
  87007. */
  87008. HighlightLayer.prototype.removeMesh = function (mesh) {
  87009. if (!this._meshes) {
  87010. return;
  87011. }
  87012. var meshHighlight = this._meshes[mesh.uniqueId];
  87013. if (meshHighlight) {
  87014. if (meshHighlight.observerHighlight) {
  87015. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87016. }
  87017. if (meshHighlight.observerDefault) {
  87018. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87019. }
  87020. delete this._meshes[mesh.uniqueId];
  87021. }
  87022. this._shouldRender = false;
  87023. for (var meshHighlightToCheck in this._meshes) {
  87024. if (this._meshes[meshHighlightToCheck]) {
  87025. this._shouldRender = true;
  87026. break;
  87027. }
  87028. }
  87029. };
  87030. /**
  87031. * Force the stencil to the normal expected value for none glowing parts
  87032. */
  87033. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87034. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87035. };
  87036. /**
  87037. * Free any resources and references associated to a mesh.
  87038. * Internal use
  87039. * @param mesh The mesh to free.
  87040. */
  87041. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87042. this.removeMesh(mesh);
  87043. this.removeExcludedMesh(mesh);
  87044. };
  87045. /**
  87046. * Dispose the highlight layer and free resources.
  87047. */
  87048. HighlightLayer.prototype.dispose = function () {
  87049. if (this._meshes) {
  87050. // Clean mesh references
  87051. for (var id in this._meshes) {
  87052. var meshHighlight = this._meshes[id];
  87053. if (meshHighlight && meshHighlight.mesh) {
  87054. if (meshHighlight.observerHighlight) {
  87055. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87056. }
  87057. if (meshHighlight.observerDefault) {
  87058. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87059. }
  87060. }
  87061. }
  87062. this._meshes = null;
  87063. }
  87064. if (this._excludedMeshes) {
  87065. for (var id in this._excludedMeshes) {
  87066. var meshHighlight = this._excludedMeshes[id];
  87067. if (meshHighlight) {
  87068. if (meshHighlight.beforeRender) {
  87069. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87070. }
  87071. if (meshHighlight.afterRender) {
  87072. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87073. }
  87074. }
  87075. }
  87076. this._excludedMeshes = null;
  87077. }
  87078. _super.prototype.dispose.call(this);
  87079. };
  87080. /**
  87081. * Effect Name of the highlight layer.
  87082. */
  87083. HighlightLayer.EffectName = "HighlightLayer";
  87084. /**
  87085. * The neutral color used during the preparation of the glow effect.
  87086. * This is black by default as the blend operation is a blend operation.
  87087. */
  87088. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87089. /**
  87090. * Stencil value used for glowing meshes.
  87091. */
  87092. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87093. /**
  87094. * Stencil value used for the other meshes in the scene.
  87095. */
  87096. HighlightLayer.NormalMeshStencilReference = 0x01;
  87097. return HighlightLayer;
  87098. }(BABYLON.EffectLayer));
  87099. BABYLON.HighlightLayer = HighlightLayer;
  87100. })(BABYLON || (BABYLON = {}));
  87101. //# sourceMappingURL=babylon.highlightLayer.js.map
  87102. "use strict";
  87103. var BABYLON;
  87104. (function (BABYLON) {
  87105. /**
  87106. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87107. *
  87108. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87109. * glowy meshes to your scene.
  87110. *
  87111. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87112. */
  87113. var GlowLayer = /** @class */ (function (_super) {
  87114. __extends(GlowLayer, _super);
  87115. /**
  87116. * Instantiates a new glow Layer and references it to the scene.
  87117. * @param name The name of the layer
  87118. * @param scene The scene to use the layer in
  87119. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87120. */
  87121. function GlowLayer(name, scene, options) {
  87122. var _this = _super.call(this, name, scene) || this;
  87123. _this.name = name;
  87124. _this._intensity = 1.0;
  87125. _this._includedOnlyMeshes = [];
  87126. _this._excludedMeshes = [];
  87127. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87128. // Adapt options
  87129. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87130. // Initialize the layer
  87131. _this._init({
  87132. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87133. camera: _this._options.camera,
  87134. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87135. mainTextureRatio: _this._options.mainTextureRatio
  87136. });
  87137. return _this;
  87138. }
  87139. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87140. /**
  87141. * Gets the kernel size of the blur.
  87142. */
  87143. get: function () {
  87144. return this._horizontalBlurPostprocess1.kernel;
  87145. },
  87146. /**
  87147. * Sets the kernel size of the blur.
  87148. */
  87149. set: function (value) {
  87150. this._horizontalBlurPostprocess1.kernel = value;
  87151. this._verticalBlurPostprocess1.kernel = value;
  87152. this._horizontalBlurPostprocess2.kernel = value;
  87153. this._verticalBlurPostprocess2.kernel = value;
  87154. },
  87155. enumerable: true,
  87156. configurable: true
  87157. });
  87158. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87159. /**
  87160. * Gets the glow intensity.
  87161. */
  87162. get: function () {
  87163. return this._intensity;
  87164. },
  87165. /**
  87166. * Sets the glow intensity.
  87167. */
  87168. set: function (value) {
  87169. this._intensity = value;
  87170. },
  87171. enumerable: true,
  87172. configurable: true
  87173. });
  87174. /**
  87175. * Get the effect name of the layer.
  87176. * @return The effect name
  87177. */
  87178. GlowLayer.prototype.getEffectName = function () {
  87179. return GlowLayer.EffectName;
  87180. };
  87181. /**
  87182. * Create the merge effect. This is the shader use to blit the information back
  87183. * to the main canvas at the end of the scene rendering.
  87184. */
  87185. GlowLayer.prototype._createMergeEffect = function () {
  87186. // Effect
  87187. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87188. };
  87189. /**
  87190. * Creates the render target textures and post processes used in the glow layer.
  87191. */
  87192. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87193. var _this = this;
  87194. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87195. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87196. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87197. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87198. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87199. width: blurTextureWidth,
  87200. height: blurTextureHeight
  87201. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87202. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87203. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87204. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87205. this._blurTexture1.renderParticles = false;
  87206. this._blurTexture1.ignoreCameraViewport = true;
  87207. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87208. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87209. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87210. width: blurTextureWidth2,
  87211. height: blurTextureHeight2
  87212. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87213. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87214. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87215. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87216. this._blurTexture2.renderParticles = false;
  87217. this._blurTexture2.ignoreCameraViewport = true;
  87218. this._textures = [this._blurTexture1, this._blurTexture2];
  87219. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87220. width: blurTextureWidth,
  87221. height: blurTextureHeight
  87222. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87223. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87224. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87225. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87226. effect.setTexture("textureSampler", _this._mainTexture);
  87227. });
  87228. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87229. width: blurTextureWidth,
  87230. height: blurTextureHeight
  87231. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87232. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87233. width: blurTextureWidth2,
  87234. height: blurTextureHeight2
  87235. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87236. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87237. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87238. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87239. effect.setTexture("textureSampler", _this._blurTexture1);
  87240. });
  87241. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87242. width: blurTextureWidth2,
  87243. height: blurTextureHeight2
  87244. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87245. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87246. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87247. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87248. this._mainTexture.samples = this._options.mainTextureSamples;
  87249. this._mainTexture.onAfterUnbindObservable.add(function () {
  87250. var internalTexture = _this._blurTexture1.getInternalTexture();
  87251. if (internalTexture) {
  87252. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87253. internalTexture = _this._blurTexture2.getInternalTexture();
  87254. if (internalTexture) {
  87255. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87256. }
  87257. }
  87258. });
  87259. // Prevent autoClear.
  87260. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87261. };
  87262. /**
  87263. * Checks for the readiness of the element composing the layer.
  87264. * @param subMesh the mesh to check for
  87265. * @param useInstances specify wether or not to use instances to render the mesh
  87266. * @param emissiveTexture the associated emissive texture used to generate the glow
  87267. * @return true if ready otherwise, false
  87268. */
  87269. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87270. var material = subMesh.getMaterial();
  87271. var mesh = subMesh.getRenderingMesh();
  87272. if (!material || !mesh) {
  87273. return false;
  87274. }
  87275. var emissiveTexture = material.emissiveTexture;
  87276. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87277. };
  87278. /**
  87279. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87280. */
  87281. GlowLayer.prototype.needStencil = function () {
  87282. return false;
  87283. };
  87284. /**
  87285. * Implementation specific of rendering the generating effect on the main canvas.
  87286. * @param effect The effect used to render through
  87287. */
  87288. GlowLayer.prototype._internalRender = function (effect) {
  87289. // Texture
  87290. effect.setTexture("textureSampler", this._blurTexture1);
  87291. effect.setTexture("textureSampler2", this._blurTexture2);
  87292. effect.setFloat("offset", this._intensity);
  87293. // Cache
  87294. var engine = this._engine;
  87295. var previousStencilBuffer = engine.getStencilBuffer();
  87296. // Draw order
  87297. engine.setStencilBuffer(false);
  87298. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87299. // Draw order
  87300. engine.setStencilBuffer(previousStencilBuffer);
  87301. };
  87302. /**
  87303. * Sets the required values for both the emissive texture and and the main color.
  87304. */
  87305. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87306. var textureLevel = 1.0;
  87307. if (this.customEmissiveTextureSelector) {
  87308. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87309. }
  87310. else {
  87311. if (material) {
  87312. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87313. if (this._emissiveTextureAndColor.texture) {
  87314. textureLevel = this._emissiveTextureAndColor.texture.level;
  87315. }
  87316. }
  87317. else {
  87318. this._emissiveTextureAndColor.texture = null;
  87319. }
  87320. }
  87321. if (this.customEmissiveColorSelector) {
  87322. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87323. }
  87324. else {
  87325. if (material.emissiveColor) {
  87326. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87327. }
  87328. else {
  87329. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87330. }
  87331. }
  87332. };
  87333. /**
  87334. * Returns true if the mesh should render, otherwise false.
  87335. * @param mesh The mesh to render
  87336. * @returns true if it should render otherwise false
  87337. */
  87338. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87339. return this.hasMesh(mesh);
  87340. };
  87341. /**
  87342. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87343. * @param mesh The mesh to exclude from the glow layer
  87344. */
  87345. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87346. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87347. this._excludedMeshes.push(mesh.uniqueId);
  87348. }
  87349. };
  87350. /**
  87351. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87352. * @param mesh The mesh to remove
  87353. */
  87354. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87355. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87356. if (index !== -1) {
  87357. this._excludedMeshes.splice(index, 1);
  87358. }
  87359. };
  87360. /**
  87361. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87362. * @param mesh The mesh to include in the glow layer
  87363. */
  87364. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87365. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87366. this._includedOnlyMeshes.push(mesh.uniqueId);
  87367. }
  87368. };
  87369. /**
  87370. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87371. * @param mesh The mesh to remove
  87372. */
  87373. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87374. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87375. if (index !== -1) {
  87376. this._includedOnlyMeshes.splice(index, 1);
  87377. }
  87378. };
  87379. /**
  87380. * Determine if a given mesh will be used in the glow layer
  87381. * @param mesh The mesh to test
  87382. * @returns true if the mesh will be highlighted by the current glow layer
  87383. */
  87384. GlowLayer.prototype.hasMesh = function (mesh) {
  87385. // Included Mesh
  87386. if (this._includedOnlyMeshes.length) {
  87387. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87388. }
  87389. ;
  87390. // Excluded Mesh
  87391. if (this._excludedMeshes.length) {
  87392. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87393. }
  87394. ;
  87395. return true;
  87396. };
  87397. /**
  87398. * Free any resources and references associated to a mesh.
  87399. * Internal use
  87400. * @param mesh The mesh to free.
  87401. */
  87402. GlowLayer.prototype._disposeMesh = function (mesh) {
  87403. this.removeIncludedOnlyMesh(mesh);
  87404. this.removeExcludedMesh(mesh);
  87405. };
  87406. /**
  87407. * Effect Name of the layer.
  87408. */
  87409. GlowLayer.EffectName = "GlowLayer";
  87410. /**
  87411. * The default blur kernel size used for the glow.
  87412. */
  87413. GlowLayer.DefaultBlurKernelSize = 32;
  87414. /**
  87415. * The default texture size ratio used for the glow.
  87416. */
  87417. GlowLayer.DefaultTextureRatio = 0.5;
  87418. return GlowLayer;
  87419. }(BABYLON.EffectLayer));
  87420. BABYLON.GlowLayer = GlowLayer;
  87421. })(BABYLON || (BABYLON = {}));
  87422. //# sourceMappingURL=babylon.glowLayer.js.map
  87423. "use strict";
  87424. var BABYLON;
  87425. (function (BABYLON) {
  87426. /**
  87427. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87428. */
  87429. var AssetTaskState;
  87430. (function (AssetTaskState) {
  87431. /**
  87432. * Initialization
  87433. */
  87434. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87435. /**
  87436. * Running
  87437. */
  87438. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87439. /**
  87440. * Done
  87441. */
  87442. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87443. /**
  87444. * Error
  87445. */
  87446. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87447. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87448. /**
  87449. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87450. */
  87451. var AbstractAssetTask = /** @class */ (function () {
  87452. /**
  87453. * Creates a new {BABYLON.AssetsManager}
  87454. * @param name defines the name of the task
  87455. */
  87456. function AbstractAssetTask(
  87457. /**
  87458. * Task name
  87459. */ name) {
  87460. this.name = name;
  87461. this._isCompleted = false;
  87462. this._taskState = AssetTaskState.INIT;
  87463. }
  87464. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87465. /**
  87466. * Get if the task is completed
  87467. */
  87468. get: function () {
  87469. return this._isCompleted;
  87470. },
  87471. enumerable: true,
  87472. configurable: true
  87473. });
  87474. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87475. /**
  87476. * Gets the current state of the task
  87477. */
  87478. get: function () {
  87479. return this._taskState;
  87480. },
  87481. enumerable: true,
  87482. configurable: true
  87483. });
  87484. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87485. /**
  87486. * Gets the current error object (if task is in error)
  87487. */
  87488. get: function () {
  87489. return this._errorObject;
  87490. },
  87491. enumerable: true,
  87492. configurable: true
  87493. });
  87494. /**
  87495. * Internal only
  87496. * @ignore
  87497. */
  87498. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87499. if (this._errorObject) {
  87500. return;
  87501. }
  87502. this._errorObject = {
  87503. message: message,
  87504. exception: exception
  87505. };
  87506. };
  87507. /**
  87508. * Execute the current task
  87509. * @param scene defines the scene where you want your assets to be loaded
  87510. * @param onSuccess is a callback called when the task is successfully executed
  87511. * @param onError is a callback called if an error occurs
  87512. */
  87513. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87514. var _this = this;
  87515. this._taskState = AssetTaskState.RUNNING;
  87516. this.runTask(scene, function () {
  87517. _this.onDoneCallback(onSuccess, onError);
  87518. }, function (msg, exception) {
  87519. _this.onErrorCallback(onError, msg, exception);
  87520. });
  87521. };
  87522. /**
  87523. * Execute the current task
  87524. * @param scene defines the scene where you want your assets to be loaded
  87525. * @param onSuccess is a callback called when the task is successfully executed
  87526. * @param onError is a callback called if an error occurs
  87527. */
  87528. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87529. throw new Error("runTask is not implemented");
  87530. };
  87531. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87532. this._taskState = AssetTaskState.ERROR;
  87533. this._errorObject = {
  87534. message: message,
  87535. exception: exception
  87536. };
  87537. if (this.onError) {
  87538. this.onError(this, message, exception);
  87539. }
  87540. onError();
  87541. };
  87542. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87543. try {
  87544. this._taskState = AssetTaskState.DONE;
  87545. this._isCompleted = true;
  87546. if (this.onSuccess) {
  87547. this.onSuccess(this);
  87548. }
  87549. onSuccess();
  87550. }
  87551. catch (e) {
  87552. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87553. }
  87554. };
  87555. return AbstractAssetTask;
  87556. }());
  87557. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87558. /**
  87559. * Class used to share progress information about assets loading
  87560. */
  87561. var AssetsProgressEvent = /** @class */ (function () {
  87562. /**
  87563. * Creates a {BABYLON.AssetsProgressEvent}
  87564. * @param remainingCount defines the number of remaining tasks to process
  87565. * @param totalCount defines the total number of tasks
  87566. * @param task defines the task that was just processed
  87567. */
  87568. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87569. this.remainingCount = remainingCount;
  87570. this.totalCount = totalCount;
  87571. this.task = task;
  87572. }
  87573. return AssetsProgressEvent;
  87574. }());
  87575. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87576. /**
  87577. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87578. */
  87579. var MeshAssetTask = /** @class */ (function (_super) {
  87580. __extends(MeshAssetTask, _super);
  87581. /**
  87582. * Creates a new {BABYLON.MeshAssetTask}
  87583. * @param name defines the name of the task
  87584. * @param meshesNames defines the list of mesh's names you want to load
  87585. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87586. * @param sceneFilename defines the filename of the scene to load from
  87587. */
  87588. function MeshAssetTask(
  87589. /**
  87590. * Defines the name of the task
  87591. */
  87592. name,
  87593. /**
  87594. * Defines the list of mesh's names you want to load
  87595. */
  87596. meshesNames,
  87597. /**
  87598. * Defines the root url to use as a base to load your meshes and associated resources
  87599. */
  87600. rootUrl,
  87601. /**
  87602. * Defines the filename of the scene to load from
  87603. */
  87604. sceneFilename) {
  87605. var _this = _super.call(this, name) || this;
  87606. _this.name = name;
  87607. _this.meshesNames = meshesNames;
  87608. _this.rootUrl = rootUrl;
  87609. _this.sceneFilename = sceneFilename;
  87610. return _this;
  87611. }
  87612. /**
  87613. * Execute the current task
  87614. * @param scene defines the scene where you want your assets to be loaded
  87615. * @param onSuccess is a callback called when the task is successfully executed
  87616. * @param onError is a callback called if an error occurs
  87617. */
  87618. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87619. var _this = this;
  87620. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87621. _this.loadedMeshes = meshes;
  87622. _this.loadedParticleSystems = particleSystems;
  87623. _this.loadedSkeletons = skeletons;
  87624. onSuccess();
  87625. }, null, function (scene, message, exception) {
  87626. onError(message, exception);
  87627. });
  87628. };
  87629. return MeshAssetTask;
  87630. }(AbstractAssetTask));
  87631. BABYLON.MeshAssetTask = MeshAssetTask;
  87632. /**
  87633. * Define a task used by {BABYLON.AssetsManager} to load text content
  87634. */
  87635. var TextFileAssetTask = /** @class */ (function (_super) {
  87636. __extends(TextFileAssetTask, _super);
  87637. /**
  87638. * Creates a new TextFileAssetTask object
  87639. * @param name defines the name of the task
  87640. * @param url defines the location of the file to load
  87641. */
  87642. function TextFileAssetTask(
  87643. /**
  87644. * Defines the name of the task
  87645. */
  87646. name,
  87647. /**
  87648. * Defines the location of the file to load
  87649. */
  87650. url) {
  87651. var _this = _super.call(this, name) || this;
  87652. _this.name = name;
  87653. _this.url = url;
  87654. return _this;
  87655. }
  87656. /**
  87657. * Execute the current task
  87658. * @param scene defines the scene where you want your assets to be loaded
  87659. * @param onSuccess is a callback called when the task is successfully executed
  87660. * @param onError is a callback called if an error occurs
  87661. */
  87662. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87663. var _this = this;
  87664. scene._loadFile(this.url, function (data) {
  87665. _this.text = data;
  87666. onSuccess();
  87667. }, undefined, false, false, function (request, exception) {
  87668. if (request) {
  87669. onError(request.status + " " + request.statusText, exception);
  87670. }
  87671. });
  87672. };
  87673. return TextFileAssetTask;
  87674. }(AbstractAssetTask));
  87675. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87676. /**
  87677. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87678. */
  87679. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87680. __extends(BinaryFileAssetTask, _super);
  87681. /**
  87682. * Creates a new BinaryFileAssetTask object
  87683. * @param name defines the name of the new task
  87684. * @param url defines the location of the file to load
  87685. */
  87686. function BinaryFileAssetTask(
  87687. /**
  87688. * Defines the name of the task
  87689. */
  87690. name,
  87691. /**
  87692. * Defines the location of the file to load
  87693. */
  87694. url) {
  87695. var _this = _super.call(this, name) || this;
  87696. _this.name = name;
  87697. _this.url = url;
  87698. return _this;
  87699. }
  87700. /**
  87701. * Execute the current task
  87702. * @param scene defines the scene where you want your assets to be loaded
  87703. * @param onSuccess is a callback called when the task is successfully executed
  87704. * @param onError is a callback called if an error occurs
  87705. */
  87706. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87707. var _this = this;
  87708. scene._loadFile(this.url, function (data) {
  87709. _this.data = data;
  87710. onSuccess();
  87711. }, undefined, true, true, function (request, exception) {
  87712. if (request) {
  87713. onError(request.status + " " + request.statusText, exception);
  87714. }
  87715. });
  87716. };
  87717. return BinaryFileAssetTask;
  87718. }(AbstractAssetTask));
  87719. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  87720. /**
  87721. * Define a task used by {BABYLON.AssetsManager} to load images
  87722. */
  87723. var ImageAssetTask = /** @class */ (function (_super) {
  87724. __extends(ImageAssetTask, _super);
  87725. /**
  87726. * Creates a new ImageAssetTask
  87727. * @param name defines the name of the task
  87728. * @param url defines the location of the image to load
  87729. */
  87730. function ImageAssetTask(
  87731. /**
  87732. * Defines the name of the task
  87733. */
  87734. name,
  87735. /**
  87736. * Defines the location of the image to load
  87737. */
  87738. url) {
  87739. var _this = _super.call(this, name) || this;
  87740. _this.name = name;
  87741. _this.url = url;
  87742. return _this;
  87743. }
  87744. /**
  87745. * Execute the current task
  87746. * @param scene defines the scene where you want your assets to be loaded
  87747. * @param onSuccess is a callback called when the task is successfully executed
  87748. * @param onError is a callback called if an error occurs
  87749. */
  87750. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87751. var _this = this;
  87752. var img = new Image();
  87753. BABYLON.Tools.SetCorsBehavior(this.url, img);
  87754. img.onload = function () {
  87755. _this.image = img;
  87756. onSuccess();
  87757. };
  87758. img.onerror = function (err) {
  87759. onError("Error loading image", err);
  87760. };
  87761. img.src = this.url;
  87762. };
  87763. return ImageAssetTask;
  87764. }(AbstractAssetTask));
  87765. BABYLON.ImageAssetTask = ImageAssetTask;
  87766. /**
  87767. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87768. */
  87769. var TextureAssetTask = /** @class */ (function (_super) {
  87770. __extends(TextureAssetTask, _super);
  87771. /**
  87772. * Creates a new TextureAssetTask object
  87773. * @param name defines the name of the task
  87774. * @param url defines the location of the file to load
  87775. * @param noMipmap defines if mipmap should not be generated (default is false)
  87776. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87777. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87778. */
  87779. function TextureAssetTask(
  87780. /**
  87781. * Defines the name of the task
  87782. */
  87783. name,
  87784. /**
  87785. * Defines the location of the file to load
  87786. */
  87787. url,
  87788. /**
  87789. * Defines if mipmap should not be generated (default is false)
  87790. */
  87791. noMipmap,
  87792. /**
  87793. * Defines if texture must be inverted on Y axis (default is false)
  87794. */
  87795. invertY,
  87796. /**
  87797. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87798. */
  87799. samplingMode) {
  87800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87801. var _this = _super.call(this, name) || this;
  87802. _this.name = name;
  87803. _this.url = url;
  87804. _this.noMipmap = noMipmap;
  87805. _this.invertY = invertY;
  87806. _this.samplingMode = samplingMode;
  87807. return _this;
  87808. }
  87809. /**
  87810. * Execute the current task
  87811. * @param scene defines the scene where you want your assets to be loaded
  87812. * @param onSuccess is a callback called when the task is successfully executed
  87813. * @param onError is a callback called if an error occurs
  87814. */
  87815. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87816. var onload = function () {
  87817. onSuccess();
  87818. };
  87819. var onerror = function (message, exception) {
  87820. onError(message, exception);
  87821. };
  87822. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87823. };
  87824. return TextureAssetTask;
  87825. }(AbstractAssetTask));
  87826. BABYLON.TextureAssetTask = TextureAssetTask;
  87827. /**
  87828. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87829. */
  87830. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87831. __extends(CubeTextureAssetTask, _super);
  87832. /**
  87833. * Creates a new CubeTextureAssetTask
  87834. * @param name defines the name of the task
  87835. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87836. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87837. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87838. * @param files defines the explicit list of files (undefined by default)
  87839. */
  87840. function CubeTextureAssetTask(
  87841. /**
  87842. * Defines the name of the task
  87843. */
  87844. name,
  87845. /**
  87846. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87847. */
  87848. url,
  87849. /**
  87850. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87851. */
  87852. extensions,
  87853. /**
  87854. * Defines if mipmaps should not be generated (default is false)
  87855. */
  87856. noMipmap,
  87857. /**
  87858. * Defines the explicit list of files (undefined by default)
  87859. */
  87860. files) {
  87861. var _this = _super.call(this, name) || this;
  87862. _this.name = name;
  87863. _this.url = url;
  87864. _this.extensions = extensions;
  87865. _this.noMipmap = noMipmap;
  87866. _this.files = files;
  87867. return _this;
  87868. }
  87869. /**
  87870. * Execute the current task
  87871. * @param scene defines the scene where you want your assets to be loaded
  87872. * @param onSuccess is a callback called when the task is successfully executed
  87873. * @param onError is a callback called if an error occurs
  87874. */
  87875. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87876. var onload = function () {
  87877. onSuccess();
  87878. };
  87879. var onerror = function (message, exception) {
  87880. onError(message, exception);
  87881. };
  87882. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87883. };
  87884. return CubeTextureAssetTask;
  87885. }(AbstractAssetTask));
  87886. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87887. /**
  87888. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87889. */
  87890. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87891. __extends(HDRCubeTextureAssetTask, _super);
  87892. /**
  87893. * Creates a new HDRCubeTextureAssetTask object
  87894. * @param name defines the name of the task
  87895. * @param url defines the location of the file to load
  87896. * @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.
  87897. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87898. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87899. * @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)
  87900. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87901. */
  87902. function HDRCubeTextureAssetTask(
  87903. /**
  87904. * Defines the name of the task
  87905. */
  87906. name,
  87907. /**
  87908. * Defines the location of the file to load
  87909. */
  87910. url,
  87911. /**
  87912. * 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.
  87913. */
  87914. size,
  87915. /**
  87916. * Defines if mipmaps should not be generated (default is false)
  87917. */
  87918. noMipmap,
  87919. /**
  87920. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87921. */
  87922. generateHarmonics,
  87923. /**
  87924. * 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)
  87925. */
  87926. useInGammaSpace,
  87927. /**
  87928. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87929. */
  87930. usePMREMGenerator) {
  87931. if (noMipmap === void 0) { noMipmap = false; }
  87932. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87933. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87934. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87935. var _this = _super.call(this, name) || this;
  87936. _this.name = name;
  87937. _this.url = url;
  87938. _this.size = size;
  87939. _this.noMipmap = noMipmap;
  87940. _this.generateHarmonics = generateHarmonics;
  87941. _this.useInGammaSpace = useInGammaSpace;
  87942. _this.usePMREMGenerator = usePMREMGenerator;
  87943. return _this;
  87944. }
  87945. /**
  87946. * Execute the current task
  87947. * @param scene defines the scene where you want your assets to be loaded
  87948. * @param onSuccess is a callback called when the task is successfully executed
  87949. * @param onError is a callback called if an error occurs
  87950. */
  87951. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87952. var onload = function () {
  87953. onSuccess();
  87954. };
  87955. var onerror = function (message, exception) {
  87956. onError(message, exception);
  87957. };
  87958. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87959. };
  87960. return HDRCubeTextureAssetTask;
  87961. }(AbstractAssetTask));
  87962. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87963. /**
  87964. * This class can be used to easily import assets into a scene
  87965. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87966. */
  87967. var AssetsManager = /** @class */ (function () {
  87968. /**
  87969. * Creates a new AssetsManager
  87970. * @param scene defines the scene to work on
  87971. */
  87972. function AssetsManager(scene) {
  87973. this._isLoading = false;
  87974. this._tasks = new Array();
  87975. this._waitingTasksCount = 0;
  87976. this._totalTasksCount = 0;
  87977. /**
  87978. * Observable called when all tasks are processed
  87979. */
  87980. this.onTaskSuccessObservable = new BABYLON.Observable();
  87981. /**
  87982. * Observable called when a task had an error
  87983. */
  87984. this.onTaskErrorObservable = new BABYLON.Observable();
  87985. /**
  87986. * Observable called when a task is successful
  87987. */
  87988. this.onTasksDoneObservable = new BABYLON.Observable();
  87989. /**
  87990. * Observable called when a task is done (whatever the result is)
  87991. */
  87992. this.onProgressObservable = new BABYLON.Observable();
  87993. /**
  87994. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87995. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  87996. */
  87997. this.useDefaultLoadingScreen = true;
  87998. this._scene = scene;
  87999. }
  88000. /**
  88001. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88002. * @param taskName defines the name of the new task
  88003. * @param meshesNames defines the name of meshes to load
  88004. * @param rootUrl defines the root url to use to locate files
  88005. * @param sceneFilename defines the filename of the scene file
  88006. * @returns a new {BABYLON.MeshAssetTask} object
  88007. */
  88008. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88009. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88010. this._tasks.push(task);
  88011. return task;
  88012. };
  88013. /**
  88014. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88015. * @param taskName defines the name of the new task
  88016. * @param url defines the url of the file to load
  88017. * @returns a new {BABYLON.TextFileAssetTask} object
  88018. */
  88019. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88020. var task = new TextFileAssetTask(taskName, url);
  88021. this._tasks.push(task);
  88022. return task;
  88023. };
  88024. /**
  88025. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88026. * @param taskName defines the name of the new task
  88027. * @param url defines the url of the file to load
  88028. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88029. */
  88030. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88031. var task = new BinaryFileAssetTask(taskName, url);
  88032. this._tasks.push(task);
  88033. return task;
  88034. };
  88035. /**
  88036. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88037. * @param taskName defines the name of the new task
  88038. * @param url defines the url of the file to load
  88039. * @returns a new {BABYLON.ImageAssetTask} object
  88040. */
  88041. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88042. var task = new ImageAssetTask(taskName, url);
  88043. this._tasks.push(task);
  88044. return task;
  88045. };
  88046. /**
  88047. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88048. * @param taskName defines the name of the new task
  88049. * @param url defines the url of the file to load
  88050. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88051. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88052. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88053. * @returns a new {BABYLON.TextureAssetTask} object
  88054. */
  88055. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88057. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88058. this._tasks.push(task);
  88059. return task;
  88060. };
  88061. /**
  88062. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88063. * @param taskName defines the name of the new task
  88064. * @param url defines the url of the file to load
  88065. * @param extensions defines the extension to use to load the cube map (can be null)
  88066. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88067. * @param files defines the list of files to load (can be null)
  88068. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88069. */
  88070. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88071. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88072. this._tasks.push(task);
  88073. return task;
  88074. };
  88075. /**
  88076. *
  88077. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88078. * @param taskName defines the name of the new task
  88079. * @param url defines the url of the file to load
  88080. * @param size defines the size you want for the cubemap (can be null)
  88081. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88082. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88083. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88084. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88085. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88086. */
  88087. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88088. if (noMipmap === void 0) { noMipmap = false; }
  88089. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88090. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88091. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88092. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88093. this._tasks.push(task);
  88094. return task;
  88095. };
  88096. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88097. var _this = this;
  88098. this._waitingTasksCount--;
  88099. try {
  88100. if (task.taskState === AssetTaskState.DONE) {
  88101. // Let's remove successfull tasks
  88102. BABYLON.Tools.SetImmediate(function () {
  88103. var index = _this._tasks.indexOf(task);
  88104. if (index > -1) {
  88105. _this._tasks.splice(index, 1);
  88106. }
  88107. });
  88108. }
  88109. if (this.onProgress) {
  88110. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88111. }
  88112. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88113. }
  88114. catch (e) {
  88115. BABYLON.Tools.Error("Error running progress callbacks.");
  88116. console.log(e);
  88117. }
  88118. if (this._waitingTasksCount === 0) {
  88119. try {
  88120. if (this.onFinish) {
  88121. this.onFinish(this._tasks);
  88122. }
  88123. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88124. }
  88125. catch (e) {
  88126. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88127. console.log(e);
  88128. }
  88129. this._isLoading = false;
  88130. this._scene.getEngine().hideLoadingUI();
  88131. }
  88132. };
  88133. AssetsManager.prototype._runTask = function (task) {
  88134. var _this = this;
  88135. var done = function () {
  88136. try {
  88137. if (_this.onTaskSuccess) {
  88138. _this.onTaskSuccess(task);
  88139. }
  88140. _this.onTaskSuccessObservable.notifyObservers(task);
  88141. _this._decreaseWaitingTasksCount(task);
  88142. }
  88143. catch (e) {
  88144. error("Error executing task success callbacks", e);
  88145. }
  88146. };
  88147. var error = function (message, exception) {
  88148. task._setErrorObject(message, exception);
  88149. if (_this.onTaskError) {
  88150. _this.onTaskError(task);
  88151. }
  88152. _this.onTaskErrorObservable.notifyObservers(task);
  88153. _this._decreaseWaitingTasksCount(task);
  88154. };
  88155. task.run(this._scene, done, error);
  88156. };
  88157. /**
  88158. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88159. * @return the current instance of the {BABYLON.AssetsManager}
  88160. */
  88161. AssetsManager.prototype.reset = function () {
  88162. this._isLoading = false;
  88163. this._tasks = new Array();
  88164. return this;
  88165. };
  88166. /**
  88167. * Start the loading process
  88168. * @return the current instance of the {BABYLON.AssetsManager}
  88169. */
  88170. AssetsManager.prototype.load = function () {
  88171. if (this._isLoading) {
  88172. return this;
  88173. }
  88174. this._isLoading = true;
  88175. this._waitingTasksCount = this._tasks.length;
  88176. this._totalTasksCount = this._tasks.length;
  88177. if (this._waitingTasksCount === 0) {
  88178. this._isLoading = false;
  88179. if (this.onFinish) {
  88180. this.onFinish(this._tasks);
  88181. }
  88182. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88183. return this;
  88184. }
  88185. if (this.useDefaultLoadingScreen) {
  88186. this._scene.getEngine().displayLoadingUI();
  88187. }
  88188. for (var index = 0; index < this._tasks.length; index++) {
  88189. var task = this._tasks[index];
  88190. this._runTask(task);
  88191. }
  88192. return this;
  88193. };
  88194. return AssetsManager;
  88195. }());
  88196. BABYLON.AssetsManager = AssetsManager;
  88197. })(BABYLON || (BABYLON = {}));
  88198. //# sourceMappingURL=babylon.assetsManager.js.map
  88199. "use strict";
  88200. var BABYLON;
  88201. (function (BABYLON) {
  88202. var serializedGeometries = [];
  88203. var serializeGeometry = function (geometry, serializationGeometries) {
  88204. if (serializedGeometries[geometry.id]) {
  88205. return;
  88206. }
  88207. if (geometry.doNotSerialize) {
  88208. return;
  88209. }
  88210. if (geometry instanceof BABYLON.BoxGeometry) {
  88211. serializationGeometries.boxes.push(geometry.serialize());
  88212. }
  88213. else if (geometry instanceof BABYLON.SphereGeometry) {
  88214. serializationGeometries.spheres.push(geometry.serialize());
  88215. }
  88216. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88217. serializationGeometries.cylinders.push(geometry.serialize());
  88218. }
  88219. else if (geometry instanceof BABYLON.TorusGeometry) {
  88220. serializationGeometries.toruses.push(geometry.serialize());
  88221. }
  88222. else if (geometry instanceof BABYLON.GroundGeometry) {
  88223. serializationGeometries.grounds.push(geometry.serialize());
  88224. }
  88225. else if (geometry instanceof BABYLON.Plane) {
  88226. serializationGeometries.planes.push(geometry.serialize());
  88227. }
  88228. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88229. serializationGeometries.torusKnots.push(geometry.serialize());
  88230. }
  88231. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88232. throw new Error("Unknown primitive type");
  88233. }
  88234. else {
  88235. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88236. }
  88237. serializedGeometries[geometry.id] = true;
  88238. };
  88239. var serializeMesh = function (mesh, serializationScene) {
  88240. var serializationObject = {};
  88241. // Geometry
  88242. var geometry = mesh._geometry;
  88243. if (geometry) {
  88244. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88245. // 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
  88246. serializeGeometry(geometry, serializationScene.geometries);
  88247. }
  88248. }
  88249. // Custom
  88250. if (mesh.serialize) {
  88251. mesh.serialize(serializationObject);
  88252. }
  88253. return serializationObject;
  88254. };
  88255. var finalizeSingleMesh = function (mesh, serializationObject) {
  88256. //only works if the mesh is already loaded
  88257. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88258. //serialize material
  88259. if (mesh.material) {
  88260. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88261. serializationObject.materials = serializationObject.materials || [];
  88262. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88263. serializationObject.materials.push(mesh.material.serialize());
  88264. }
  88265. }
  88266. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88267. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88268. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88269. serializationObject.multiMaterials.push(mesh.material.serialize());
  88270. }
  88271. }
  88272. }
  88273. //serialize geometry
  88274. var geometry = mesh._geometry;
  88275. if (geometry) {
  88276. if (!serializationObject.geometries) {
  88277. serializationObject.geometries = {};
  88278. serializationObject.geometries.boxes = [];
  88279. serializationObject.geometries.spheres = [];
  88280. serializationObject.geometries.cylinders = [];
  88281. serializationObject.geometries.toruses = [];
  88282. serializationObject.geometries.grounds = [];
  88283. serializationObject.geometries.planes = [];
  88284. serializationObject.geometries.torusKnots = [];
  88285. serializationObject.geometries.vertexData = [];
  88286. }
  88287. serializeGeometry(geometry, serializationObject.geometries);
  88288. }
  88289. // Skeletons
  88290. if (mesh.skeleton) {
  88291. serializationObject.skeletons = serializationObject.skeletons || [];
  88292. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88293. }
  88294. //serialize the actual mesh
  88295. serializationObject.meshes = serializationObject.meshes || [];
  88296. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88297. }
  88298. };
  88299. var SceneSerializer = /** @class */ (function () {
  88300. function SceneSerializer() {
  88301. }
  88302. SceneSerializer.ClearCache = function () {
  88303. serializedGeometries = [];
  88304. };
  88305. SceneSerializer.Serialize = function (scene) {
  88306. var serializationObject = {};
  88307. SceneSerializer.ClearCache();
  88308. // Scene
  88309. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88310. serializationObject.autoClear = scene.autoClear;
  88311. serializationObject.clearColor = scene.clearColor.asArray();
  88312. serializationObject.ambientColor = scene.ambientColor.asArray();
  88313. serializationObject.gravity = scene.gravity.asArray();
  88314. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88315. serializationObject.workerCollisions = scene.workerCollisions;
  88316. // Fog
  88317. if (scene.fogMode && scene.fogMode !== 0) {
  88318. serializationObject.fogMode = scene.fogMode;
  88319. serializationObject.fogColor = scene.fogColor.asArray();
  88320. serializationObject.fogStart = scene.fogStart;
  88321. serializationObject.fogEnd = scene.fogEnd;
  88322. serializationObject.fogDensity = scene.fogDensity;
  88323. }
  88324. //Physics
  88325. if (scene.isPhysicsEnabled()) {
  88326. var physicEngine = scene.getPhysicsEngine();
  88327. if (physicEngine) {
  88328. serializationObject.physicsEnabled = true;
  88329. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88330. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88331. }
  88332. }
  88333. // Metadata
  88334. if (scene.metadata) {
  88335. serializationObject.metadata = scene.metadata;
  88336. }
  88337. // Morph targets
  88338. serializationObject.morphTargetManagers = [];
  88339. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88340. var abstractMesh = _a[_i];
  88341. var manager = abstractMesh.morphTargetManager;
  88342. if (manager) {
  88343. serializationObject.morphTargetManagers.push(manager.serialize());
  88344. }
  88345. }
  88346. // Lights
  88347. serializationObject.lights = [];
  88348. var index;
  88349. var light;
  88350. for (index = 0; index < scene.lights.length; index++) {
  88351. light = scene.lights[index];
  88352. if (!light.doNotSerialize) {
  88353. serializationObject.lights.push(light.serialize());
  88354. }
  88355. }
  88356. // Cameras
  88357. serializationObject.cameras = [];
  88358. for (index = 0; index < scene.cameras.length; index++) {
  88359. var camera = scene.cameras[index];
  88360. if (!camera.doNotSerialize) {
  88361. serializationObject.cameras.push(camera.serialize());
  88362. }
  88363. }
  88364. if (scene.activeCamera) {
  88365. serializationObject.activeCameraID = scene.activeCamera.id;
  88366. }
  88367. // Animations
  88368. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88369. // Materials
  88370. serializationObject.materials = [];
  88371. serializationObject.multiMaterials = [];
  88372. var material;
  88373. for (index = 0; index < scene.materials.length; index++) {
  88374. material = scene.materials[index];
  88375. if (!material.doNotSerialize) {
  88376. serializationObject.materials.push(material.serialize());
  88377. }
  88378. }
  88379. // MultiMaterials
  88380. serializationObject.multiMaterials = [];
  88381. for (index = 0; index < scene.multiMaterials.length; index++) {
  88382. var multiMaterial = scene.multiMaterials[index];
  88383. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88384. }
  88385. // Environment texture
  88386. if (scene.environmentTexture) {
  88387. serializationObject.environmentTexture = scene.environmentTexture.name;
  88388. }
  88389. // Skeletons
  88390. serializationObject.skeletons = [];
  88391. for (index = 0; index < scene.skeletons.length; index++) {
  88392. var skeleton = scene.skeletons[index];
  88393. if (!skeleton.doNotSerialize) {
  88394. serializationObject.skeletons.push(skeleton.serialize());
  88395. }
  88396. }
  88397. // Transform nodes
  88398. serializationObject.transformNodes = [];
  88399. for (index = 0; index < scene.transformNodes.length; index++) {
  88400. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88401. }
  88402. // Geometries
  88403. serializationObject.geometries = {};
  88404. serializationObject.geometries.boxes = [];
  88405. serializationObject.geometries.spheres = [];
  88406. serializationObject.geometries.cylinders = [];
  88407. serializationObject.geometries.toruses = [];
  88408. serializationObject.geometries.grounds = [];
  88409. serializationObject.geometries.planes = [];
  88410. serializationObject.geometries.torusKnots = [];
  88411. serializationObject.geometries.vertexData = [];
  88412. serializedGeometries = [];
  88413. var geometries = scene.getGeometries();
  88414. for (index = 0; index < geometries.length; index++) {
  88415. var geometry = geometries[index];
  88416. if (geometry.isReady()) {
  88417. serializeGeometry(geometry, serializationObject.geometries);
  88418. }
  88419. }
  88420. // Meshes
  88421. serializationObject.meshes = [];
  88422. for (index = 0; index < scene.meshes.length; index++) {
  88423. var abstractMesh = scene.meshes[index];
  88424. if (abstractMesh instanceof BABYLON.Mesh) {
  88425. var mesh = abstractMesh;
  88426. if (!mesh.doNotSerialize) {
  88427. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88428. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88429. }
  88430. }
  88431. }
  88432. }
  88433. // Particles Systems
  88434. serializationObject.particleSystems = [];
  88435. for (index = 0; index < scene.particleSystems.length; index++) {
  88436. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88437. }
  88438. // Lens flares
  88439. serializationObject.lensFlareSystems = [];
  88440. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88441. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88442. }
  88443. // Shadows
  88444. serializationObject.shadowGenerators = [];
  88445. for (index = 0; index < scene.lights.length; index++) {
  88446. light = scene.lights[index];
  88447. var shadowGenerator = light.getShadowGenerator();
  88448. if (shadowGenerator) {
  88449. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88450. }
  88451. }
  88452. // Action Manager
  88453. if (scene.actionManager) {
  88454. serializationObject.actions = scene.actionManager.serialize("scene");
  88455. }
  88456. // Audio
  88457. serializationObject.sounds = [];
  88458. for (index = 0; index < scene.soundTracks.length; index++) {
  88459. var soundtrack = scene.soundTracks[index];
  88460. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88461. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88462. }
  88463. }
  88464. return serializationObject;
  88465. };
  88466. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88467. if (withParents === void 0) { withParents = false; }
  88468. if (withChildren === void 0) { withChildren = false; }
  88469. var serializationObject = {};
  88470. SceneSerializer.ClearCache();
  88471. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88472. if (withParents || withChildren) {
  88473. //deliberate for loop! not for each, appended should be processed as well.
  88474. for (var i = 0; i < toSerialize.length; ++i) {
  88475. if (withChildren) {
  88476. toSerialize[i].getDescendants().forEach(function (node) {
  88477. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88478. toSerialize.push(node);
  88479. }
  88480. });
  88481. }
  88482. //make sure the array doesn't contain the object already
  88483. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88484. toSerialize.push(toSerialize[i].parent);
  88485. }
  88486. }
  88487. }
  88488. toSerialize.forEach(function (mesh) {
  88489. finalizeSingleMesh(mesh, serializationObject);
  88490. });
  88491. return serializationObject;
  88492. };
  88493. return SceneSerializer;
  88494. }());
  88495. BABYLON.SceneSerializer = SceneSerializer;
  88496. })(BABYLON || (BABYLON = {}));
  88497. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88498. "use strict";
  88499. var BABYLON;
  88500. (function (BABYLON) {
  88501. var ReflectionProbe = /** @class */ (function () {
  88502. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88503. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88504. var _this = this;
  88505. this.name = name;
  88506. this._viewMatrix = BABYLON.Matrix.Identity();
  88507. this._target = BABYLON.Vector3.Zero();
  88508. this._add = BABYLON.Vector3.Zero();
  88509. this._invertYAxis = false;
  88510. this.position = BABYLON.Vector3.Zero();
  88511. this._scene = scene;
  88512. this._scene.reflectionProbes.push(this);
  88513. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88514. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88515. switch (faceIndex) {
  88516. case 0:
  88517. _this._add.copyFromFloats(1, 0, 0);
  88518. break;
  88519. case 1:
  88520. _this._add.copyFromFloats(-1, 0, 0);
  88521. break;
  88522. case 2:
  88523. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88524. break;
  88525. case 3:
  88526. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88527. break;
  88528. case 4:
  88529. _this._add.copyFromFloats(0, 0, 1);
  88530. break;
  88531. case 5:
  88532. _this._add.copyFromFloats(0, 0, -1);
  88533. break;
  88534. }
  88535. if (_this._attachedMesh) {
  88536. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88537. }
  88538. _this.position.addToRef(_this._add, _this._target);
  88539. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88540. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88541. scene._forcedViewPosition = _this.position;
  88542. });
  88543. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88544. scene._forcedViewPosition = null;
  88545. scene.updateTransformMatrix(true);
  88546. });
  88547. if (scene.activeCamera) {
  88548. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88549. }
  88550. }
  88551. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88552. get: function () {
  88553. return this._renderTargetTexture.samples;
  88554. },
  88555. set: function (value) {
  88556. this._renderTargetTexture.samples = value;
  88557. },
  88558. enumerable: true,
  88559. configurable: true
  88560. });
  88561. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88562. get: function () {
  88563. return this._renderTargetTexture.refreshRate;
  88564. },
  88565. set: function (value) {
  88566. this._renderTargetTexture.refreshRate = value;
  88567. },
  88568. enumerable: true,
  88569. configurable: true
  88570. });
  88571. ReflectionProbe.prototype.getScene = function () {
  88572. return this._scene;
  88573. };
  88574. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88575. get: function () {
  88576. return this._renderTargetTexture;
  88577. },
  88578. enumerable: true,
  88579. configurable: true
  88580. });
  88581. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88582. get: function () {
  88583. return this._renderTargetTexture.renderList;
  88584. },
  88585. enumerable: true,
  88586. configurable: true
  88587. });
  88588. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88589. this._attachedMesh = mesh;
  88590. };
  88591. /**
  88592. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88593. *
  88594. * @param renderingGroupId The rendering group id corresponding to its index
  88595. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88596. */
  88597. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88598. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88599. };
  88600. ReflectionProbe.prototype.dispose = function () {
  88601. var index = this._scene.reflectionProbes.indexOf(this);
  88602. if (index !== -1) {
  88603. // Remove from the scene if found
  88604. this._scene.reflectionProbes.splice(index, 1);
  88605. }
  88606. if (this._renderTargetTexture) {
  88607. this._renderTargetTexture.dispose();
  88608. this._renderTargetTexture = null;
  88609. }
  88610. };
  88611. return ReflectionProbe;
  88612. }());
  88613. BABYLON.ReflectionProbe = ReflectionProbe;
  88614. })(BABYLON || (BABYLON = {}));
  88615. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88616. "use strict";
  88617. var BABYLON;
  88618. (function (BABYLON) {
  88619. var Layer = /** @class */ (function () {
  88620. function Layer(name, imgUrl, scene, isBackground, color) {
  88621. this.name = name;
  88622. this.scale = new BABYLON.Vector2(1, 1);
  88623. this.offset = new BABYLON.Vector2(0, 0);
  88624. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88625. this.layerMask = 0x0FFFFFFF;
  88626. this._vertexBuffers = {};
  88627. // Events
  88628. /**
  88629. * An event triggered when the layer is disposed.
  88630. * @type {BABYLON.Observable}
  88631. */
  88632. this.onDisposeObservable = new BABYLON.Observable();
  88633. /**
  88634. * An event triggered before rendering the scene
  88635. * @type {BABYLON.Observable}
  88636. */
  88637. this.onBeforeRenderObservable = new BABYLON.Observable();
  88638. /**
  88639. * An event triggered after rendering the scene
  88640. * @type {BABYLON.Observable}
  88641. */
  88642. this.onAfterRenderObservable = new BABYLON.Observable();
  88643. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88644. this.isBackground = isBackground === undefined ? true : isBackground;
  88645. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88646. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88647. this._scene.layers.push(this);
  88648. var engine = this._scene.getEngine();
  88649. // VBO
  88650. var vertices = [];
  88651. vertices.push(1, 1);
  88652. vertices.push(-1, 1);
  88653. vertices.push(-1, -1);
  88654. vertices.push(1, -1);
  88655. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88656. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88657. this._createIndexBuffer();
  88658. // Effects
  88659. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  88660. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88661. }
  88662. Object.defineProperty(Layer.prototype, "onDispose", {
  88663. set: function (callback) {
  88664. if (this._onDisposeObserver) {
  88665. this.onDisposeObservable.remove(this._onDisposeObserver);
  88666. }
  88667. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88668. },
  88669. enumerable: true,
  88670. configurable: true
  88671. });
  88672. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88673. set: function (callback) {
  88674. if (this._onBeforeRenderObserver) {
  88675. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88676. }
  88677. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88678. },
  88679. enumerable: true,
  88680. configurable: true
  88681. });
  88682. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88683. set: function (callback) {
  88684. if (this._onAfterRenderObserver) {
  88685. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88686. }
  88687. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  88688. },
  88689. enumerable: true,
  88690. configurable: true
  88691. });
  88692. Layer.prototype._createIndexBuffer = function () {
  88693. var engine = this._scene.getEngine();
  88694. // Indices
  88695. var indices = [];
  88696. indices.push(0);
  88697. indices.push(1);
  88698. indices.push(2);
  88699. indices.push(0);
  88700. indices.push(2);
  88701. indices.push(3);
  88702. this._indexBuffer = engine.createIndexBuffer(indices);
  88703. };
  88704. Layer.prototype._rebuild = function () {
  88705. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88706. if (vb) {
  88707. vb._rebuild();
  88708. }
  88709. this._createIndexBuffer();
  88710. };
  88711. Layer.prototype.render = function () {
  88712. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  88713. // Check
  88714. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  88715. return;
  88716. var engine = this._scene.getEngine();
  88717. this.onBeforeRenderObservable.notifyObservers(this);
  88718. // Render
  88719. engine.enableEffect(currentEffect);
  88720. engine.setState(false);
  88721. // Texture
  88722. currentEffect.setTexture("textureSampler", this.texture);
  88723. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  88724. // Color
  88725. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  88726. // Scale / offset
  88727. currentEffect.setVector2("offset", this.offset);
  88728. currentEffect.setVector2("scale", this.scale);
  88729. // VBOs
  88730. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88731. // Draw order
  88732. if (!this.alphaTest) {
  88733. engine.setAlphaMode(this.alphaBlendingMode);
  88734. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88735. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88736. }
  88737. else {
  88738. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88739. }
  88740. this.onAfterRenderObservable.notifyObservers(this);
  88741. };
  88742. Layer.prototype.dispose = function () {
  88743. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88744. if (vertexBuffer) {
  88745. vertexBuffer.dispose();
  88746. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88747. }
  88748. if (this._indexBuffer) {
  88749. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88750. this._indexBuffer = null;
  88751. }
  88752. if (this.texture) {
  88753. this.texture.dispose();
  88754. this.texture = null;
  88755. }
  88756. // Remove from scene
  88757. var index = this._scene.layers.indexOf(this);
  88758. this._scene.layers.splice(index, 1);
  88759. // Callback
  88760. this.onDisposeObservable.notifyObservers(this);
  88761. this.onDisposeObservable.clear();
  88762. this.onAfterRenderObservable.clear();
  88763. this.onBeforeRenderObservable.clear();
  88764. };
  88765. return Layer;
  88766. }());
  88767. BABYLON.Layer = Layer;
  88768. })(BABYLON || (BABYLON = {}));
  88769. //# sourceMappingURL=babylon.layer.js.map
  88770. "use strict";
  88771. var BABYLON;
  88772. (function (BABYLON) {
  88773. var TextureTools = /** @class */ (function () {
  88774. function TextureTools() {
  88775. }
  88776. /**
  88777. * Uses the GPU to create a copy texture rescaled at a given size
  88778. * @param texture Texture to copy from
  88779. * @param width Desired width
  88780. * @param height Desired height
  88781. * @return Generated texture
  88782. */
  88783. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88784. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88785. var scene = texture.getScene();
  88786. var engine = scene.getEngine();
  88787. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88788. rtt.wrapU = texture.wrapU;
  88789. rtt.wrapV = texture.wrapV;
  88790. rtt.uOffset = texture.uOffset;
  88791. rtt.vOffset = texture.vOffset;
  88792. rtt.uScale = texture.uScale;
  88793. rtt.vScale = texture.vScale;
  88794. rtt.uAng = texture.uAng;
  88795. rtt.vAng = texture.vAng;
  88796. rtt.wAng = texture.wAng;
  88797. rtt.coordinatesIndex = texture.coordinatesIndex;
  88798. rtt.level = texture.level;
  88799. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88800. rtt._texture.isReady = false;
  88801. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88802. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88803. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88804. passPostProcess.getEffect().executeWhenCompiled(function () {
  88805. passPostProcess.onApply = function (effect) {
  88806. effect.setTexture("textureSampler", texture);
  88807. };
  88808. var internalTexture = rtt.getInternalTexture();
  88809. if (internalTexture) {
  88810. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88811. engine.unBindFramebuffer(internalTexture);
  88812. rtt.disposeFramebufferObjects();
  88813. passPostProcess.dispose();
  88814. internalTexture.isReady = true;
  88815. }
  88816. });
  88817. return rtt;
  88818. };
  88819. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88820. if (!scene._environmentBRDFTexture) {
  88821. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88822. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88823. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88824. scene._environmentBRDFTexture = texture;
  88825. }
  88826. return scene._environmentBRDFTexture;
  88827. };
  88828. 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=";
  88829. return TextureTools;
  88830. }());
  88831. BABYLON.TextureTools = TextureTools;
  88832. })(BABYLON || (BABYLON = {}));
  88833. //# sourceMappingURL=babylon.textureTools.js.map
  88834. "use strict";
  88835. var BABYLON;
  88836. (function (BABYLON) {
  88837. var FramingBehavior = /** @class */ (function () {
  88838. function FramingBehavior() {
  88839. this._mode = FramingBehavior.FitFrustumSidesMode;
  88840. this._radiusScale = 1.0;
  88841. this._positionScale = 0.5;
  88842. this._defaultElevation = 0.3;
  88843. this._elevationReturnTime = 1500;
  88844. this._elevationReturnWaitTime = 1000;
  88845. this._zoomStopsAnimation = false;
  88846. this._framingTime = 1500;
  88847. this._isPointerDown = false;
  88848. this._lastInteractionTime = -Infinity;
  88849. // Framing control
  88850. this._animatables = new Array();
  88851. this._betaIsAnimating = false;
  88852. }
  88853. Object.defineProperty(FramingBehavior.prototype, "name", {
  88854. get: function () {
  88855. return "Framing";
  88856. },
  88857. enumerable: true,
  88858. configurable: true
  88859. });
  88860. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88861. /**
  88862. * Gets current mode used by the behavior.
  88863. */
  88864. get: function () {
  88865. return this._mode;
  88866. },
  88867. /**
  88868. * Sets the current mode used by the behavior
  88869. */
  88870. set: function (mode) {
  88871. this._mode = mode;
  88872. },
  88873. enumerable: true,
  88874. configurable: true
  88875. });
  88876. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88877. /**
  88878. * Gets the scale applied to the radius
  88879. */
  88880. get: function () {
  88881. return this._radiusScale;
  88882. },
  88883. /**
  88884. * Sets the scale applied to the radius (1 by default)
  88885. */
  88886. set: function (radius) {
  88887. this._radiusScale = radius;
  88888. },
  88889. enumerable: true,
  88890. configurable: true
  88891. });
  88892. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88893. /**
  88894. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88895. */
  88896. get: function () {
  88897. return this._positionScale;
  88898. },
  88899. /**
  88900. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88901. */
  88902. set: function (scale) {
  88903. this._positionScale = scale;
  88904. },
  88905. enumerable: true,
  88906. configurable: true
  88907. });
  88908. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88909. /**
  88910. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88911. * behaviour is triggered, in radians.
  88912. */
  88913. get: function () {
  88914. return this._defaultElevation;
  88915. },
  88916. /**
  88917. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88918. * behaviour is triggered, in radians.
  88919. */
  88920. set: function (elevation) {
  88921. this._defaultElevation = elevation;
  88922. },
  88923. enumerable: true,
  88924. configurable: true
  88925. });
  88926. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88927. /**
  88928. * Gets the time (in milliseconds) taken to return to the default beta position.
  88929. * Negative value indicates camera should not return to default.
  88930. */
  88931. get: function () {
  88932. return this._elevationReturnTime;
  88933. },
  88934. /**
  88935. * Sets the time (in milliseconds) taken to return to the default beta position.
  88936. * Negative value indicates camera should not return to default.
  88937. */
  88938. set: function (speed) {
  88939. this._elevationReturnTime = speed;
  88940. },
  88941. enumerable: true,
  88942. configurable: true
  88943. });
  88944. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88945. /**
  88946. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88947. */
  88948. get: function () {
  88949. return this._elevationReturnWaitTime;
  88950. },
  88951. /**
  88952. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88953. */
  88954. set: function (time) {
  88955. this._elevationReturnWaitTime = time;
  88956. },
  88957. enumerable: true,
  88958. configurable: true
  88959. });
  88960. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88961. /**
  88962. * Gets the flag that indicates if user zooming should stop animation.
  88963. */
  88964. get: function () {
  88965. return this._zoomStopsAnimation;
  88966. },
  88967. /**
  88968. * Sets the flag that indicates if user zooming should stop animation.
  88969. */
  88970. set: function (flag) {
  88971. this._zoomStopsAnimation = flag;
  88972. },
  88973. enumerable: true,
  88974. configurable: true
  88975. });
  88976. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88977. /**
  88978. * Gets the transition time when framing the mesh, in milliseconds
  88979. */
  88980. get: function () {
  88981. return this._framingTime;
  88982. },
  88983. /**
  88984. * Sets the transition time when framing the mesh, in milliseconds
  88985. */
  88986. set: function (time) {
  88987. this._framingTime = time;
  88988. },
  88989. enumerable: true,
  88990. configurable: true
  88991. });
  88992. FramingBehavior.prototype.init = function () {
  88993. // Do notihng
  88994. };
  88995. FramingBehavior.prototype.attach = function (camera) {
  88996. var _this = this;
  88997. this._attachedCamera = camera;
  88998. var scene = this._attachedCamera.getScene();
  88999. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89000. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89001. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89002. _this._isPointerDown = true;
  89003. return;
  89004. }
  89005. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89006. _this._isPointerDown = false;
  89007. }
  89008. });
  89009. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89010. if (mesh) {
  89011. _this.zoomOnMesh(mesh);
  89012. }
  89013. });
  89014. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89015. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89016. _this._applyUserInteraction();
  89017. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89018. // back to the default position after a given timeout
  89019. _this._maintainCameraAboveGround();
  89020. });
  89021. };
  89022. FramingBehavior.prototype.detach = function () {
  89023. if (!this._attachedCamera) {
  89024. return;
  89025. }
  89026. var scene = this._attachedCamera.getScene();
  89027. if (this._onPrePointerObservableObserver) {
  89028. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89029. }
  89030. if (this._onAfterCheckInputsObserver) {
  89031. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89032. }
  89033. if (this._onMeshTargetChangedObserver) {
  89034. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89035. }
  89036. this._attachedCamera = null;
  89037. };
  89038. /**
  89039. * Targets the given mesh and updates zoom level accordingly.
  89040. * @param mesh The mesh to target.
  89041. * @param radius Optional. If a cached radius position already exists, overrides default.
  89042. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89043. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89044. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89045. */
  89046. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89047. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89048. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89049. mesh.computeWorldMatrix(true);
  89050. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89051. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89052. };
  89053. /**
  89054. * Targets the given mesh with its children and updates zoom level accordingly.
  89055. * @param mesh The mesh to target.
  89056. * @param radius Optional. If a cached radius position already exists, overrides default.
  89057. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89058. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89059. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89060. */
  89061. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89062. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89063. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89064. mesh.computeWorldMatrix(true);
  89065. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89066. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89067. };
  89068. /**
  89069. * Targets the given meshes with their children and updates zoom level accordingly.
  89070. * @param meshes The mesh to target.
  89071. * @param radius Optional. If a cached radius position already exists, overrides default.
  89072. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89073. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89074. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89075. */
  89076. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89077. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89078. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89079. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89080. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89081. for (var i = 0; i < meshes.length; i++) {
  89082. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89083. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89084. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89085. }
  89086. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89087. };
  89088. /**
  89089. * Targets the given mesh and updates zoom level accordingly.
  89090. * @param mesh The mesh to target.
  89091. * @param radius Optional. If a cached radius position already exists, overrides default.
  89092. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89093. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89094. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89095. */
  89096. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89097. var _this = this;
  89098. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89099. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89100. var zoomTarget;
  89101. if (!this._attachedCamera) {
  89102. return;
  89103. }
  89104. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89105. var bottom = minimumWorld.y;
  89106. var top = maximumWorld.y;
  89107. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89108. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89109. if (focusOnOriginXZ) {
  89110. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89111. }
  89112. else {
  89113. var centerWorld = minimumWorld.add(radiusWorld);
  89114. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89115. }
  89116. if (!this._vectorTransition) {
  89117. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89118. }
  89119. this._betaIsAnimating = true;
  89120. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89121. if (animatable) {
  89122. this._animatables.push(animatable);
  89123. }
  89124. // sets the radius and lower radius bounds
  89125. // Small delta ensures camera is not always at lower zoom limit.
  89126. var radius = 0;
  89127. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89128. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89129. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89130. radius = position;
  89131. }
  89132. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89133. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89134. if (this._attachedCamera.lowerRadiusLimit === null) {
  89135. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89136. }
  89137. }
  89138. // Set sensibilities
  89139. var extend = maximumWorld.subtract(minimumWorld).length();
  89140. this._attachedCamera.panningSensibility = 5000 / extend;
  89141. this._attachedCamera.wheelPrecision = 100 / radius;
  89142. // transition to new radius
  89143. if (!this._radiusTransition) {
  89144. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89145. }
  89146. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89147. _this.stopAllAnimations();
  89148. if (onAnimationEnd) {
  89149. onAnimationEnd();
  89150. }
  89151. if (_this._attachedCamera) {
  89152. _this._attachedCamera.storeState();
  89153. }
  89154. });
  89155. if (animatable) {
  89156. this._animatables.push(animatable);
  89157. }
  89158. };
  89159. /**
  89160. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89161. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89162. * frustum width.
  89163. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89164. * to fully enclose the mesh in the viewing frustum.
  89165. */
  89166. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89167. var size = maximumWorld.subtract(minimumWorld);
  89168. var boxVectorGlobalDiagonal = size.length();
  89169. var frustumSlope = this._getFrustumSlope();
  89170. // Formula for setting distance
  89171. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89172. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89173. // Horizon distance
  89174. var radius = radiusWithoutFraming * this._radiusScale;
  89175. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89176. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89177. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89178. var camera = this._attachedCamera;
  89179. if (!camera) {
  89180. return 0;
  89181. }
  89182. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89183. // Don't exceed the requested limit
  89184. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89185. }
  89186. // Don't exceed the upper radius limit
  89187. if (camera.upperRadiusLimit) {
  89188. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89189. }
  89190. return distance;
  89191. };
  89192. /**
  89193. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89194. * is automatically returned to its default position (expected to be above ground plane).
  89195. */
  89196. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89197. var _this = this;
  89198. if (this._elevationReturnTime < 0) {
  89199. return;
  89200. }
  89201. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89202. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89203. var limitBeta = Math.PI * 0.5;
  89204. // Bring the camera back up if below the ground plane
  89205. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89206. this._betaIsAnimating = true;
  89207. //Transition to new position
  89208. this.stopAllAnimations();
  89209. if (!this._betaTransition) {
  89210. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89211. }
  89212. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89213. _this._clearAnimationLocks();
  89214. _this.stopAllAnimations();
  89215. });
  89216. if (animatabe) {
  89217. this._animatables.push(animatabe);
  89218. }
  89219. }
  89220. };
  89221. /**
  89222. * Returns the frustum slope based on the canvas ratio and camera FOV
  89223. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89224. */
  89225. FramingBehavior.prototype._getFrustumSlope = function () {
  89226. // Calculate the viewport ratio
  89227. // Aspect Ratio is Height/Width.
  89228. var camera = this._attachedCamera;
  89229. if (!camera) {
  89230. return BABYLON.Vector2.Zero();
  89231. }
  89232. var engine = camera.getScene().getEngine();
  89233. var aspectRatio = engine.getAspectRatio(camera);
  89234. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89235. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89236. var frustumSlopeY = Math.tan(camera.fov / 2);
  89237. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89238. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89239. // along the forward vector.
  89240. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89241. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89242. };
  89243. /**
  89244. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89245. */
  89246. FramingBehavior.prototype._clearAnimationLocks = function () {
  89247. this._betaIsAnimating = false;
  89248. };
  89249. /**
  89250. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89251. */
  89252. FramingBehavior.prototype._applyUserInteraction = function () {
  89253. if (this.isUserIsMoving) {
  89254. this._lastInteractionTime = BABYLON.Tools.Now;
  89255. this.stopAllAnimations();
  89256. this._clearAnimationLocks();
  89257. }
  89258. };
  89259. /**
  89260. * Stops and removes all animations that have been applied to the camera
  89261. */
  89262. FramingBehavior.prototype.stopAllAnimations = function () {
  89263. if (this._attachedCamera) {
  89264. this._attachedCamera.animations = [];
  89265. }
  89266. while (this._animatables.length) {
  89267. if (this._animatables[0]) {
  89268. this._animatables[0].onAnimationEnd = null;
  89269. this._animatables[0].stop();
  89270. }
  89271. this._animatables.shift();
  89272. }
  89273. };
  89274. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89275. /**
  89276. * Gets a value indicating if the user is moving the camera
  89277. */
  89278. get: function () {
  89279. if (!this._attachedCamera) {
  89280. return false;
  89281. }
  89282. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89283. this._attachedCamera.inertialBetaOffset !== 0 ||
  89284. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89285. this._attachedCamera.inertialPanningX !== 0 ||
  89286. this._attachedCamera.inertialPanningY !== 0 ||
  89287. this._isPointerDown;
  89288. },
  89289. enumerable: true,
  89290. configurable: true
  89291. });
  89292. /**
  89293. * The easing function used by animations
  89294. */
  89295. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89296. /**
  89297. * The easing mode used by animations
  89298. */
  89299. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89300. // Statics
  89301. /**
  89302. * The camera can move all the way towards the mesh.
  89303. */
  89304. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89305. /**
  89306. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89307. */
  89308. FramingBehavior.FitFrustumSidesMode = 1;
  89309. return FramingBehavior;
  89310. }());
  89311. BABYLON.FramingBehavior = FramingBehavior;
  89312. })(BABYLON || (BABYLON = {}));
  89313. //# sourceMappingURL=babylon.framingBehavior.js.map
  89314. "use strict";
  89315. var BABYLON;
  89316. (function (BABYLON) {
  89317. /**
  89318. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89319. */
  89320. var BouncingBehavior = /** @class */ (function () {
  89321. function BouncingBehavior() {
  89322. /**
  89323. * The duration of the animation, in milliseconds
  89324. */
  89325. this.transitionDuration = 450;
  89326. /**
  89327. * Length of the distance animated by the transition when lower radius is reached
  89328. */
  89329. this.lowerRadiusTransitionRange = 2;
  89330. /**
  89331. * Length of the distance animated by the transition when upper radius is reached
  89332. */
  89333. this.upperRadiusTransitionRange = -2;
  89334. this._autoTransitionRange = false;
  89335. // Animations
  89336. this._radiusIsAnimating = false;
  89337. this._radiusBounceTransition = null;
  89338. this._animatables = new Array();
  89339. }
  89340. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89341. get: function () {
  89342. return "Bouncing";
  89343. },
  89344. enumerable: true,
  89345. configurable: true
  89346. });
  89347. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89348. /**
  89349. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89350. */
  89351. get: function () {
  89352. return this._autoTransitionRange;
  89353. },
  89354. /**
  89355. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89356. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89357. */
  89358. set: function (value) {
  89359. var _this = this;
  89360. if (this._autoTransitionRange === value) {
  89361. return;
  89362. }
  89363. this._autoTransitionRange = value;
  89364. var camera = this._attachedCamera;
  89365. if (!camera) {
  89366. return;
  89367. }
  89368. if (value) {
  89369. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89370. if (!mesh) {
  89371. return;
  89372. }
  89373. mesh.computeWorldMatrix(true);
  89374. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89375. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89376. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89377. });
  89378. }
  89379. else if (this._onMeshTargetChangedObserver) {
  89380. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89381. }
  89382. },
  89383. enumerable: true,
  89384. configurable: true
  89385. });
  89386. BouncingBehavior.prototype.init = function () {
  89387. // Do notihng
  89388. };
  89389. BouncingBehavior.prototype.attach = function (camera) {
  89390. var _this = this;
  89391. this._attachedCamera = camera;
  89392. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89393. if (!_this._attachedCamera) {
  89394. return;
  89395. }
  89396. // Add the bounce animation to the lower radius limit
  89397. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89398. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89399. }
  89400. // Add the bounce animation to the upper radius limit
  89401. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89402. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89403. }
  89404. });
  89405. };
  89406. BouncingBehavior.prototype.detach = function () {
  89407. if (!this._attachedCamera) {
  89408. return;
  89409. }
  89410. if (this._onAfterCheckInputsObserver) {
  89411. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89412. }
  89413. if (this._onMeshTargetChangedObserver) {
  89414. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89415. }
  89416. this._attachedCamera = null;
  89417. };
  89418. /**
  89419. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89420. * @param radiusLimit The limit to check against.
  89421. * @return Bool to indicate if at limit.
  89422. */
  89423. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89424. if (!this._attachedCamera) {
  89425. return false;
  89426. }
  89427. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89428. return true;
  89429. }
  89430. return false;
  89431. };
  89432. /**
  89433. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89434. * @param radiusDelta The delta by which to animate to. Can be negative.
  89435. */
  89436. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89437. var _this = this;
  89438. if (!this._attachedCamera) {
  89439. return;
  89440. }
  89441. if (!this._radiusBounceTransition) {
  89442. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89443. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89444. }
  89445. // Prevent zoom until bounce has completed
  89446. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89447. this._attachedCamera.wheelPrecision = Infinity;
  89448. this._attachedCamera.inertialRadiusOffset = 0;
  89449. // Animate to the radius limit
  89450. this.stopAllAnimations();
  89451. this._radiusIsAnimating = true;
  89452. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89453. if (animatable) {
  89454. this._animatables.push(animatable);
  89455. }
  89456. };
  89457. /**
  89458. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89459. */
  89460. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89461. this._radiusIsAnimating = false;
  89462. if (this._attachedCamera) {
  89463. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89464. }
  89465. };
  89466. /**
  89467. * Stops and removes all animations that have been applied to the camera
  89468. */
  89469. BouncingBehavior.prototype.stopAllAnimations = function () {
  89470. if (this._attachedCamera) {
  89471. this._attachedCamera.animations = [];
  89472. }
  89473. while (this._animatables.length) {
  89474. this._animatables[0].onAnimationEnd = null;
  89475. this._animatables[0].stop();
  89476. this._animatables.shift();
  89477. }
  89478. };
  89479. /**
  89480. * The easing function used by animations
  89481. */
  89482. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89483. /**
  89484. * The easing mode used by animations
  89485. */
  89486. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89487. return BouncingBehavior;
  89488. }());
  89489. BABYLON.BouncingBehavior = BouncingBehavior;
  89490. })(BABYLON || (BABYLON = {}));
  89491. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89492. "use strict";
  89493. var BABYLON;
  89494. (function (BABYLON) {
  89495. var AutoRotationBehavior = /** @class */ (function () {
  89496. function AutoRotationBehavior() {
  89497. this._zoomStopsAnimation = false;
  89498. this._idleRotationSpeed = 0.05;
  89499. this._idleRotationWaitTime = 2000;
  89500. this._idleRotationSpinupTime = 2000;
  89501. this._isPointerDown = false;
  89502. this._lastFrameTime = null;
  89503. this._lastInteractionTime = -Infinity;
  89504. this._cameraRotationSpeed = 0;
  89505. this._lastFrameRadius = 0;
  89506. }
  89507. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89508. get: function () {
  89509. return "AutoRotation";
  89510. },
  89511. enumerable: true,
  89512. configurable: true
  89513. });
  89514. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89515. /**
  89516. * Gets the flag that indicates if user zooming should stop animation.
  89517. */
  89518. get: function () {
  89519. return this._zoomStopsAnimation;
  89520. },
  89521. /**
  89522. * Sets the flag that indicates if user zooming should stop animation.
  89523. */
  89524. set: function (flag) {
  89525. this._zoomStopsAnimation = flag;
  89526. },
  89527. enumerable: true,
  89528. configurable: true
  89529. });
  89530. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89531. /**
  89532. * Gets the default speed at which the camera rotates around the model.
  89533. */
  89534. get: function () {
  89535. return this._idleRotationSpeed;
  89536. },
  89537. /**
  89538. * Sets the default speed at which the camera rotates around the model.
  89539. */
  89540. set: function (speed) {
  89541. this._idleRotationSpeed = speed;
  89542. },
  89543. enumerable: true,
  89544. configurable: true
  89545. });
  89546. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89547. /**
  89548. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89549. */
  89550. get: function () {
  89551. return this._idleRotationWaitTime;
  89552. },
  89553. /**
  89554. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89555. */
  89556. set: function (time) {
  89557. this._idleRotationWaitTime = time;
  89558. },
  89559. enumerable: true,
  89560. configurable: true
  89561. });
  89562. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89563. /**
  89564. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89565. */
  89566. get: function () {
  89567. return this._idleRotationSpinupTime;
  89568. },
  89569. /**
  89570. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89571. */
  89572. set: function (time) {
  89573. this._idleRotationSpinupTime = time;
  89574. },
  89575. enumerable: true,
  89576. configurable: true
  89577. });
  89578. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89579. /**
  89580. * Gets a value indicating if the camera is currently rotating because of this behavior
  89581. */
  89582. get: function () {
  89583. return Math.abs(this._cameraRotationSpeed) > 0;
  89584. },
  89585. enumerable: true,
  89586. configurable: true
  89587. });
  89588. AutoRotationBehavior.prototype.init = function () {
  89589. // Do notihng
  89590. };
  89591. AutoRotationBehavior.prototype.attach = function (camera) {
  89592. var _this = this;
  89593. this._attachedCamera = camera;
  89594. var scene = this._attachedCamera.getScene();
  89595. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89596. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89597. _this._isPointerDown = true;
  89598. return;
  89599. }
  89600. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89601. _this._isPointerDown = false;
  89602. }
  89603. });
  89604. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89605. var now = BABYLON.Tools.Now;
  89606. var dt = 0;
  89607. if (_this._lastFrameTime != null) {
  89608. dt = now - _this._lastFrameTime;
  89609. }
  89610. _this._lastFrameTime = now;
  89611. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89612. _this._applyUserInteraction();
  89613. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89614. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89615. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89616. // Step camera rotation by rotation speed
  89617. if (_this._attachedCamera) {
  89618. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89619. }
  89620. });
  89621. };
  89622. AutoRotationBehavior.prototype.detach = function () {
  89623. if (!this._attachedCamera) {
  89624. return;
  89625. }
  89626. var scene = this._attachedCamera.getScene();
  89627. if (this._onPrePointerObservableObserver) {
  89628. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89629. }
  89630. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89631. this._attachedCamera = null;
  89632. };
  89633. /**
  89634. * Returns true if user is scrolling.
  89635. * @return true if user is scrolling.
  89636. */
  89637. AutoRotationBehavior.prototype._userIsZooming = function () {
  89638. if (!this._attachedCamera) {
  89639. return false;
  89640. }
  89641. return this._attachedCamera.inertialRadiusOffset !== 0;
  89642. };
  89643. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89644. if (!this._attachedCamera) {
  89645. return false;
  89646. }
  89647. var zoomHasHitLimit = false;
  89648. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89649. zoomHasHitLimit = true;
  89650. }
  89651. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89652. this._lastFrameRadius = this._attachedCamera.radius;
  89653. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  89654. };
  89655. /**
  89656. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89657. */
  89658. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  89659. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  89660. this._lastInteractionTime = BABYLON.Tools.Now;
  89661. }
  89662. };
  89663. // Tools
  89664. AutoRotationBehavior.prototype._userIsMoving = function () {
  89665. if (!this._attachedCamera) {
  89666. return false;
  89667. }
  89668. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89669. this._attachedCamera.inertialBetaOffset !== 0 ||
  89670. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89671. this._attachedCamera.inertialPanningX !== 0 ||
  89672. this._attachedCamera.inertialPanningY !== 0 ||
  89673. this._isPointerDown;
  89674. };
  89675. return AutoRotationBehavior;
  89676. }());
  89677. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89678. })(BABYLON || (BABYLON = {}));
  89679. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89680. "use strict";
  89681. var BABYLON;
  89682. (function (BABYLON) {
  89683. var NullEngineOptions = /** @class */ (function () {
  89684. function NullEngineOptions() {
  89685. this.renderWidth = 512;
  89686. this.renderHeight = 256;
  89687. this.textureSize = 512;
  89688. this.deterministicLockstep = false;
  89689. this.lockstepMaxSteps = 4;
  89690. }
  89691. return NullEngineOptions;
  89692. }());
  89693. BABYLON.NullEngineOptions = NullEngineOptions;
  89694. /**
  89695. * The null engine class provides support for headless version of babylon.js.
  89696. * This can be used in server side scenario or for testing purposes
  89697. */
  89698. var NullEngine = /** @class */ (function (_super) {
  89699. __extends(NullEngine, _super);
  89700. function NullEngine(options) {
  89701. if (options === void 0) { options = new NullEngineOptions(); }
  89702. var _this = _super.call(this, null) || this;
  89703. if (options.deterministicLockstep === undefined) {
  89704. options.deterministicLockstep = false;
  89705. }
  89706. if (options.lockstepMaxSteps === undefined) {
  89707. options.lockstepMaxSteps = 4;
  89708. }
  89709. _this._options = options;
  89710. // Init caps
  89711. // We consider we are on a webgl1 capable device
  89712. _this._caps = new BABYLON.EngineCapabilities();
  89713. _this._caps.maxTexturesImageUnits = 16;
  89714. _this._caps.maxVertexTextureImageUnits = 16;
  89715. _this._caps.maxTextureSize = 512;
  89716. _this._caps.maxCubemapTextureSize = 512;
  89717. _this._caps.maxRenderTextureSize = 512;
  89718. _this._caps.maxVertexAttribs = 16;
  89719. _this._caps.maxVaryingVectors = 16;
  89720. _this._caps.maxFragmentUniformVectors = 16;
  89721. _this._caps.maxVertexUniformVectors = 16;
  89722. // Extensions
  89723. _this._caps.standardDerivatives = false;
  89724. _this._caps.astc = null;
  89725. _this._caps.s3tc = null;
  89726. _this._caps.pvrtc = null;
  89727. _this._caps.etc1 = null;
  89728. _this._caps.etc2 = null;
  89729. _this._caps.textureAnisotropicFilterExtension = null;
  89730. _this._caps.maxAnisotropy = 0;
  89731. _this._caps.uintIndices = false;
  89732. _this._caps.fragmentDepthSupported = false;
  89733. _this._caps.highPrecisionShaderSupported = true;
  89734. _this._caps.colorBufferFloat = false;
  89735. _this._caps.textureFloat = false;
  89736. _this._caps.textureFloatLinearFiltering = false;
  89737. _this._caps.textureFloatRender = false;
  89738. _this._caps.textureHalfFloat = false;
  89739. _this._caps.textureHalfFloatLinearFiltering = false;
  89740. _this._caps.textureHalfFloatRender = false;
  89741. _this._caps.textureLOD = false;
  89742. _this._caps.drawBuffersExtension = false;
  89743. _this._caps.depthTextureExtension = false;
  89744. _this._caps.vertexArrayObject = false;
  89745. _this._caps.instancedArrays = false;
  89746. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  89747. // Wrappers
  89748. if (typeof URL === "undefined") {
  89749. URL = {
  89750. createObjectURL: function () { },
  89751. revokeObjectURL: function () { }
  89752. };
  89753. }
  89754. if (typeof Blob === "undefined") {
  89755. Blob = function () { };
  89756. }
  89757. return _this;
  89758. }
  89759. NullEngine.prototype.isDeterministicLockStep = function () {
  89760. return this._options.deterministicLockstep;
  89761. };
  89762. NullEngine.prototype.getLockstepMaxSteps = function () {
  89763. return this._options.lockstepMaxSteps;
  89764. };
  89765. NullEngine.prototype.getHardwareScalingLevel = function () {
  89766. return 1.0;
  89767. };
  89768. NullEngine.prototype.createVertexBuffer = function (vertices) {
  89769. return {
  89770. capacity: 0,
  89771. references: 1,
  89772. is32Bits: false
  89773. };
  89774. };
  89775. NullEngine.prototype.createIndexBuffer = function (indices) {
  89776. return {
  89777. capacity: 0,
  89778. references: 1,
  89779. is32Bits: false
  89780. };
  89781. };
  89782. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  89783. if (stencil === void 0) { stencil = false; }
  89784. };
  89785. NullEngine.prototype.getRenderWidth = function (useScreen) {
  89786. if (useScreen === void 0) { useScreen = false; }
  89787. if (!useScreen && this._currentRenderTarget) {
  89788. return this._currentRenderTarget.width;
  89789. }
  89790. return this._options.renderWidth;
  89791. };
  89792. NullEngine.prototype.getRenderHeight = function (useScreen) {
  89793. if (useScreen === void 0) { useScreen = false; }
  89794. if (!useScreen && this._currentRenderTarget) {
  89795. return this._currentRenderTarget.height;
  89796. }
  89797. return this._options.renderHeight;
  89798. };
  89799. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  89800. this._cachedViewport = viewport;
  89801. };
  89802. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  89803. return {
  89804. transformFeedback: null,
  89805. __SPECTOR_rebuildProgram: null
  89806. };
  89807. };
  89808. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  89809. return [];
  89810. };
  89811. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  89812. return [];
  89813. };
  89814. NullEngine.prototype.bindSamplers = function (effect) {
  89815. this._currentEffect = null;
  89816. };
  89817. NullEngine.prototype.enableEffect = function (effect) {
  89818. this._currentEffect = effect;
  89819. if (effect.onBind) {
  89820. effect.onBind(effect);
  89821. }
  89822. effect.onBindObservable.notifyObservers(effect);
  89823. };
  89824. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  89825. if (zOffset === void 0) { zOffset = 0; }
  89826. if (reverseSide === void 0) { reverseSide = false; }
  89827. };
  89828. NullEngine.prototype.setIntArray = function (uniform, array) {
  89829. };
  89830. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  89831. };
  89832. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  89833. };
  89834. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  89835. };
  89836. NullEngine.prototype.setFloatArray = function (uniform, array) {
  89837. };
  89838. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  89839. };
  89840. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  89841. };
  89842. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  89843. };
  89844. NullEngine.prototype.setArray = function (uniform, array) {
  89845. };
  89846. NullEngine.prototype.setArray2 = function (uniform, array) {
  89847. };
  89848. NullEngine.prototype.setArray3 = function (uniform, array) {
  89849. };
  89850. NullEngine.prototype.setArray4 = function (uniform, array) {
  89851. };
  89852. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  89853. };
  89854. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  89855. };
  89856. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  89857. };
  89858. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  89859. };
  89860. NullEngine.prototype.setFloat = function (uniform, value) {
  89861. };
  89862. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  89863. };
  89864. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  89865. };
  89866. NullEngine.prototype.setBool = function (uniform, bool) {
  89867. };
  89868. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  89869. };
  89870. NullEngine.prototype.setColor3 = function (uniform, color3) {
  89871. };
  89872. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  89873. };
  89874. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  89875. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  89876. if (this._alphaMode === mode) {
  89877. return;
  89878. }
  89879. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  89880. if (!noDepthWriteChange) {
  89881. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  89882. }
  89883. this._alphaMode = mode;
  89884. };
  89885. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  89886. };
  89887. NullEngine.prototype.wipeCaches = function (bruteForce) {
  89888. if (this.preventCacheWipeBetweenFrames) {
  89889. return;
  89890. }
  89891. this.resetTextureCache();
  89892. this._currentEffect = null;
  89893. if (bruteForce) {
  89894. this._currentProgram = null;
  89895. this._stencilState.reset();
  89896. this._depthCullingState.reset();
  89897. this._alphaState.reset();
  89898. }
  89899. this._cachedVertexBuffers = null;
  89900. this._cachedIndexBuffer = null;
  89901. this._cachedEffectForVertexBuffers = null;
  89902. };
  89903. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  89904. };
  89905. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  89906. };
  89907. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  89908. };
  89909. NullEngine.prototype._createTexture = function () {
  89910. return {};
  89911. };
  89912. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  89913. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  89914. if (onLoad === void 0) { onLoad = null; }
  89915. if (onError === void 0) { onError = null; }
  89916. if (buffer === void 0) { buffer = null; }
  89917. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  89918. var url = String(urlArg);
  89919. texture.url = url;
  89920. texture.generateMipMaps = !noMipmap;
  89921. texture.samplingMode = samplingMode;
  89922. texture.invertY = invertY;
  89923. texture.baseWidth = this._options.textureSize;
  89924. texture.baseHeight = this._options.textureSize;
  89925. texture.width = this._options.textureSize;
  89926. texture.height = this._options.textureSize;
  89927. if (format) {
  89928. texture.format = format;
  89929. }
  89930. texture.isReady = true;
  89931. if (onLoad) {
  89932. onLoad();
  89933. }
  89934. return texture;
  89935. };
  89936. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  89937. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  89938. if (options !== undefined && typeof options === "object") {
  89939. fullOptions.generateMipMaps = options.generateMipMaps;
  89940. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  89941. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  89942. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  89943. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  89944. }
  89945. else {
  89946. fullOptions.generateMipMaps = options;
  89947. fullOptions.generateDepthBuffer = true;
  89948. fullOptions.generateStencilBuffer = false;
  89949. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89950. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  89951. }
  89952. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  89953. var width = size.width || size;
  89954. var height = size.height || size;
  89955. texture._depthStencilBuffer = {};
  89956. texture._framebuffer = {};
  89957. texture.baseWidth = width;
  89958. texture.baseHeight = height;
  89959. texture.width = width;
  89960. texture.height = height;
  89961. texture.isReady = true;
  89962. texture.samples = 1;
  89963. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  89964. texture.samplingMode = fullOptions.samplingMode;
  89965. texture.type = fullOptions.type;
  89966. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  89967. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  89968. return texture;
  89969. };
  89970. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  89971. texture.samplingMode = samplingMode;
  89972. };
  89973. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  89974. if (this._currentRenderTarget) {
  89975. this.unBindFramebuffer(this._currentRenderTarget);
  89976. }
  89977. this._currentRenderTarget = texture;
  89978. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  89979. if (this._cachedViewport && !forceFullscreenViewport) {
  89980. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  89981. }
  89982. };
  89983. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  89984. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  89985. this._currentRenderTarget = null;
  89986. if (onBeforeUnbind) {
  89987. if (texture._MSAAFramebuffer) {
  89988. this._currentFramebuffer = texture._framebuffer;
  89989. }
  89990. onBeforeUnbind();
  89991. }
  89992. this._currentFramebuffer = null;
  89993. };
  89994. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  89995. var vbo = {
  89996. capacity: 1,
  89997. references: 1,
  89998. is32Bits: false
  89999. };
  90000. return vbo;
  90001. };
  90002. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90003. if (offset === void 0) { offset = 0; }
  90004. };
  90005. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  90006. };
  90007. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90008. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90009. this._boundTexturesCache[this._activeChannel] = texture;
  90010. }
  90011. };
  90012. NullEngine.prototype._bindTexture = function (channel, texture) {
  90013. if (channel < 0) {
  90014. return;
  90015. }
  90016. this._bindTextureDirectly(0, texture);
  90017. };
  90018. NullEngine.prototype._releaseBuffer = function (buffer) {
  90019. buffer.references--;
  90020. if (buffer.references === 0) {
  90021. return true;
  90022. }
  90023. return false;
  90024. };
  90025. return NullEngine;
  90026. }(BABYLON.Engine));
  90027. BABYLON.NullEngine = NullEngine;
  90028. })(BABYLON || (BABYLON = {}));
  90029. //# sourceMappingURL=babylon.nullEngine.js.map
  90030. "use strict";
  90031. var BABYLON;
  90032. (function (BABYLON) {
  90033. /**
  90034. * This class can be used to get instrumentation data from a Babylon engine
  90035. */
  90036. var EngineInstrumentation = /** @class */ (function () {
  90037. function EngineInstrumentation(engine) {
  90038. this.engine = engine;
  90039. this._captureGPUFrameTime = false;
  90040. this._gpuFrameTime = new BABYLON.PerfCounter();
  90041. this._captureShaderCompilationTime = false;
  90042. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90043. // Observers
  90044. this._onBeginFrameObserver = null;
  90045. this._onEndFrameObserver = null;
  90046. this._onBeforeShaderCompilationObserver = null;
  90047. this._onAfterShaderCompilationObserver = null;
  90048. }
  90049. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90050. // Properties
  90051. /**
  90052. * Gets the perf counter used for GPU frame time
  90053. */
  90054. get: function () {
  90055. return this._gpuFrameTime;
  90056. },
  90057. enumerable: true,
  90058. configurable: true
  90059. });
  90060. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90061. /**
  90062. * Gets the GPU frame time capture status
  90063. */
  90064. get: function () {
  90065. return this._captureGPUFrameTime;
  90066. },
  90067. /**
  90068. * Enable or disable the GPU frame time capture
  90069. */
  90070. set: function (value) {
  90071. var _this = this;
  90072. if (value === this._captureGPUFrameTime) {
  90073. return;
  90074. }
  90075. this._captureGPUFrameTime = value;
  90076. if (value) {
  90077. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90078. if (!_this._gpuFrameTimeToken) {
  90079. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90080. }
  90081. });
  90082. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90083. if (!_this._gpuFrameTimeToken) {
  90084. return;
  90085. }
  90086. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90087. if (time > -1) {
  90088. _this._gpuFrameTimeToken = null;
  90089. _this._gpuFrameTime.fetchNewFrame();
  90090. _this._gpuFrameTime.addCount(time, true);
  90091. }
  90092. });
  90093. }
  90094. else {
  90095. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90096. this._onBeginFrameObserver = null;
  90097. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90098. this._onEndFrameObserver = null;
  90099. }
  90100. },
  90101. enumerable: true,
  90102. configurable: true
  90103. });
  90104. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90105. /**
  90106. * Gets the perf counter used for shader compilation time
  90107. */
  90108. get: function () {
  90109. return this._shaderCompilationTime;
  90110. },
  90111. enumerable: true,
  90112. configurable: true
  90113. });
  90114. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90115. /**
  90116. * Gets the shader compilation time capture status
  90117. */
  90118. get: function () {
  90119. return this._captureShaderCompilationTime;
  90120. },
  90121. /**
  90122. * Enable or disable the shader compilation time capture
  90123. */
  90124. set: function (value) {
  90125. var _this = this;
  90126. if (value === this._captureShaderCompilationTime) {
  90127. return;
  90128. }
  90129. this._captureShaderCompilationTime = value;
  90130. if (value) {
  90131. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90132. _this._shaderCompilationTime.fetchNewFrame();
  90133. _this._shaderCompilationTime.beginMonitoring();
  90134. });
  90135. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90136. _this._shaderCompilationTime.endMonitoring();
  90137. });
  90138. }
  90139. else {
  90140. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90141. this._onBeforeShaderCompilationObserver = null;
  90142. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90143. this._onAfterShaderCompilationObserver = null;
  90144. }
  90145. },
  90146. enumerable: true,
  90147. configurable: true
  90148. });
  90149. EngineInstrumentation.prototype.dispose = function () {
  90150. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90151. this._onBeginFrameObserver = null;
  90152. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90153. this._onEndFrameObserver = null;
  90154. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90155. this._onBeforeShaderCompilationObserver = null;
  90156. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90157. this._onAfterShaderCompilationObserver = null;
  90158. this.engine = null;
  90159. };
  90160. return EngineInstrumentation;
  90161. }());
  90162. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90163. })(BABYLON || (BABYLON = {}));
  90164. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90165. "use strict";
  90166. var BABYLON;
  90167. (function (BABYLON) {
  90168. /**
  90169. * This class can be used to get instrumentation data from a Babylon engine
  90170. */
  90171. var SceneInstrumentation = /** @class */ (function () {
  90172. function SceneInstrumentation(scene) {
  90173. var _this = this;
  90174. this.scene = scene;
  90175. this._captureActiveMeshesEvaluationTime = false;
  90176. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90177. this._captureRenderTargetsRenderTime = false;
  90178. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90179. this._captureFrameTime = false;
  90180. this._frameTime = new BABYLON.PerfCounter();
  90181. this._captureRenderTime = false;
  90182. this._renderTime = new BABYLON.PerfCounter();
  90183. this._captureInterFrameTime = false;
  90184. this._interFrameTime = new BABYLON.PerfCounter();
  90185. this._captureParticlesRenderTime = false;
  90186. this._particlesRenderTime = new BABYLON.PerfCounter();
  90187. this._captureSpritesRenderTime = false;
  90188. this._spritesRenderTime = new BABYLON.PerfCounter();
  90189. this._capturePhysicsTime = false;
  90190. this._physicsTime = new BABYLON.PerfCounter();
  90191. this._captureAnimationsTime = false;
  90192. this._animationsTime = new BABYLON.PerfCounter();
  90193. // Observers
  90194. this._onBeforeActiveMeshesEvaluationObserver = null;
  90195. this._onAfterActiveMeshesEvaluationObserver = null;
  90196. this._onBeforeRenderTargetsRenderObserver = null;
  90197. this._onAfterRenderTargetsRenderObserver = null;
  90198. this._onAfterRenderObserver = null;
  90199. this._onBeforeDrawPhaseObserver = null;
  90200. this._onAfterDrawPhaseObserver = null;
  90201. this._onBeforeAnimationsObserver = null;
  90202. this._onBeforeParticlesRenderingObserver = null;
  90203. this._onAfterParticlesRenderingObserver = null;
  90204. this._onBeforeSpritesRenderingObserver = null;
  90205. this._onAfterSpritesRenderingObserver = null;
  90206. this._onBeforePhysicsObserver = null;
  90207. this._onAfterPhysicsObserver = null;
  90208. this._onAfterAnimationsObserver = null;
  90209. // Before render
  90210. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90211. if (_this._captureActiveMeshesEvaluationTime) {
  90212. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90213. }
  90214. if (_this._captureRenderTargetsRenderTime) {
  90215. _this._renderTargetsRenderTime.fetchNewFrame();
  90216. }
  90217. if (_this._captureFrameTime) {
  90218. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90219. _this._frameTime.beginMonitoring();
  90220. }
  90221. if (_this._captureInterFrameTime) {
  90222. _this._interFrameTime.endMonitoring();
  90223. }
  90224. if (_this._captureParticlesRenderTime) {
  90225. _this._particlesRenderTime.fetchNewFrame();
  90226. }
  90227. if (_this._captureSpritesRenderTime) {
  90228. _this._spritesRenderTime.fetchNewFrame();
  90229. }
  90230. if (_this._captureAnimationsTime) {
  90231. _this._animationsTime.beginMonitoring();
  90232. }
  90233. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90234. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90235. });
  90236. // After render
  90237. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90238. if (_this._captureFrameTime) {
  90239. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90240. _this._frameTime.endMonitoring();
  90241. }
  90242. if (_this._captureRenderTime) {
  90243. _this._renderTime.endMonitoring(false);
  90244. }
  90245. if (_this._captureInterFrameTime) {
  90246. _this._interFrameTime.beginMonitoring();
  90247. }
  90248. });
  90249. }
  90250. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90251. // Properties
  90252. /**
  90253. * Gets the perf counter used for active meshes evaluation time
  90254. */
  90255. get: function () {
  90256. return this._activeMeshesEvaluationTime;
  90257. },
  90258. enumerable: true,
  90259. configurable: true
  90260. });
  90261. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90262. /**
  90263. * Gets the active meshes evaluation time capture status
  90264. */
  90265. get: function () {
  90266. return this._captureActiveMeshesEvaluationTime;
  90267. },
  90268. /**
  90269. * Enable or disable the active meshes evaluation time capture
  90270. */
  90271. set: function (value) {
  90272. var _this = this;
  90273. if (value === this._captureActiveMeshesEvaluationTime) {
  90274. return;
  90275. }
  90276. this._captureActiveMeshesEvaluationTime = value;
  90277. if (value) {
  90278. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90279. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90280. _this._activeMeshesEvaluationTime.beginMonitoring();
  90281. });
  90282. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90283. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90284. _this._activeMeshesEvaluationTime.endMonitoring();
  90285. });
  90286. }
  90287. else {
  90288. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90289. this._onBeforeActiveMeshesEvaluationObserver = null;
  90290. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90291. this._onAfterActiveMeshesEvaluationObserver = null;
  90292. }
  90293. },
  90294. enumerable: true,
  90295. configurable: true
  90296. });
  90297. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90298. /**
  90299. * Gets the perf counter used for render targets render time
  90300. */
  90301. get: function () {
  90302. return this._renderTargetsRenderTime;
  90303. },
  90304. enumerable: true,
  90305. configurable: true
  90306. });
  90307. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90308. /**
  90309. * Gets the render targets render time capture status
  90310. */
  90311. get: function () {
  90312. return this._captureRenderTargetsRenderTime;
  90313. },
  90314. /**
  90315. * Enable or disable the render targets render time capture
  90316. */
  90317. set: function (value) {
  90318. var _this = this;
  90319. if (value === this._captureRenderTargetsRenderTime) {
  90320. return;
  90321. }
  90322. this._captureRenderTargetsRenderTime = value;
  90323. if (value) {
  90324. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90325. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90326. _this._renderTargetsRenderTime.beginMonitoring();
  90327. });
  90328. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90329. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90330. _this._renderTargetsRenderTime.endMonitoring(false);
  90331. });
  90332. }
  90333. else {
  90334. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90335. this._onBeforeRenderTargetsRenderObserver = null;
  90336. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90337. this._onAfterRenderTargetsRenderObserver = null;
  90338. }
  90339. },
  90340. enumerable: true,
  90341. configurable: true
  90342. });
  90343. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90344. /**
  90345. * Gets the perf counter used for particles render time
  90346. */
  90347. get: function () {
  90348. return this._particlesRenderTime;
  90349. },
  90350. enumerable: true,
  90351. configurable: true
  90352. });
  90353. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90354. /**
  90355. * Gets the particles render time capture status
  90356. */
  90357. get: function () {
  90358. return this._captureParticlesRenderTime;
  90359. },
  90360. /**
  90361. * Enable or disable the particles render time capture
  90362. */
  90363. set: function (value) {
  90364. var _this = this;
  90365. if (value === this._captureParticlesRenderTime) {
  90366. return;
  90367. }
  90368. this._captureParticlesRenderTime = value;
  90369. if (value) {
  90370. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90371. BABYLON.Tools.StartPerformanceCounter("Particles");
  90372. _this._particlesRenderTime.beginMonitoring();
  90373. });
  90374. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90375. BABYLON.Tools.EndPerformanceCounter("Particles");
  90376. _this._particlesRenderTime.endMonitoring(false);
  90377. });
  90378. }
  90379. else {
  90380. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90381. this._onBeforeParticlesRenderingObserver = null;
  90382. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90383. this._onAfterParticlesRenderingObserver = null;
  90384. }
  90385. },
  90386. enumerable: true,
  90387. configurable: true
  90388. });
  90389. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90390. /**
  90391. * Gets the perf counter used for sprites render time
  90392. */
  90393. get: function () {
  90394. return this._spritesRenderTime;
  90395. },
  90396. enumerable: true,
  90397. configurable: true
  90398. });
  90399. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90400. /**
  90401. * Gets the sprites render time capture status
  90402. */
  90403. get: function () {
  90404. return this._captureSpritesRenderTime;
  90405. },
  90406. /**
  90407. * Enable or disable the sprites render time capture
  90408. */
  90409. set: function (value) {
  90410. var _this = this;
  90411. if (value === this._captureSpritesRenderTime) {
  90412. return;
  90413. }
  90414. this._captureSpritesRenderTime = value;
  90415. if (value) {
  90416. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90417. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90418. _this._spritesRenderTime.beginMonitoring();
  90419. });
  90420. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90421. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90422. _this._spritesRenderTime.endMonitoring(false);
  90423. });
  90424. }
  90425. else {
  90426. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90427. this._onBeforeSpritesRenderingObserver = null;
  90428. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90429. this._onAfterSpritesRenderingObserver = null;
  90430. }
  90431. },
  90432. enumerable: true,
  90433. configurable: true
  90434. });
  90435. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90436. /**
  90437. * Gets the perf counter used for physics time
  90438. */
  90439. get: function () {
  90440. return this._physicsTime;
  90441. },
  90442. enumerable: true,
  90443. configurable: true
  90444. });
  90445. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90446. /**
  90447. * Gets the physics time capture status
  90448. */
  90449. get: function () {
  90450. return this._capturePhysicsTime;
  90451. },
  90452. /**
  90453. * Enable or disable the physics time capture
  90454. */
  90455. set: function (value) {
  90456. var _this = this;
  90457. if (value === this._capturePhysicsTime) {
  90458. return;
  90459. }
  90460. this._capturePhysicsTime = value;
  90461. if (value) {
  90462. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90463. BABYLON.Tools.StartPerformanceCounter("Physics");
  90464. _this._physicsTime.beginMonitoring();
  90465. });
  90466. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90467. BABYLON.Tools.EndPerformanceCounter("Physics");
  90468. _this._physicsTime.endMonitoring();
  90469. });
  90470. }
  90471. else {
  90472. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90473. this._onBeforePhysicsObserver = null;
  90474. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90475. this._onAfterPhysicsObserver = null;
  90476. }
  90477. },
  90478. enumerable: true,
  90479. configurable: true
  90480. });
  90481. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90482. /**
  90483. * Gets the perf counter used for animations time
  90484. */
  90485. get: function () {
  90486. return this._animationsTime;
  90487. },
  90488. enumerable: true,
  90489. configurable: true
  90490. });
  90491. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90492. /**
  90493. * Gets the animations time capture status
  90494. */
  90495. get: function () {
  90496. return this._captureAnimationsTime;
  90497. },
  90498. /**
  90499. * Enable or disable the animations time capture
  90500. */
  90501. set: function (value) {
  90502. var _this = this;
  90503. if (value === this._captureAnimationsTime) {
  90504. return;
  90505. }
  90506. this._captureAnimationsTime = value;
  90507. if (value) {
  90508. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90509. _this._animationsTime.endMonitoring();
  90510. });
  90511. }
  90512. else {
  90513. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90514. this._onAfterAnimationsObserver = null;
  90515. }
  90516. },
  90517. enumerable: true,
  90518. configurable: true
  90519. });
  90520. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90521. /**
  90522. * Gets the perf counter used for frame time capture
  90523. */
  90524. get: function () {
  90525. return this._frameTime;
  90526. },
  90527. enumerable: true,
  90528. configurable: true
  90529. });
  90530. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90531. /**
  90532. * Gets the frame time capture status
  90533. */
  90534. get: function () {
  90535. return this._captureFrameTime;
  90536. },
  90537. /**
  90538. * Enable or disable the frame time capture
  90539. */
  90540. set: function (value) {
  90541. this._captureFrameTime = value;
  90542. },
  90543. enumerable: true,
  90544. configurable: true
  90545. });
  90546. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90547. /**
  90548. * Gets the perf counter used for inter-frames time capture
  90549. */
  90550. get: function () {
  90551. return this._interFrameTime;
  90552. },
  90553. enumerable: true,
  90554. configurable: true
  90555. });
  90556. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90557. /**
  90558. * Gets the inter-frames time capture status
  90559. */
  90560. get: function () {
  90561. return this._captureInterFrameTime;
  90562. },
  90563. /**
  90564. * Enable or disable the inter-frames time capture
  90565. */
  90566. set: function (value) {
  90567. this._captureInterFrameTime = value;
  90568. },
  90569. enumerable: true,
  90570. configurable: true
  90571. });
  90572. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90573. /**
  90574. * Gets the perf counter used for render time capture
  90575. */
  90576. get: function () {
  90577. return this._renderTime;
  90578. },
  90579. enumerable: true,
  90580. configurable: true
  90581. });
  90582. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90583. /**
  90584. * Gets the render time capture status
  90585. */
  90586. get: function () {
  90587. return this._captureRenderTime;
  90588. },
  90589. /**
  90590. * Enable or disable the render time capture
  90591. */
  90592. set: function (value) {
  90593. var _this = this;
  90594. if (value === this._captureRenderTime) {
  90595. return;
  90596. }
  90597. this._captureRenderTime = value;
  90598. if (value) {
  90599. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90600. _this._renderTime.beginMonitoring();
  90601. BABYLON.Tools.StartPerformanceCounter("Main render");
  90602. });
  90603. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90604. _this._renderTime.endMonitoring(false);
  90605. BABYLON.Tools.EndPerformanceCounter("Main render");
  90606. });
  90607. }
  90608. else {
  90609. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90610. this._onBeforeDrawPhaseObserver = null;
  90611. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90612. this._onAfterDrawPhaseObserver = null;
  90613. }
  90614. },
  90615. enumerable: true,
  90616. configurable: true
  90617. });
  90618. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90619. /**
  90620. * Gets the perf counter used for draw calls
  90621. */
  90622. get: function () {
  90623. return this.scene.getEngine()._drawCalls;
  90624. },
  90625. enumerable: true,
  90626. configurable: true
  90627. });
  90628. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90629. /**
  90630. * Gets the perf counter used for texture collisions
  90631. */
  90632. get: function () {
  90633. return this.scene.getEngine()._textureCollisions;
  90634. },
  90635. enumerable: true,
  90636. configurable: true
  90637. });
  90638. SceneInstrumentation.prototype.dispose = function () {
  90639. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90640. this._onAfterRenderObserver = null;
  90641. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90642. this._onBeforeActiveMeshesEvaluationObserver = null;
  90643. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90644. this._onAfterActiveMeshesEvaluationObserver = null;
  90645. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90646. this._onBeforeRenderTargetsRenderObserver = null;
  90647. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90648. this._onAfterRenderTargetsRenderObserver = null;
  90649. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90650. this._onBeforeAnimationsObserver = null;
  90651. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90652. this._onBeforeParticlesRenderingObserver = null;
  90653. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90654. this._onAfterParticlesRenderingObserver = null;
  90655. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90656. this._onBeforeSpritesRenderingObserver = null;
  90657. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90658. this._onAfterSpritesRenderingObserver = null;
  90659. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90660. this._onBeforeDrawPhaseObserver = null;
  90661. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90662. this._onAfterDrawPhaseObserver = null;
  90663. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90664. this._onBeforePhysicsObserver = null;
  90665. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90666. this._onAfterPhysicsObserver = null;
  90667. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90668. this._onAfterAnimationsObserver = null;
  90669. this.scene = null;
  90670. };
  90671. return SceneInstrumentation;
  90672. }());
  90673. BABYLON.SceneInstrumentation = SceneInstrumentation;
  90674. })(BABYLON || (BABYLON = {}));
  90675. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  90676. "use strict";
  90677. var BABYLON;
  90678. (function (BABYLON) {
  90679. var _TimeToken = /** @class */ (function () {
  90680. function _TimeToken() {
  90681. this._timeElapsedQueryEnded = false;
  90682. }
  90683. return _TimeToken;
  90684. }());
  90685. BABYLON._TimeToken = _TimeToken;
  90686. })(BABYLON || (BABYLON = {}));
  90687. //# sourceMappingURL=babylon.timeToken.js.map
  90688. "use strict";
  90689. var BABYLON;
  90690. (function (BABYLON) {
  90691. /**
  90692. * Background material defines definition.
  90693. * @ignore Mainly internal Use
  90694. */
  90695. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  90696. __extends(BackgroundMaterialDefines, _super);
  90697. /**
  90698. * Constructor of the defines.
  90699. */
  90700. function BackgroundMaterialDefines() {
  90701. var _this = _super.call(this) || this;
  90702. /**
  90703. * True if the diffuse texture is in use.
  90704. */
  90705. _this.DIFFUSE = false;
  90706. /**
  90707. * The direct UV channel to use.
  90708. */
  90709. _this.DIFFUSEDIRECTUV = 0;
  90710. /**
  90711. * True if the diffuse texture is in gamma space.
  90712. */
  90713. _this.GAMMADIFFUSE = false;
  90714. /**
  90715. * True if the diffuse texture has opacity in the alpha channel.
  90716. */
  90717. _this.DIFFUSEHASALPHA = false;
  90718. /**
  90719. * True if you want the material to fade to transparent at grazing angle.
  90720. */
  90721. _this.OPACITYFRESNEL = false;
  90722. /**
  90723. * True if an extra blur needs to be added in the reflection.
  90724. */
  90725. _this.REFLECTIONBLUR = false;
  90726. /**
  90727. * True if you want the material to fade to reflection at grazing angle.
  90728. */
  90729. _this.REFLECTIONFRESNEL = false;
  90730. /**
  90731. * True if you want the material to falloff as far as you move away from the scene center.
  90732. */
  90733. _this.REFLECTIONFALLOFF = false;
  90734. /**
  90735. * False if the current Webgl implementation does not support the texture lod extension.
  90736. */
  90737. _this.TEXTURELODSUPPORT = false;
  90738. /**
  90739. * True to ensure the data are premultiplied.
  90740. */
  90741. _this.PREMULTIPLYALPHA = false;
  90742. /**
  90743. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  90744. */
  90745. _this.USERGBCOLOR = false;
  90746. /**
  90747. * True to add noise in order to reduce the banding effect.
  90748. */
  90749. _this.NOISE = false;
  90750. /**
  90751. * is the reflection texture in BGR color scheme?
  90752. * Mainly used to solve a bug in ios10 video tag
  90753. */
  90754. _this.REFLECTIONBGR = false;
  90755. _this.IMAGEPROCESSING = false;
  90756. _this.VIGNETTE = false;
  90757. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  90758. _this.VIGNETTEBLENDMODEOPAQUE = false;
  90759. _this.TONEMAPPING = false;
  90760. _this.CONTRAST = false;
  90761. _this.COLORCURVES = false;
  90762. _this.COLORGRADING = false;
  90763. _this.COLORGRADING3D = false;
  90764. _this.SAMPLER3DGREENDEPTH = false;
  90765. _this.SAMPLER3DBGRMAP = false;
  90766. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  90767. _this.EXPOSURE = false;
  90768. _this.GRAIN = false;
  90769. // Reflection.
  90770. _this.REFLECTION = false;
  90771. _this.REFLECTIONMAP_3D = false;
  90772. _this.REFLECTIONMAP_SPHERICAL = false;
  90773. _this.REFLECTIONMAP_PLANAR = false;
  90774. _this.REFLECTIONMAP_CUBIC = false;
  90775. _this.REFLECTIONMAP_PROJECTION = false;
  90776. _this.REFLECTIONMAP_SKYBOX = false;
  90777. _this.REFLECTIONMAP_EXPLICIT = false;
  90778. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90779. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90780. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90781. _this.INVERTCUBICMAP = false;
  90782. _this.REFLECTIONMAP_OPPOSITEZ = false;
  90783. _this.LODINREFLECTIONALPHA = false;
  90784. _this.GAMMAREFLECTION = false;
  90785. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  90786. // Default BJS.
  90787. _this.MAINUV1 = false;
  90788. _this.MAINUV2 = false;
  90789. _this.UV1 = false;
  90790. _this.UV2 = false;
  90791. _this.CLIPPLANE = false;
  90792. _this.POINTSIZE = false;
  90793. _this.FOG = false;
  90794. _this.NORMAL = false;
  90795. _this.NUM_BONE_INFLUENCERS = 0;
  90796. _this.BonesPerMesh = 0;
  90797. _this.INSTANCES = false;
  90798. _this.SHADOWFLOAT = false;
  90799. _this.rebuild();
  90800. return _this;
  90801. }
  90802. return BackgroundMaterialDefines;
  90803. }(BABYLON.MaterialDefines));
  90804. /**
  90805. * Background material used to create an efficient environement around your scene.
  90806. */
  90807. var BackgroundMaterial = /** @class */ (function (_super) {
  90808. __extends(BackgroundMaterial, _super);
  90809. /**
  90810. * Instantiates a Background Material in the given scene
  90811. * @param name The friendly name of the material
  90812. * @param scene The scene to add the material to
  90813. */
  90814. function BackgroundMaterial(name, scene) {
  90815. var _this = _super.call(this, name, scene) || this;
  90816. /**
  90817. * Key light Color (multiply against the R channel of the environement texture)
  90818. */
  90819. _this.primaryColor = BABYLON.Color3.White();
  90820. /**
  90821. * Key light Level (allowing HDR output of the background)
  90822. */
  90823. _this.primaryLevel = 1;
  90824. /**
  90825. * Secondary light Color (multiply against the G channel of the environement texture)
  90826. */
  90827. _this.secondaryColor = BABYLON.Color3.Gray();
  90828. /**
  90829. * Secondary light Level (allowing HDR output of the background)
  90830. */
  90831. _this.secondaryLevel = 1;
  90832. /**
  90833. * Tertiary light Color (multiply against the B channel of the environement texture)
  90834. */
  90835. _this.tertiaryColor = BABYLON.Color3.Black();
  90836. /**
  90837. * Tertiary light Level (allowing HDR output of the background)
  90838. */
  90839. _this.tertiaryLevel = 1;
  90840. /**
  90841. * Reflection Texture used in the material.
  90842. * Should be author in a specific way for the best result (refer to the documentation).
  90843. */
  90844. _this.reflectionTexture = null;
  90845. /**
  90846. * Reflection Texture level of blur.
  90847. *
  90848. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  90849. * texture twice.
  90850. */
  90851. _this.reflectionBlur = 0;
  90852. /**
  90853. * Diffuse Texture used in the material.
  90854. * Should be author in a specific way for the best result (refer to the documentation).
  90855. */
  90856. _this.diffuseTexture = null;
  90857. _this._shadowLights = null;
  90858. /**
  90859. * Specify the list of lights casting shadow on the material.
  90860. * All scene shadow lights will be included if null.
  90861. */
  90862. _this.shadowLights = null;
  90863. /**
  90864. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  90865. * soft lighting on the background.
  90866. */
  90867. _this.shadowBlurScale = 1;
  90868. /**
  90869. * Helps adjusting the shadow to a softer level if required.
  90870. * 0 means black shadows and 1 means no shadows.
  90871. */
  90872. _this.shadowLevel = 0;
  90873. /**
  90874. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  90875. * It is usually zero but might be interesting to modify according to your setup.
  90876. */
  90877. _this.sceneCenter = BABYLON.Vector3.Zero();
  90878. /**
  90879. * This helps specifying that the material is falling off to the sky box at grazing angle.
  90880. * This helps ensuring a nice transition when the camera goes under the ground.
  90881. */
  90882. _this.opacityFresnel = true;
  90883. /**
  90884. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  90885. * This helps adding a mirror texture on the ground.
  90886. */
  90887. _this.reflectionFresnel = false;
  90888. /**
  90889. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  90890. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  90891. */
  90892. _this.reflectionFalloffDistance = 0.0;
  90893. /**
  90894. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  90895. */
  90896. _this.reflectionAmount = 1.0;
  90897. /**
  90898. * This specifies the weight of the reflection at grazing angle.
  90899. */
  90900. _this.reflectionReflectance0 = 0.05;
  90901. /**
  90902. * This specifies the weight of the reflection at a perpendicular point of view.
  90903. */
  90904. _this.reflectionReflectance90 = 0.5;
  90905. /**
  90906. * Helps to directly use the maps channels instead of their level.
  90907. */
  90908. _this.useRGBColor = true;
  90909. /**
  90910. * This helps reducing the banding effect that could occur on the background.
  90911. */
  90912. _this.enableNoise = false;
  90913. _this._fovMultiplier = 1.0;
  90914. /**
  90915. * Enable the FOV adjustment feature controlled by fovMultiplier.
  90916. * @type {boolean}
  90917. */
  90918. _this.useEquirectangularFOV = false;
  90919. _this._maxSimultaneousLights = 4;
  90920. /**
  90921. * Number of Simultaneous lights allowed on the material.
  90922. */
  90923. _this.maxSimultaneousLights = 4;
  90924. /**
  90925. * Keep track of the image processing observer to allow dispose and replace.
  90926. */
  90927. _this._imageProcessingObserver = null;
  90928. /**
  90929. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  90930. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  90931. */
  90932. _this.switchToBGR = false;
  90933. // Temp values kept as cache in the material.
  90934. _this._renderTargets = new BABYLON.SmartArray(16);
  90935. _this._reflectionControls = BABYLON.Vector4.Zero();
  90936. // Setup the default processing configuration to the scene.
  90937. _this._attachImageProcessingConfiguration(null);
  90938. _this.getRenderTargetTextures = function () {
  90939. _this._renderTargets.reset();
  90940. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  90941. _this._renderTargets.push(_this._diffuseTexture);
  90942. }
  90943. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  90944. _this._renderTargets.push(_this._reflectionTexture);
  90945. }
  90946. return _this._renderTargets;
  90947. };
  90948. return _this;
  90949. }
  90950. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  90951. /**
  90952. * Sets the reflection reflectance fresnel values according to the default standard
  90953. * empirically know to work well :-)
  90954. */
  90955. set: function (value) {
  90956. var reflectionWeight = value;
  90957. if (reflectionWeight < 0.5) {
  90958. reflectionWeight = reflectionWeight * 2.0;
  90959. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  90960. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  90961. }
  90962. else {
  90963. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  90964. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  90965. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  90966. }
  90967. },
  90968. enumerable: true,
  90969. configurable: true
  90970. });
  90971. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  90972. /**
  90973. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90974. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  90975. * Recommended to be keep at 1.0 except for special cases.
  90976. */
  90977. get: function () {
  90978. return this._fovMultiplier;
  90979. },
  90980. set: function (value) {
  90981. if (isNaN(value)) {
  90982. value = 1.0;
  90983. }
  90984. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  90985. },
  90986. enumerable: true,
  90987. configurable: true
  90988. });
  90989. /**
  90990. * Attaches a new image processing configuration to the PBR Material.
  90991. * @param configuration (if null the scene configuration will be use)
  90992. */
  90993. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  90994. var _this = this;
  90995. if (configuration === this._imageProcessingConfiguration) {
  90996. return;
  90997. }
  90998. // Detaches observer.
  90999. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91000. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91001. }
  91002. // Pick the scene configuration if needed.
  91003. if (!configuration) {
  91004. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91005. }
  91006. else {
  91007. this._imageProcessingConfiguration = configuration;
  91008. }
  91009. // Attaches observer.
  91010. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91011. _this._markAllSubMeshesAsImageProcessingDirty();
  91012. });
  91013. };
  91014. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91015. /**
  91016. * Gets the image processing configuration used either in this material.
  91017. */
  91018. get: function () {
  91019. return this._imageProcessingConfiguration;
  91020. },
  91021. /**
  91022. * Sets the Default image processing configuration used either in the this material.
  91023. *
  91024. * If sets to null, the scene one is in use.
  91025. */
  91026. set: function (value) {
  91027. this._attachImageProcessingConfiguration(value);
  91028. // Ensure the effect will be rebuilt.
  91029. this._markAllSubMeshesAsTexturesDirty();
  91030. },
  91031. enumerable: true,
  91032. configurable: true
  91033. });
  91034. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91035. /**
  91036. * Gets wether the color curves effect is enabled.
  91037. */
  91038. get: function () {
  91039. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91040. },
  91041. /**
  91042. * Sets wether the color curves effect is enabled.
  91043. */
  91044. set: function (value) {
  91045. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91046. },
  91047. enumerable: true,
  91048. configurable: true
  91049. });
  91050. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91051. /**
  91052. * Gets wether the color grading effect is enabled.
  91053. */
  91054. get: function () {
  91055. return this.imageProcessingConfiguration.colorGradingEnabled;
  91056. },
  91057. /**
  91058. * Gets wether the color grading effect is enabled.
  91059. */
  91060. set: function (value) {
  91061. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91062. },
  91063. enumerable: true,
  91064. configurable: true
  91065. });
  91066. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91067. /**
  91068. * Gets wether tonemapping is enabled or not.
  91069. */
  91070. get: function () {
  91071. return this._imageProcessingConfiguration.toneMappingEnabled;
  91072. },
  91073. /**
  91074. * Sets wether tonemapping is enabled or not
  91075. */
  91076. set: function (value) {
  91077. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91078. },
  91079. enumerable: true,
  91080. configurable: true
  91081. });
  91082. ;
  91083. ;
  91084. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91085. /**
  91086. * The camera exposure used on this material.
  91087. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91088. * This corresponds to a photographic exposure.
  91089. */
  91090. get: function () {
  91091. return this._imageProcessingConfiguration.exposure;
  91092. },
  91093. /**
  91094. * The camera exposure used on this material.
  91095. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91096. * This corresponds to a photographic exposure.
  91097. */
  91098. set: function (value) {
  91099. this._imageProcessingConfiguration.exposure = value;
  91100. },
  91101. enumerable: true,
  91102. configurable: true
  91103. });
  91104. ;
  91105. ;
  91106. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91107. /**
  91108. * Gets The camera contrast used on this material.
  91109. */
  91110. get: function () {
  91111. return this._imageProcessingConfiguration.contrast;
  91112. },
  91113. /**
  91114. * Sets The camera contrast used on this material.
  91115. */
  91116. set: function (value) {
  91117. this._imageProcessingConfiguration.contrast = value;
  91118. },
  91119. enumerable: true,
  91120. configurable: true
  91121. });
  91122. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91123. /**
  91124. * Gets the Color Grading 2D Lookup Texture.
  91125. */
  91126. get: function () {
  91127. return this._imageProcessingConfiguration.colorGradingTexture;
  91128. },
  91129. /**
  91130. * Sets the Color Grading 2D Lookup Texture.
  91131. */
  91132. set: function (value) {
  91133. this.imageProcessingConfiguration.colorGradingTexture = value;
  91134. },
  91135. enumerable: true,
  91136. configurable: true
  91137. });
  91138. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91139. /**
  91140. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91141. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91142. * 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;
  91143. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91144. */
  91145. get: function () {
  91146. return this.imageProcessingConfiguration.colorCurves;
  91147. },
  91148. /**
  91149. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91150. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91151. * 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;
  91152. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91153. */
  91154. set: function (value) {
  91155. this.imageProcessingConfiguration.colorCurves = value;
  91156. },
  91157. enumerable: true,
  91158. configurable: true
  91159. });
  91160. /**
  91161. * The entire material has been created in order to prevent overdraw.
  91162. * @returns false
  91163. */
  91164. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91165. return true;
  91166. };
  91167. /**
  91168. * The entire material has been created in order to prevent overdraw.
  91169. * @returns true if blending is enable
  91170. */
  91171. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91172. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91173. };
  91174. /**
  91175. * Checks wether the material is ready to be rendered for a given mesh.
  91176. * @param mesh The mesh to render
  91177. * @param subMesh The submesh to check against
  91178. * @param useInstances Specify wether or not the material is used with instances
  91179. * @returns true if all the dependencies are ready (Textures, Effects...)
  91180. */
  91181. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91182. var _this = this;
  91183. if (useInstances === void 0) { useInstances = false; }
  91184. if (subMesh.effect && this.isFrozen) {
  91185. if (this._wasPreviouslyReady) {
  91186. return true;
  91187. }
  91188. }
  91189. if (!subMesh._materialDefines) {
  91190. subMesh._materialDefines = new BackgroundMaterialDefines();
  91191. }
  91192. var scene = this.getScene();
  91193. var defines = subMesh._materialDefines;
  91194. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91195. if (defines._renderId === scene.getRenderId()) {
  91196. return true;
  91197. }
  91198. }
  91199. var engine = scene.getEngine();
  91200. // Lights
  91201. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91202. defines._needNormals = true;
  91203. // Textures
  91204. if (defines._areTexturesDirty) {
  91205. defines._needUVs = false;
  91206. if (scene.texturesEnabled) {
  91207. if (scene.getEngine().getCaps().textureLOD) {
  91208. defines.TEXTURELODSUPPORT = true;
  91209. }
  91210. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91211. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91212. return false;
  91213. }
  91214. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91215. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91216. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91217. defines.OPACITYFRESNEL = this._opacityFresnel;
  91218. }
  91219. else {
  91220. defines.DIFFUSE = false;
  91221. defines.DIFFUSEHASALPHA = false;
  91222. defines.GAMMADIFFUSE = false;
  91223. defines.OPACITYFRESNEL = false;
  91224. }
  91225. var reflectionTexture = this._reflectionTexture;
  91226. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91227. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91228. return false;
  91229. }
  91230. defines.REFLECTION = true;
  91231. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91232. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91233. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91234. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91235. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91236. defines.REFLECTIONBGR = this.switchToBGR;
  91237. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91238. defines.INVERTCUBICMAP = true;
  91239. }
  91240. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91241. switch (reflectionTexture.coordinatesMode) {
  91242. case BABYLON.Texture.CUBIC_MODE:
  91243. case BABYLON.Texture.INVCUBIC_MODE:
  91244. defines.REFLECTIONMAP_CUBIC = true;
  91245. break;
  91246. case BABYLON.Texture.EXPLICIT_MODE:
  91247. defines.REFLECTIONMAP_EXPLICIT = true;
  91248. break;
  91249. case BABYLON.Texture.PLANAR_MODE:
  91250. defines.REFLECTIONMAP_PLANAR = true;
  91251. break;
  91252. case BABYLON.Texture.PROJECTION_MODE:
  91253. defines.REFLECTIONMAP_PROJECTION = true;
  91254. break;
  91255. case BABYLON.Texture.SKYBOX_MODE:
  91256. defines.REFLECTIONMAP_SKYBOX = true;
  91257. break;
  91258. case BABYLON.Texture.SPHERICAL_MODE:
  91259. defines.REFLECTIONMAP_SPHERICAL = true;
  91260. break;
  91261. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91262. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91263. break;
  91264. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91265. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91266. break;
  91267. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91268. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91269. break;
  91270. }
  91271. if (this.reflectionFresnel) {
  91272. defines.REFLECTIONFRESNEL = true;
  91273. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91274. this._reflectionControls.x = this.reflectionAmount;
  91275. this._reflectionControls.y = this.reflectionReflectance0;
  91276. this._reflectionControls.z = this.reflectionReflectance90;
  91277. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91278. }
  91279. else {
  91280. defines.REFLECTIONFRESNEL = false;
  91281. defines.REFLECTIONFALLOFF = false;
  91282. }
  91283. }
  91284. else {
  91285. defines.REFLECTION = false;
  91286. defines.REFLECTIONFALLOFF = false;
  91287. defines.REFLECTIONBLUR = false;
  91288. defines.REFLECTIONMAP_3D = false;
  91289. defines.REFLECTIONMAP_SPHERICAL = false;
  91290. defines.REFLECTIONMAP_PLANAR = false;
  91291. defines.REFLECTIONMAP_CUBIC = false;
  91292. defines.REFLECTIONMAP_PROJECTION = false;
  91293. defines.REFLECTIONMAP_SKYBOX = false;
  91294. defines.REFLECTIONMAP_EXPLICIT = false;
  91295. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91296. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91297. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91298. defines.INVERTCUBICMAP = false;
  91299. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91300. defines.LODINREFLECTIONALPHA = false;
  91301. defines.GAMMAREFLECTION = false;
  91302. }
  91303. }
  91304. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91305. defines.USERGBCOLOR = this._useRGBColor;
  91306. defines.NOISE = this._enableNoise;
  91307. }
  91308. if (defines._areImageProcessingDirty) {
  91309. if (!this._imageProcessingConfiguration.isReady()) {
  91310. return false;
  91311. }
  91312. this._imageProcessingConfiguration.prepareDefines(defines);
  91313. }
  91314. // Misc.
  91315. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91316. // Values that need to be evaluated on every frame
  91317. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91318. // Attribs
  91319. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91320. if (mesh) {
  91321. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91322. mesh.createNormals(true);
  91323. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91324. }
  91325. }
  91326. }
  91327. // Get correct effect
  91328. if (defines.isDirty) {
  91329. defines.markAsProcessed();
  91330. scene.resetCachedMaterial();
  91331. // Fallbacks
  91332. var fallbacks = new BABYLON.EffectFallbacks();
  91333. if (defines.FOG) {
  91334. fallbacks.addFallback(0, "FOG");
  91335. }
  91336. if (defines.POINTSIZE) {
  91337. fallbacks.addFallback(1, "POINTSIZE");
  91338. }
  91339. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91340. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91341. fallbacks.addCPUSkinningFallback(0, mesh);
  91342. }
  91343. //Attributes
  91344. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91345. if (defines.NORMAL) {
  91346. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91347. }
  91348. if (defines.UV1) {
  91349. attribs.push(BABYLON.VertexBuffer.UVKind);
  91350. }
  91351. if (defines.UV2) {
  91352. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91353. }
  91354. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91355. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91356. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91357. "vFogInfos", "vFogColor", "pointSize",
  91358. "vClipPlane", "mBones",
  91359. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91360. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91361. "shadowLevel", "alpha",
  91362. "vBackgroundCenter", "vReflectionControl",
  91363. "vDiffuseInfos", "diffuseMatrix",
  91364. ];
  91365. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91366. var uniformBuffers = ["Material", "Scene"];
  91367. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91368. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91369. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91370. uniformsNames: uniforms,
  91371. uniformBuffersNames: uniformBuffers,
  91372. samplers: samplers,
  91373. defines: defines,
  91374. maxSimultaneousLights: this._maxSimultaneousLights
  91375. });
  91376. var onCompiled = function (effect) {
  91377. if (_this.onCompiled) {
  91378. _this.onCompiled(effect);
  91379. }
  91380. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91381. };
  91382. var join = defines.toString();
  91383. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91384. attributes: attribs,
  91385. uniformsNames: uniforms,
  91386. uniformBuffersNames: uniformBuffers,
  91387. samplers: samplers,
  91388. defines: join,
  91389. fallbacks: fallbacks,
  91390. onCompiled: onCompiled,
  91391. onError: this.onError,
  91392. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91393. }, engine), defines);
  91394. this.buildUniformLayout();
  91395. }
  91396. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91397. return false;
  91398. }
  91399. defines._renderId = scene.getRenderId();
  91400. this._wasPreviouslyReady = true;
  91401. return true;
  91402. };
  91403. /**
  91404. * Build the uniform buffer used in the material.
  91405. */
  91406. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91407. // Order is important !
  91408. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91409. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91410. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91411. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91412. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91413. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91414. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91415. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91416. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91417. this._uniformBuffer.addUniform("pointSize", 1);
  91418. this._uniformBuffer.addUniform("shadowLevel", 1);
  91419. this._uniformBuffer.addUniform("alpha", 1);
  91420. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91421. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91422. this._uniformBuffer.create();
  91423. };
  91424. /**
  91425. * Unbind the material.
  91426. */
  91427. BackgroundMaterial.prototype.unbind = function () {
  91428. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91429. this._uniformBuffer.setTexture("diffuseSampler", null);
  91430. }
  91431. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91432. this._uniformBuffer.setTexture("reflectionSampler", null);
  91433. }
  91434. _super.prototype.unbind.call(this);
  91435. };
  91436. /**
  91437. * Bind only the world matrix to the material.
  91438. * @param world The world matrix to bind.
  91439. */
  91440. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91441. this._activeEffect.setMatrix("world", world);
  91442. };
  91443. /**
  91444. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91445. * @param world The world matrix to bind.
  91446. * @param subMesh The submesh to bind for.
  91447. */
  91448. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91449. var scene = this.getScene();
  91450. var defines = subMesh._materialDefines;
  91451. if (!defines) {
  91452. return;
  91453. }
  91454. var effect = subMesh.effect;
  91455. if (!effect) {
  91456. return;
  91457. }
  91458. this._activeEffect = effect;
  91459. // Matrices
  91460. this.bindOnlyWorldMatrix(world);
  91461. // Bones
  91462. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91463. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91464. if (mustRebind) {
  91465. this._uniformBuffer.bindToEffect(effect, "Material");
  91466. this.bindViewProjection(effect);
  91467. var reflectionTexture = this._reflectionTexture;
  91468. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91469. // Texture uniforms
  91470. if (scene.texturesEnabled) {
  91471. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91472. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91473. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91474. }
  91475. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91476. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91477. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91478. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91479. }
  91480. }
  91481. if (this.shadowLevel > 0) {
  91482. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91483. }
  91484. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91485. // Point size
  91486. if (this.pointsCloud) {
  91487. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91488. }
  91489. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91490. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91491. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91492. }
  91493. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91494. // Textures
  91495. if (scene.texturesEnabled) {
  91496. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91497. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91498. }
  91499. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91500. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91501. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91502. }
  91503. else if (!defines.REFLECTIONBLUR) {
  91504. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91505. }
  91506. else {
  91507. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91508. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91509. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91510. }
  91511. if (defines.REFLECTIONFRESNEL) {
  91512. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91513. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91514. }
  91515. }
  91516. }
  91517. // Clip plane
  91518. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91519. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91520. }
  91521. if (mustRebind || !this.isFrozen) {
  91522. if (scene.lightsEnabled) {
  91523. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91524. }
  91525. // View
  91526. this.bindView(effect);
  91527. // Fog
  91528. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91529. // image processing
  91530. this._imageProcessingConfiguration.bind(this._activeEffect);
  91531. }
  91532. this._uniformBuffer.update();
  91533. this._afterBind(mesh);
  91534. };
  91535. /**
  91536. * Dispose the material.
  91537. * @param forceDisposeEffect Force disposal of the associated effect.
  91538. * @param forceDisposeTextures Force disposal of the associated textures.
  91539. */
  91540. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91541. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91542. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91543. if (forceDisposeTextures) {
  91544. if (this.diffuseTexture) {
  91545. this.diffuseTexture.dispose();
  91546. }
  91547. if (this.reflectionTexture) {
  91548. this.reflectionTexture.dispose();
  91549. }
  91550. }
  91551. this._renderTargets.dispose();
  91552. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91553. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91554. }
  91555. _super.prototype.dispose.call(this, forceDisposeEffect);
  91556. };
  91557. /**
  91558. * Clones the material.
  91559. * @param name The cloned name.
  91560. * @returns The cloned material.
  91561. */
  91562. BackgroundMaterial.prototype.clone = function (name) {
  91563. var _this = this;
  91564. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91565. };
  91566. /**
  91567. * Serializes the current material to its JSON representation.
  91568. * @returns The JSON representation.
  91569. */
  91570. BackgroundMaterial.prototype.serialize = function () {
  91571. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91572. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91573. return serializationObject;
  91574. };
  91575. /**
  91576. * Gets the class name of the material
  91577. * @returns "BackgroundMaterial"
  91578. */
  91579. BackgroundMaterial.prototype.getClassName = function () {
  91580. return "BackgroundMaterial";
  91581. };
  91582. /**
  91583. * Parse a JSON input to create back a background material.
  91584. * @param source The JSON data to parse
  91585. * @param scene The scene to create the parsed material in
  91586. * @param rootUrl The root url of the assets the material depends upon
  91587. * @returns the instantiated BackgroundMaterial.
  91588. */
  91589. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91590. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91591. };
  91592. /**
  91593. * Standard reflectance value at parallel view angle.
  91594. */
  91595. BackgroundMaterial.StandardReflectance0 = 0.05;
  91596. /**
  91597. * Standard reflectance value at grazing angle.
  91598. */
  91599. BackgroundMaterial.StandardReflectance90 = 0.5;
  91600. __decorate([
  91601. BABYLON.serializeAsColor3()
  91602. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91603. __decorate([
  91604. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91605. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91606. __decorate([
  91607. BABYLON.serialize()
  91608. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91609. __decorate([
  91610. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91611. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91612. __decorate([
  91613. BABYLON.serializeAsColor3()
  91614. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91615. __decorate([
  91616. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91617. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91618. __decorate([
  91619. BABYLON.serialize()
  91620. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91621. __decorate([
  91622. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91623. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91624. __decorate([
  91625. BABYLON.serializeAsColor3()
  91626. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91627. __decorate([
  91628. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91629. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91630. __decorate([
  91631. BABYLON.serialize()
  91632. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91633. __decorate([
  91634. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91635. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91636. __decorate([
  91637. BABYLON.serializeAsTexture()
  91638. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91639. __decorate([
  91640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91641. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91642. __decorate([
  91643. BABYLON.serialize()
  91644. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91645. __decorate([
  91646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91647. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91648. __decorate([
  91649. BABYLON.serializeAsTexture()
  91650. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91651. __decorate([
  91652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91653. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  91654. __decorate([
  91655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91656. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  91657. __decorate([
  91658. BABYLON.serialize()
  91659. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  91660. __decorate([
  91661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91662. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  91663. __decorate([
  91664. BABYLON.serialize()
  91665. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  91666. __decorate([
  91667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91668. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  91669. __decorate([
  91670. BABYLON.serializeAsVector3()
  91671. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  91672. __decorate([
  91673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91674. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  91675. __decorate([
  91676. BABYLON.serialize()
  91677. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  91678. __decorate([
  91679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91680. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  91681. __decorate([
  91682. BABYLON.serialize()
  91683. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  91684. __decorate([
  91685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91686. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  91687. __decorate([
  91688. BABYLON.serialize()
  91689. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  91690. __decorate([
  91691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91692. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  91693. __decorate([
  91694. BABYLON.serialize()
  91695. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  91696. __decorate([
  91697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91698. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  91699. __decorate([
  91700. BABYLON.serialize()
  91701. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  91702. __decorate([
  91703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91704. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  91705. __decorate([
  91706. BABYLON.serialize()
  91707. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  91708. __decorate([
  91709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91710. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  91711. __decorate([
  91712. BABYLON.serialize()
  91713. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  91714. __decorate([
  91715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91716. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  91717. __decorate([
  91718. BABYLON.serialize()
  91719. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  91720. __decorate([
  91721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91722. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  91723. __decorate([
  91724. BABYLON.serialize()
  91725. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  91726. __decorate([
  91727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91728. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  91729. __decorate([
  91730. BABYLON.serializeAsImageProcessingConfiguration()
  91731. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  91732. return BackgroundMaterial;
  91733. }(BABYLON.PushMaterial));
  91734. BABYLON.BackgroundMaterial = BackgroundMaterial;
  91735. })(BABYLON || (BABYLON = {}));
  91736. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  91737. "use strict";
  91738. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91739. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91740. s = arguments[i];
  91741. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91742. t[p] = s[p];
  91743. }
  91744. return t;
  91745. };
  91746. var BABYLON;
  91747. (function (BABYLON) {
  91748. /**
  91749. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  91750. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  91751. * It also helps with the default setup of your imageProcessing configuration.
  91752. */
  91753. var EnvironmentHelper = /** @class */ (function () {
  91754. /**
  91755. * constructor
  91756. * @param options
  91757. * @param scene The scene to add the material to
  91758. */
  91759. function EnvironmentHelper(options, scene) {
  91760. var _this = this;
  91761. this._errorHandler = function (message, exception) {
  91762. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  91763. };
  91764. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  91765. this._scene = scene;
  91766. this.onErrorObservable = new BABYLON.Observable();
  91767. this._setupBackground();
  91768. this._setupImageProcessing();
  91769. }
  91770. /**
  91771. * Creates the default options for the helper.
  91772. */
  91773. EnvironmentHelper._getDefaultOptions = function () {
  91774. return {
  91775. createGround: true,
  91776. groundSize: 15,
  91777. groundTexture: this._groundTextureCDNUrl,
  91778. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91779. groundOpacity: 0.9,
  91780. enableGroundShadow: true,
  91781. groundShadowLevel: 0.5,
  91782. enableGroundMirror: false,
  91783. groundMirrorSizeRatio: 0.3,
  91784. groundMirrorBlurKernel: 64,
  91785. groundMirrorAmount: 1,
  91786. groundMirrorFresnelWeight: 1,
  91787. groundMirrorFallOffDistance: 0,
  91788. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  91789. groundYBias: 0.00001,
  91790. createSkybox: true,
  91791. skyboxSize: 20,
  91792. skyboxTexture: this._skyboxTextureCDNUrl,
  91793. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91794. backgroundYRotation: 0,
  91795. sizeAuto: true,
  91796. rootPosition: BABYLON.Vector3.Zero(),
  91797. setupImageProcessing: true,
  91798. environmentTexture: this._environmentTextureCDNUrl,
  91799. cameraExposure: 0.8,
  91800. cameraContrast: 1.2,
  91801. toneMappingEnabled: true,
  91802. };
  91803. };
  91804. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  91805. /**
  91806. * Gets the root mesh created by the helper.
  91807. */
  91808. get: function () {
  91809. return this._rootMesh;
  91810. },
  91811. enumerable: true,
  91812. configurable: true
  91813. });
  91814. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  91815. /**
  91816. * Gets the skybox created by the helper.
  91817. */
  91818. get: function () {
  91819. return this._skybox;
  91820. },
  91821. enumerable: true,
  91822. configurable: true
  91823. });
  91824. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  91825. /**
  91826. * Gets the skybox texture created by the helper.
  91827. */
  91828. get: function () {
  91829. return this._skyboxTexture;
  91830. },
  91831. enumerable: true,
  91832. configurable: true
  91833. });
  91834. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  91835. /**
  91836. * Gets the skybox material created by the helper.
  91837. */
  91838. get: function () {
  91839. return this._skyboxMaterial;
  91840. },
  91841. enumerable: true,
  91842. configurable: true
  91843. });
  91844. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  91845. /**
  91846. * Gets the ground mesh created by the helper.
  91847. */
  91848. get: function () {
  91849. return this._ground;
  91850. },
  91851. enumerable: true,
  91852. configurable: true
  91853. });
  91854. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  91855. /**
  91856. * Gets the ground texture created by the helper.
  91857. */
  91858. get: function () {
  91859. return this._groundTexture;
  91860. },
  91861. enumerable: true,
  91862. configurable: true
  91863. });
  91864. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  91865. /**
  91866. * Gets the ground mirror created by the helper.
  91867. */
  91868. get: function () {
  91869. return this._groundMirror;
  91870. },
  91871. enumerable: true,
  91872. configurable: true
  91873. });
  91874. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  91875. /**
  91876. * Gets the ground mirror render list to helps pushing the meshes
  91877. * you wish in the ground reflection.
  91878. */
  91879. get: function () {
  91880. if (this._groundMirror) {
  91881. return this._groundMirror.renderList;
  91882. }
  91883. return null;
  91884. },
  91885. enumerable: true,
  91886. configurable: true
  91887. });
  91888. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  91889. /**
  91890. * Gets the ground material created by the helper.
  91891. */
  91892. get: function () {
  91893. return this._groundMaterial;
  91894. },
  91895. enumerable: true,
  91896. configurable: true
  91897. });
  91898. /**
  91899. * Updates the background according to the new options
  91900. * @param options
  91901. */
  91902. EnvironmentHelper.prototype.updateOptions = function (options) {
  91903. var newOptions = __assign({}, this._options, options);
  91904. if (this._ground && !newOptions.createGround) {
  91905. this._ground.dispose();
  91906. this._ground = null;
  91907. }
  91908. if (this._groundMaterial && !newOptions.createGround) {
  91909. this._groundMaterial.dispose();
  91910. this._groundMaterial = null;
  91911. }
  91912. if (this._groundTexture) {
  91913. if (this._options.groundTexture != newOptions.groundTexture) {
  91914. this._groundTexture.dispose();
  91915. this._groundTexture = null;
  91916. }
  91917. }
  91918. if (this._skybox && !newOptions.createSkybox) {
  91919. this._skybox.dispose();
  91920. this._skybox = null;
  91921. }
  91922. if (this._skyboxMaterial && !newOptions.createSkybox) {
  91923. this._skyboxMaterial.dispose();
  91924. this._skyboxMaterial = null;
  91925. }
  91926. if (this._skyboxTexture) {
  91927. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  91928. this._skyboxTexture.dispose();
  91929. this._skyboxTexture = null;
  91930. }
  91931. }
  91932. if (this._groundMirror && !newOptions.enableGroundMirror) {
  91933. this._groundMirror.dispose();
  91934. this._groundMirror = null;
  91935. }
  91936. if (this._scene.environmentTexture) {
  91937. if (this._options.environmentTexture != newOptions.environmentTexture) {
  91938. this._scene.environmentTexture.dispose();
  91939. }
  91940. }
  91941. this._options = newOptions;
  91942. this._setupBackground();
  91943. this._setupImageProcessing();
  91944. };
  91945. /**
  91946. * Sets the primary color of all the available elements.
  91947. * @param color
  91948. */
  91949. EnvironmentHelper.prototype.setMainColor = function (color) {
  91950. if (this.groundMaterial) {
  91951. this.groundMaterial.primaryColor = color;
  91952. }
  91953. if (this.skyboxMaterial) {
  91954. this.skyboxMaterial.primaryColor = color;
  91955. }
  91956. if (this.groundMirror) {
  91957. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  91958. }
  91959. };
  91960. /**
  91961. * Setup the image processing according to the specified options.
  91962. */
  91963. EnvironmentHelper.prototype._setupImageProcessing = function () {
  91964. if (this._options.setupImageProcessing) {
  91965. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  91966. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  91967. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  91968. this._setupEnvironmentTexture();
  91969. }
  91970. };
  91971. /**
  91972. * Setup the environment texture according to the specified options.
  91973. */
  91974. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  91975. if (this._scene.environmentTexture) {
  91976. return;
  91977. }
  91978. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  91979. this._scene.environmentTexture = this._options.environmentTexture;
  91980. return;
  91981. }
  91982. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  91983. this._scene.environmentTexture = environmentTexture;
  91984. };
  91985. /**
  91986. * Setup the background according to the specified options.
  91987. */
  91988. EnvironmentHelper.prototype._setupBackground = function () {
  91989. if (!this._rootMesh) {
  91990. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  91991. }
  91992. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  91993. var sceneSize = this._getSceneSize();
  91994. if (this._options.createGround) {
  91995. this._setupGround(sceneSize);
  91996. this._setupGroundMaterial();
  91997. this._setupGroundDiffuseTexture();
  91998. if (this._options.enableGroundMirror) {
  91999. this._setupGroundMirrorTexture(sceneSize);
  92000. }
  92001. this._setupMirrorInGroundMaterial();
  92002. }
  92003. if (this._options.createSkybox) {
  92004. this._setupSkybox(sceneSize);
  92005. this._setupSkyboxMaterial();
  92006. this._setupSkyboxReflectionTexture();
  92007. }
  92008. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92009. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92010. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92011. };
  92012. /**
  92013. * Get the scene sizes according to the setup.
  92014. */
  92015. EnvironmentHelper.prototype._getSceneSize = function () {
  92016. var _this = this;
  92017. var groundSize = this._options.groundSize;
  92018. var skyboxSize = this._options.skyboxSize;
  92019. var rootPosition = this._options.rootPosition;
  92020. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92021. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92022. }
  92023. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92024. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92025. });
  92026. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92027. if (this._options.sizeAuto) {
  92028. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92029. this._scene.activeCamera.upperRadiusLimit) {
  92030. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92031. skyboxSize = groundSize;
  92032. }
  92033. var sceneDiagonalLenght = sceneDiagonal.length();
  92034. if (sceneDiagonalLenght > groundSize) {
  92035. groundSize = sceneDiagonalLenght * 2;
  92036. skyboxSize = groundSize;
  92037. }
  92038. // 10 % bigger.
  92039. groundSize *= 1.1;
  92040. skyboxSize *= 1.5;
  92041. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92042. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92043. }
  92044. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92045. };
  92046. /**
  92047. * Setup the ground according to the specified options.
  92048. */
  92049. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92050. var _this = this;
  92051. if (!this._ground) {
  92052. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92053. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92054. this._ground.parent = this._rootMesh;
  92055. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92056. }
  92057. this._ground.receiveShadows = this._options.enableGroundShadow;
  92058. };
  92059. /**
  92060. * Setup the ground material according to the specified options.
  92061. */
  92062. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92063. if (!this._groundMaterial) {
  92064. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92065. }
  92066. this._groundMaterial.alpha = this._options.groundOpacity;
  92067. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92068. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92069. this._groundMaterial.primaryLevel = 1;
  92070. this._groundMaterial.primaryColor = this._options.groundColor;
  92071. this._groundMaterial.secondaryLevel = 0;
  92072. this._groundMaterial.tertiaryLevel = 0;
  92073. this._groundMaterial.useRGBColor = false;
  92074. this._groundMaterial.enableNoise = true;
  92075. if (this._ground) {
  92076. this._ground.material = this._groundMaterial;
  92077. }
  92078. };
  92079. /**
  92080. * Setup the ground diffuse texture according to the specified options.
  92081. */
  92082. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92083. if (!this._groundMaterial) {
  92084. return;
  92085. }
  92086. if (this._groundTexture) {
  92087. return;
  92088. }
  92089. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92090. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92091. return;
  92092. }
  92093. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92094. diffuseTexture.gammaSpace = false;
  92095. diffuseTexture.hasAlpha = true;
  92096. this._groundMaterial.diffuseTexture = diffuseTexture;
  92097. };
  92098. /**
  92099. * Setup the ground mirror texture according to the specified options.
  92100. */
  92101. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92102. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92103. if (!this._groundMirror) {
  92104. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92105. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92106. this._groundMirror.anisotropicFilteringLevel = 1;
  92107. this._groundMirror.wrapU = wrapping;
  92108. this._groundMirror.wrapV = wrapping;
  92109. this._groundMirror.gammaSpace = false;
  92110. if (this._groundMirror.renderList) {
  92111. for (var i = 0; i < this._scene.meshes.length; i++) {
  92112. var mesh = this._scene.meshes[i];
  92113. if (mesh !== this._ground &&
  92114. mesh !== this._skybox &&
  92115. mesh !== this._rootMesh) {
  92116. this._groundMirror.renderList.push(mesh);
  92117. }
  92118. }
  92119. }
  92120. }
  92121. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92122. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92123. };
  92124. /**
  92125. * Setup the ground to receive the mirror texture.
  92126. */
  92127. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92128. if (this._groundMaterial) {
  92129. this._groundMaterial.reflectionTexture = this._groundMirror;
  92130. this._groundMaterial.reflectionFresnel = true;
  92131. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92132. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92133. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92134. }
  92135. };
  92136. /**
  92137. * Setup the skybox according to the specified options.
  92138. */
  92139. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92140. var _this = this;
  92141. if (!this._skybox) {
  92142. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92143. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92144. }
  92145. this._skybox.parent = this._rootMesh;
  92146. };
  92147. /**
  92148. * Setup the skybox material according to the specified options.
  92149. */
  92150. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92151. if (!this._skybox) {
  92152. return;
  92153. }
  92154. if (!this._skyboxMaterial) {
  92155. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92156. }
  92157. this._skyboxMaterial.useRGBColor = false;
  92158. this._skyboxMaterial.primaryLevel = 1;
  92159. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92160. this._skyboxMaterial.secondaryLevel = 0;
  92161. this._skyboxMaterial.tertiaryLevel = 0;
  92162. this._skyboxMaterial.enableNoise = true;
  92163. this._skybox.material = this._skyboxMaterial;
  92164. };
  92165. /**
  92166. * Setup the skybox reflection texture according to the specified options.
  92167. */
  92168. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92169. if (!this._skyboxMaterial) {
  92170. return;
  92171. }
  92172. if (this._skyboxTexture) {
  92173. return;
  92174. }
  92175. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92176. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92177. return;
  92178. }
  92179. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92180. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92181. this._skyboxTexture.gammaSpace = false;
  92182. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92183. };
  92184. /**
  92185. * Dispose all the elements created by the Helper.
  92186. */
  92187. EnvironmentHelper.prototype.dispose = function () {
  92188. if (this._groundMaterial) {
  92189. this._groundMaterial.dispose(true, true);
  92190. }
  92191. if (this._skyboxMaterial) {
  92192. this._skyboxMaterial.dispose(true, true);
  92193. }
  92194. this._rootMesh.dispose(false);
  92195. };
  92196. /**
  92197. * Default ground texture URL.
  92198. */
  92199. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92200. /**
  92201. * Default skybox texture URL.
  92202. */
  92203. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92204. /**
  92205. * Default environment texture URL.
  92206. */
  92207. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92208. return EnvironmentHelper;
  92209. }());
  92210. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92211. })(BABYLON || (BABYLON = {}));
  92212. //# sourceMappingURL=babylon.environmentHelper.js.map
  92213. "use strict";
  92214. var BABYLON;
  92215. (function (BABYLON) {
  92216. /**
  92217. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92218. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92219. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92220. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92221. */
  92222. var VideoDome = /** @class */ (function (_super) {
  92223. __extends(VideoDome, _super);
  92224. /**
  92225. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92226. * @param name Element's name, child elements will append suffixes for their own names.
  92227. * @param urlsOrVideo
  92228. * @param options An object containing optional or exposed sub element properties:
  92229. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92230. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92231. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92232. * @param options **loop=true** Automatically loop video on end.
  92233. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92234. */
  92235. function VideoDome(name, urlsOrVideo, options, scene) {
  92236. var _this = _super.call(this, name, scene) || this;
  92237. // set defaults and manage values
  92238. name = name || "videoDome";
  92239. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92240. options.clickToPlay = Boolean(options.clickToPlay);
  92241. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92242. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92243. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92244. // create
  92245. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92246. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92247. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92248. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92249. flat: false,
  92250. radius: options.size,
  92251. subdivisions: options.resolution,
  92252. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92253. }, scene);
  92254. // configure material
  92255. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92256. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92257. material.reflectionTexture = _this._videoTexture;
  92258. material.useEquirectangularFOV = true;
  92259. material.fovMultiplier = 1.0;
  92260. // configure mesh
  92261. _this._mesh.material = material;
  92262. _this._mesh.parent = _this;
  92263. // optional configuration
  92264. if (options.clickToPlay) {
  92265. scene.onPointerUp = function () {
  92266. _this._videoTexture.video.play();
  92267. };
  92268. }
  92269. return _this;
  92270. }
  92271. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92272. /**
  92273. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92274. * Also see the options.resolution property.
  92275. */
  92276. get: function () {
  92277. return this._material.fovMultiplier;
  92278. },
  92279. set: function (value) {
  92280. this._material.fovMultiplier = value;
  92281. },
  92282. enumerable: true,
  92283. configurable: true
  92284. });
  92285. /**
  92286. * Releases resources associated with this node.
  92287. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92288. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92289. */
  92290. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92291. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92292. this._videoTexture.dispose();
  92293. this._mesh.dispose();
  92294. this._material.dispose();
  92295. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92296. };
  92297. return VideoDome;
  92298. }(BABYLON.Node));
  92299. BABYLON.VideoDome = VideoDome;
  92300. })(BABYLON || (BABYLON = {}));
  92301. //# sourceMappingURL=babylon.videoDome.js.map
  92302. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\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=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb);\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=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\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\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#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\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\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h/height;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 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);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\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 vec3 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.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\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{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  92303. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\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 computeShadowWithPoissonSamplingCube(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 computeShadowWithPoissonSampling(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#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(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#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,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#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  92304. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92305. globalObject["BABYLON"] = BABYLON
  92306. return BABYLON;
  92307. });
  92308. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16)))
  92309. /***/ }),
  92310. /* 1 */
  92311. /***/ (function(module, exports, __webpack_require__) {
  92312. "use strict";
  92313. Object.defineProperty(exports, "__esModule", { value: true });
  92314. var babylonjs_1 = __webpack_require__(0);
  92315. var helper_1 = __webpack_require__(2);
  92316. var HTMLMapper = (function () {
  92317. function HTMLMapper() {
  92318. }
  92319. HTMLMapper.prototype.map = function (element) {
  92320. var config = {};
  92321. var _loop_1 = function (attrIdx) {
  92322. var attr = element.attributes.item(attrIdx);
  92323. var split = attr.nodeName.split('.');
  92324. split.reduce(function (currentConfig, key, idx) {
  92325. var camelKey = helper_1.kebabToCamel(key);
  92326. if (idx === split.length - 1) {
  92327. var val = attr.nodeValue;
  92328. if (val === "true") {
  92329. val = true;
  92330. }
  92331. else if (val === "false") {
  92332. val = false;
  92333. }
  92334. else {
  92335. var isnum = /^\d+$/.test(val);
  92336. if (isnum) {
  92337. var number = parseFloat(val);
  92338. if (!isNaN(number)) {
  92339. val = number;
  92340. }
  92341. }
  92342. }
  92343. currentConfig[camelKey] = val;
  92344. }
  92345. else {
  92346. currentConfig[camelKey] = currentConfig[camelKey] || {};
  92347. }
  92348. return currentConfig[camelKey];
  92349. }, config);
  92350. };
  92351. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  92352. _loop_1(attrIdx);
  92353. }
  92354. return config;
  92355. };
  92356. return HTMLMapper;
  92357. }());
  92358. var JSONMapper = (function () {
  92359. function JSONMapper() {
  92360. }
  92361. JSONMapper.prototype.map = function (rawSource) {
  92362. return JSON.parse(rawSource);
  92363. };
  92364. return JSONMapper;
  92365. }());
  92366. var DOMMapper = (function () {
  92367. function DOMMapper() {
  92368. }
  92369. DOMMapper.prototype.map = function (baseElement) {
  92370. var htmlMapper = new HTMLMapper();
  92371. var config = htmlMapper.map(baseElement);
  92372. var traverseChildren = function (element, partConfig) {
  92373. var children = element.children;
  92374. if (children.length) {
  92375. for (var i = 0; i < children.length; ++i) {
  92376. var item = children.item(i);
  92377. var configMapped = htmlMapper.map(item);
  92378. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  92379. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  92380. partConfig[key] = [];
  92381. }
  92382. else {
  92383. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  92384. partConfig.push(configMapped);
  92385. }
  92386. else if (partConfig[key]) {
  92387. element.setAttribute('array', 'true');
  92388. var oldItem = partConfig[key];
  92389. partConfig = [oldItem, configMapped];
  92390. }
  92391. else {
  92392. partConfig[key] = configMapped;
  92393. }
  92394. }
  92395. traverseChildren(item, partConfig[key] || configMapped);
  92396. }
  92397. }
  92398. return partConfig;
  92399. };
  92400. traverseChildren(baseElement, config);
  92401. return config;
  92402. };
  92403. return DOMMapper;
  92404. }());
  92405. var MapperManager = (function () {
  92406. function MapperManager() {
  92407. this.mappers = {
  92408. "html": new HTMLMapper(),
  92409. "json": new JSONMapper(),
  92410. "dom": new DOMMapper()
  92411. };
  92412. }
  92413. MapperManager.prototype.getMapper = function (type) {
  92414. if (!this.mappers[type]) {
  92415. babylonjs_1.Tools.Error("No mapper defined for " + type);
  92416. }
  92417. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  92418. };
  92419. MapperManager.prototype.registerMapper = function (type, mapper) {
  92420. this.mappers[type] = mapper;
  92421. };
  92422. MapperManager.DefaultMapper = 'json';
  92423. return MapperManager;
  92424. }());
  92425. exports.MapperManager = MapperManager;
  92426. exports.mapperManager = new MapperManager();
  92427. /***/ }),
  92428. /* 2 */
  92429. /***/ (function(module, exports, __webpack_require__) {
  92430. "use strict";
  92431. Object.defineProperty(exports, "__esModule", { value: true });
  92432. function isUrl(urlToCheck) {
  92433. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  92434. return true;
  92435. }
  92436. return false;
  92437. }
  92438. exports.isUrl = isUrl;
  92439. function kebabToCamel(s) {
  92440. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  92441. }
  92442. exports.kebabToCamel = kebabToCamel;
  92443. function camelToKebab(str) {
  92444. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  92445. }
  92446. exports.camelToKebab = camelToKebab;
  92447. /***/ }),
  92448. /* 3 */
  92449. /***/ (function(module, exports, __webpack_require__) {
  92450. "use strict";
  92451. Object.defineProperty(exports, "__esModule", { value: true });
  92452. var babylonjs_1 = __webpack_require__(0);
  92453. var ViewerManager = (function () {
  92454. function ViewerManager() {
  92455. this.viewers = {};
  92456. this.onViewerAddedObservable = new babylonjs_1.Observable();
  92457. }
  92458. ViewerManager.prototype.addViewer = function (viewer) {
  92459. this.viewers[viewer.getBaseId()] = viewer;
  92460. this._onViewerAdded(viewer);
  92461. };
  92462. ViewerManager.prototype.getViewerById = function (id) {
  92463. return this.viewers[id];
  92464. };
  92465. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  92466. for (var id in this.viewers) {
  92467. if (this.viewers[id].containerElement === element) {
  92468. return this.getViewerById(id);
  92469. }
  92470. }
  92471. };
  92472. ViewerManager.prototype.getViewerPromiseById = function (id) {
  92473. var _this = this;
  92474. return new Promise(function (resolve, reject) {
  92475. var localViewer = _this.getViewerById(id);
  92476. if (localViewer) {
  92477. return resolve(localViewer);
  92478. }
  92479. var viewerFunction = function (viewer) {
  92480. if (viewer.getBaseId() === id) {
  92481. resolve(viewer);
  92482. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  92483. }
  92484. };
  92485. _this.onViewerAddedObservable.add(viewerFunction);
  92486. });
  92487. };
  92488. ViewerManager.prototype._onViewerAdded = function (viewer) {
  92489. this.onViewerAdded && this.onViewerAdded(viewer);
  92490. this.onViewerAddedObservable.notifyObservers(viewer);
  92491. };
  92492. return ViewerManager;
  92493. }());
  92494. exports.ViewerManager = ViewerManager;
  92495. exports.viewerManager = new ViewerManager();
  92496. /***/ }),
  92497. /* 4 */
  92498. /***/ (function(module, exports, __webpack_require__) {
  92499. "use strict";
  92500. var __extends = (this && this.__extends) || (function () {
  92501. var extendStatics = Object.setPrototypeOf ||
  92502. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  92503. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  92504. return function (d, b) {
  92505. extendStatics(d, b);
  92506. function __() { this.constructor = d; }
  92507. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  92508. };
  92509. })();
  92510. Object.defineProperty(exports, "__esModule", { value: true });
  92511. var viewer_1 = __webpack_require__(5);
  92512. var babylonjs_1 = __webpack_require__(0);
  92513. var DefaultViewer = (function (_super) {
  92514. __extends(DefaultViewer, _super);
  92515. function DefaultViewer(containerElement, initialConfiguration) {
  92516. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  92517. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  92518. _this.containerElement = containerElement;
  92519. _this.onModelLoaded = function (model) {
  92520. var hideLoadingDelay = 500;
  92521. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  92522. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  92523. }
  92524. setTimeout(function () {
  92525. _this.hideLoadingScreen();
  92526. }, hideLoadingDelay);
  92527. return;
  92528. };
  92529. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  92530. return _this;
  92531. }
  92532. DefaultViewer.prototype.initScene = function () {
  92533. var _this = this;
  92534. return _super.prototype.initScene.call(this).then(function () {
  92535. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  92536. return _this.scene;
  92537. });
  92538. };
  92539. DefaultViewer.prototype.onTemplatesLoaded = function () {
  92540. var _this = this;
  92541. this.showLoadingScreen();
  92542. this.initNavbar();
  92543. var closeButton = document.getElementById('close-button');
  92544. if (closeButton) {
  92545. closeButton.addEventListener('pointerdown', function () {
  92546. _this.hideOverlayScreen();
  92547. });
  92548. }
  92549. return _super.prototype.onTemplatesLoaded.call(this);
  92550. };
  92551. DefaultViewer.prototype.initNavbar = function () {
  92552. var navbar = this.templateManager.getTemplate('navBar');
  92553. if (navbar) {
  92554. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  92555. var navbarShown_1 = true;
  92556. var timeoutCancel_1;
  92557. var triggerNavbar = function (show, evt) {
  92558. if (show === void 0) { show = false; }
  92559. if (!navbar || evt.button > 0)
  92560. return;
  92561. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  92562. if (show === navbarShown_1)
  92563. return;
  92564. if (show) {
  92565. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  92566. navbarShown_1 = show;
  92567. }
  92568. else {
  92569. var visibilityTimeout = 2000;
  92570. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  92571. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  92572. }
  92573. timeoutCancel_1 = setTimeout(function () {
  92574. if (navbar) {
  92575. navbar.parent.style.bottom = '-' + navbarHeight_1;
  92576. }
  92577. navbarShown_1 = show;
  92578. }, visibilityTimeout);
  92579. }
  92580. };
  92581. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  92582. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  92583. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  92584. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  92585. var viewerTemplate = this.templateManager.getTemplate('viewer');
  92586. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  92587. var triggerFullscren = function (eventData) {
  92588. if (viewerElement_1) {
  92589. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  92590. if (!fullscreenElement) {
  92591. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  92592. requestFullScreen.call(viewerElement_1);
  92593. }
  92594. else {
  92595. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  92596. exitFullscreen.call(document);
  92597. }
  92598. }
  92599. };
  92600. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  92601. }
  92602. };
  92603. DefaultViewer.prototype.prepareContainerElement = function () {
  92604. this.containerElement.style.position = 'relative';
  92605. this.containerElement.style.display = 'flex';
  92606. };
  92607. DefaultViewer.prototype.configureModel = function (modelConfiguration, model) {
  92608. _super.prototype.configureModel.call(this, modelConfiguration, model);
  92609. var navbar = this.templateManager.getTemplate('navBar');
  92610. if (!navbar)
  92611. return;
  92612. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  92613. if (metadataContainer) {
  92614. if (modelConfiguration.title !== undefined) {
  92615. var element = metadataContainer.querySelector('span.model-title');
  92616. if (element) {
  92617. element.innerHTML = modelConfiguration.title;
  92618. }
  92619. }
  92620. if (modelConfiguration.subtitle !== undefined) {
  92621. var element = metadataContainer.querySelector('span.model-subtitle');
  92622. if (element) {
  92623. element.innerHTML = modelConfiguration.subtitle;
  92624. }
  92625. }
  92626. if (modelConfiguration.thumbnail !== undefined) {
  92627. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  92628. }
  92629. }
  92630. };
  92631. DefaultViewer.prototype.loadModel = function (model) {
  92632. var _this = this;
  92633. if (model === void 0) { model = this.configuration.model; }
  92634. this.showLoadingScreen();
  92635. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  92636. console.log(error);
  92637. _this.hideLoadingScreen();
  92638. _this.showOverlayScreen('error');
  92639. return Promise.reject(error);
  92640. });
  92641. };
  92642. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  92643. var _this = this;
  92644. var template = this.templateManager.getTemplate('overlay');
  92645. if (!template)
  92646. return Promise.resolve('Overlay template not found');
  92647. return template.show((function (template) {
  92648. var canvasRect = _this.containerElement.getBoundingClientRect();
  92649. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  92650. template.parent.style.display = 'flex';
  92651. template.parent.style.width = canvasRect.width + "px";
  92652. template.parent.style.height = canvasRect.height + "px";
  92653. template.parent.style.opacity = "1";
  92654. var subTemplate = _this.templateManager.getTemplate(subScreen);
  92655. if (!subTemplate) {
  92656. return Promise.reject(subScreen + ' template not found');
  92657. }
  92658. return subTemplate.show((function (template) {
  92659. template.parent.style.display = 'flex';
  92660. return Promise.resolve(template);
  92661. }));
  92662. }));
  92663. };
  92664. DefaultViewer.prototype.hideOverlayScreen = function () {
  92665. var template = this.templateManager.getTemplate('overlay');
  92666. if (!template)
  92667. return Promise.resolve('Overlay template not found');
  92668. return template.hide((function (template) {
  92669. template.parent.style.opacity = "0";
  92670. var onTransitionEnd = function () {
  92671. template.parent.removeEventListener("transitionend", onTransitionEnd);
  92672. template.parent.style.display = 'none';
  92673. };
  92674. template.parent.addEventListener("transitionend", onTransitionEnd);
  92675. var overlays = template.parent.querySelectorAll('.overlay');
  92676. if (overlays) {
  92677. for (var i = 0; i < overlays.length; ++i) {
  92678. var htmlElement = overlays.item(i);
  92679. htmlElement.style.display = 'none';
  92680. }
  92681. }
  92682. return Promise.resolve(template);
  92683. }));
  92684. };
  92685. DefaultViewer.prototype.showLoadingScreen = function () {
  92686. var _this = this;
  92687. var template = this.templateManager.getTemplate('loadingScreen');
  92688. if (!template)
  92689. return Promise.resolve('Loading Screen template not found');
  92690. return template.show((function (template) {
  92691. var canvasRect = _this.containerElement.getBoundingClientRect();
  92692. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  92693. template.parent.style.display = 'flex';
  92694. template.parent.style.width = canvasRect.width + "px";
  92695. template.parent.style.height = canvasRect.height + "px";
  92696. template.parent.style.opacity = "1";
  92697. template.parent.style.backgroundColor = "black";
  92698. return Promise.resolve(template);
  92699. }));
  92700. };
  92701. DefaultViewer.prototype.hideLoadingScreen = function () {
  92702. var template = this.templateManager.getTemplate('loadingScreen');
  92703. if (!template)
  92704. return Promise.resolve('Loading Screen template not found');
  92705. return template.hide((function (template) {
  92706. template.parent.style.opacity = "0";
  92707. var onTransitionEnd = function () {
  92708. template.parent.removeEventListener("transitionend", onTransitionEnd);
  92709. template.parent.style.display = 'none';
  92710. };
  92711. template.parent.addEventListener("transitionend", onTransitionEnd);
  92712. return Promise.resolve(template);
  92713. }));
  92714. };
  92715. DefaultViewer.prototype.configureLights = function (lightsConfiguration, model) {
  92716. var _this = this;
  92717. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  92718. _super.prototype.configureLights.call(this, lightsConfiguration, model);
  92719. if (this.configuration.lab && this.configuration.lab.flashlight) {
  92720. var pointerPosition = BABYLON.Vector3.Zero();
  92721. var lightTarget_1;
  92722. var angle = 0.5;
  92723. var exponent = Math.PI / 2;
  92724. if (typeof this.configuration.lab.flashlight === "object") {
  92725. exponent = this.configuration.lab.flashlight.exponent || exponent;
  92726. angle = this.configuration.lab.flashlight.angle || angle;
  92727. }
  92728. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  92729. if (typeof this.configuration.lab.flashlight === "object") {
  92730. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  92731. if (this.configuration.lab.flashlight.diffuse) {
  92732. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  92733. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  92734. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  92735. }
  92736. if (this.configuration.lab.flashlight.specular) {
  92737. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  92738. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  92739. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  92740. }
  92741. }
  92742. this.scene.constantlyUpdateMeshUnderPointer = true;
  92743. this.scene.onPointerObservable.add(function (eventData, eventState) {
  92744. if (eventData.type === 4 && eventData.pickInfo) {
  92745. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  92746. }
  92747. else {
  92748. lightTarget_1 = undefined;
  92749. }
  92750. });
  92751. var updateFlashlightFunction = function () {
  92752. if (_this.camera && flashlight) {
  92753. flashlight.position.copyFrom(_this.camera.position);
  92754. if (lightTarget_1) {
  92755. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  92756. }
  92757. }
  92758. };
  92759. this.scene.registerBeforeRender(updateFlashlightFunction);
  92760. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  92761. }
  92762. };
  92763. return DefaultViewer;
  92764. }(viewer_1.AbstractViewer));
  92765. exports.DefaultViewer = DefaultViewer;
  92766. /***/ }),
  92767. /* 5 */
  92768. /***/ (function(module, exports, __webpack_require__) {
  92769. "use strict";
  92770. Object.defineProperty(exports, "__esModule", { value: true });
  92771. var viewerManager_1 = __webpack_require__(3);
  92772. var templateManager_1 = __webpack_require__(19);
  92773. var loader_1 = __webpack_require__(22);
  92774. var babylonjs_1 = __webpack_require__(0);
  92775. var deepmerge = __webpack_require__(13);
  92776. var viewerModel_1 = __webpack_require__(30);
  92777. var AbstractViewer = (function () {
  92778. function AbstractViewer(containerElement, initialConfiguration) {
  92779. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  92780. var _this = this;
  92781. this.containerElement = containerElement;
  92782. this.resize = function () {
  92783. if (!_this.isCanvasInDOM()) {
  92784. return;
  92785. }
  92786. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  92787. return;
  92788. }
  92789. _this.engine.resize();
  92790. };
  92791. this.render = function () {
  92792. _this.scene && _this.scene.activeCamera && _this.scene.render();
  92793. };
  92794. if (containerElement.id) {
  92795. this.baseId = containerElement.id;
  92796. }
  92797. else {
  92798. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  92799. }
  92800. this.onSceneInitObservable = new babylonjs_1.Observable();
  92801. this.onEngineInitObservable = new babylonjs_1.Observable();
  92802. this.onModelLoadedObservable = new babylonjs_1.Observable();
  92803. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  92804. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  92805. this.onInitDoneObservable = new babylonjs_1.Observable();
  92806. this.onLoaderInitObservable = new babylonjs_1.Observable();
  92807. this.registeredOnBeforerenderFunctions = [];
  92808. this.models = [];
  92809. viewerManager_1.viewerManager.addViewer(this);
  92810. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  92811. this.prepareContainerElement();
  92812. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  92813. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  92814. if (_this.configuration.observers) {
  92815. _this.configureObservers(_this.configuration.observers);
  92816. }
  92817. var templateConfiguration = _this.configuration.templates || {};
  92818. _this.templateManager.initTemplate(templateConfiguration);
  92819. _this.templateManager.onAllLoaded.add(function () {
  92820. var canvas = _this.templateManager.getCanvas();
  92821. if (canvas) {
  92822. _this.canvas = canvas;
  92823. }
  92824. _this._onTemplateLoaded();
  92825. });
  92826. });
  92827. }
  92828. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  92829. get: function () {
  92830. return this._hdrSupport;
  92831. },
  92832. enumerable: true,
  92833. configurable: true
  92834. });
  92835. AbstractViewer.prototype.getBaseId = function () {
  92836. return this.baseId;
  92837. };
  92838. AbstractViewer.prototype.isCanvasInDOM = function () {
  92839. return !!this.canvas && !!this.canvas.parentElement;
  92840. };
  92841. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  92842. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  92843. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  92844. if (newConfiguration.scene) {
  92845. this.configureScene(newConfiguration.scene);
  92846. }
  92847. if (newConfiguration.optimizer) {
  92848. this.configureOptimizer(newConfiguration.optimizer);
  92849. }
  92850. if (newConfiguration.observers) {
  92851. this.configureObservers(newConfiguration.observers);
  92852. }
  92853. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  92854. this.configureModel(newConfiguration.model);
  92855. }
  92856. if (newConfiguration.lights) {
  92857. this.configureLights(newConfiguration.lights);
  92858. }
  92859. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  92860. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  92861. }
  92862. if (newConfiguration.camera) {
  92863. this.configureCamera(newConfiguration.camera);
  92864. }
  92865. };
  92866. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  92867. if (!skyboxConifguration && !groundConfiguration) {
  92868. if (this.environmentHelper) {
  92869. this.environmentHelper.dispose();
  92870. delete this.environmentHelper;
  92871. }
  92872. ;
  92873. return Promise.resolve(this.scene);
  92874. }
  92875. var options = {
  92876. createGround: !!groundConfiguration,
  92877. createSkybox: !!skyboxConifguration,
  92878. setupImageProcessing: false
  92879. };
  92880. if (groundConfiguration) {
  92881. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  92882. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  92883. if (groundSize) {
  92884. options.groundSize = groundSize;
  92885. }
  92886. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  92887. if (groundConfig.shadowLevel !== undefined) {
  92888. options.groundShadowLevel = groundConfig.shadowLevel;
  92889. }
  92890. options.enableGroundMirror = !!groundConfig.mirror;
  92891. if (groundConfig.texture) {
  92892. options.groundTexture = groundConfig.texture;
  92893. }
  92894. if (groundConfig.color) {
  92895. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  92896. }
  92897. if (groundConfig.opacity !== undefined) {
  92898. options.groundOpacity = groundConfig.opacity;
  92899. }
  92900. if (groundConfig.mirror) {
  92901. options.enableGroundMirror = true;
  92902. if (typeof groundConfig.mirror === "object") {
  92903. if (groundConfig.mirror.amount !== undefined)
  92904. options.groundMirrorAmount = groundConfig.mirror.amount;
  92905. if (groundConfig.mirror.sizeRatio !== undefined)
  92906. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  92907. if (groundConfig.mirror.blurKernel !== undefined)
  92908. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  92909. if (groundConfig.mirror.fresnelWeight !== undefined)
  92910. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  92911. if (groundConfig.mirror.fallOffDistance !== undefined)
  92912. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  92913. if (this.defaultPipelineTextureType !== undefined)
  92914. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  92915. }
  92916. }
  92917. }
  92918. var postInitSkyboxMaterial = false;
  92919. if (skyboxConifguration) {
  92920. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  92921. if (conf.material && conf.material.imageProcessingConfiguration) {
  92922. options.setupImageProcessing = false;
  92923. }
  92924. var skyboxSize = conf.scale;
  92925. if (skyboxSize) {
  92926. options.skyboxSize = skyboxSize;
  92927. }
  92928. options.sizeAuto = !options.skyboxSize;
  92929. if (conf.color) {
  92930. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  92931. }
  92932. if (conf.cubeTexture && conf.cubeTexture.url) {
  92933. if (typeof conf.cubeTexture.url === "string") {
  92934. options.skyboxTexture = conf.cubeTexture.url;
  92935. }
  92936. else {
  92937. postInitSkyboxMaterial = true;
  92938. }
  92939. }
  92940. if (conf.material && conf.material.imageProcessingConfiguration) {
  92941. postInitSkyboxMaterial = true;
  92942. }
  92943. }
  92944. options.setupImageProcessing = false;
  92945. if (!this.environmentHelper) {
  92946. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  92947. }
  92948. else {
  92949. var scene = this.environmentHelper.rootMesh.getScene();
  92950. if (scene !== this.scene) {
  92951. this.environmentHelper.dispose();
  92952. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  92953. }
  92954. else {
  92955. this.environmentHelper.updateOptions(options);
  92956. }
  92957. }
  92958. if (postInitSkyboxMaterial) {
  92959. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  92960. if (skyboxMaterial) {
  92961. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  92962. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  92963. }
  92964. }
  92965. }
  92966. };
  92967. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  92968. if (!this.scene) {
  92969. return;
  92970. }
  92971. if (sceneConfig.debug) {
  92972. this.scene.debugLayer.show();
  92973. }
  92974. else {
  92975. if (this.scene.debugLayer.isVisible()) {
  92976. this.scene.debugLayer.hide();
  92977. }
  92978. }
  92979. if (sceneConfig.clearColor) {
  92980. var cc = sceneConfig.clearColor;
  92981. var oldcc = this.scene.clearColor;
  92982. if (cc.r !== undefined) {
  92983. oldcc.r = cc.r;
  92984. }
  92985. if (cc.g !== undefined) {
  92986. oldcc.g = cc.g;
  92987. }
  92988. if (cc.b !== undefined) {
  92989. oldcc.b = cc.b;
  92990. }
  92991. if (cc.a !== undefined) {
  92992. oldcc.a = cc.a;
  92993. }
  92994. }
  92995. if (sceneConfig.imageProcessingConfiguration) {
  92996. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  92997. }
  92998. if (sceneConfig.environmentTexture) {
  92999. if (this.scene.environmentTexture) {
  93000. this.scene.environmentTexture.dispose();
  93001. }
  93002. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  93003. this.scene.environmentTexture = environmentTexture;
  93004. }
  93005. if (sceneConfig.autoRotate) {
  93006. this.camera.useAutoRotationBehavior = true;
  93007. }
  93008. };
  93009. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  93010. if (typeof optimizerConfig === 'boolean') {
  93011. if (this.sceneOptimizer) {
  93012. this.sceneOptimizer.stop();
  93013. this.sceneOptimizer.dispose();
  93014. delete this.sceneOptimizer;
  93015. }
  93016. if (optimizerConfig) {
  93017. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  93018. this.sceneOptimizer.start();
  93019. }
  93020. }
  93021. else {
  93022. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  93023. if (optimizerConfig.degradation) {
  93024. switch (optimizerConfig.degradation) {
  93025. case "low":
  93026. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  93027. break;
  93028. case "moderate":
  93029. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  93030. break;
  93031. case "hight":
  93032. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  93033. break;
  93034. }
  93035. }
  93036. if (this.sceneOptimizer) {
  93037. this.sceneOptimizer.stop();
  93038. this.sceneOptimizer.dispose();
  93039. }
  93040. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  93041. this.sceneOptimizer.start();
  93042. }
  93043. };
  93044. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  93045. if (observersConfiguration.onEngineInit) {
  93046. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  93047. }
  93048. else {
  93049. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  93050. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  93051. }
  93052. }
  93053. if (observersConfiguration.onSceneInit) {
  93054. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  93055. }
  93056. else {
  93057. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  93058. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  93059. }
  93060. }
  93061. if (observersConfiguration.onModelLoaded) {
  93062. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  93063. }
  93064. else {
  93065. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  93066. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  93067. }
  93068. }
  93069. };
  93070. AbstractViewer.prototype.configureCamera = function (cameraConfig, model) {
  93071. var _this = this;
  93072. var focusMeshes = model ? model.meshes : this.scene.meshes;
  93073. if (!this.scene.activeCamera) {
  93074. this.scene.createDefaultCamera(true, true, true);
  93075. this.camera = this.scene.activeCamera;
  93076. }
  93077. if (cameraConfig.position) {
  93078. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  93079. }
  93080. if (cameraConfig.rotation) {
  93081. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  93082. }
  93083. this.extendClassWithConfig(this.camera, cameraConfig);
  93084. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  93085. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  93086. if (cameraConfig.behaviors) {
  93087. for (var name_1 in cameraConfig.behaviors) {
  93088. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  93089. }
  93090. }
  93091. ;
  93092. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  93093. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  93094. });
  93095. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  93096. var sceneDiagonalLenght = sceneDiagonal.length();
  93097. if (isFinite(sceneDiagonalLenght))
  93098. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  93099. };
  93100. AbstractViewer.prototype.configureLights = function (lightsConfiguration, model) {
  93101. var _this = this;
  93102. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  93103. var focusMeshes = model ? model.meshes : this.scene.meshes;
  93104. if (!Object.keys(lightsConfiguration).length)
  93105. return;
  93106. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  93107. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  93108. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  93109. lightsAvailable.forEach(function (lName) {
  93110. if (lightsToConfigure.indexOf(lName) === -1) {
  93111. _this.scene.getLightByName(lName).dispose();
  93112. }
  93113. });
  93114. }
  93115. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  93116. var lightConfig = { type: 0 };
  93117. if (typeof lightsConfiguration[name] === 'object') {
  93118. lightConfig = lightsConfiguration[name];
  93119. }
  93120. lightConfig.name = name;
  93121. var light;
  93122. if (lightsAvailable.indexOf(name) === -1) {
  93123. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  93124. if (!constructor)
  93125. return;
  93126. light = constructor();
  93127. }
  93128. else {
  93129. light = _this.scene.getLightByName(name);
  93130. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  93131. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  93132. light.dispose();
  93133. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  93134. if (!constructor)
  93135. return;
  93136. light = constructor();
  93137. }
  93138. }
  93139. if (lightsConfiguration[name] === false) {
  93140. light.dispose();
  93141. return;
  93142. }
  93143. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  93144. light.setEnabled(enabled);
  93145. _this.extendClassWithConfig(light, lightConfig);
  93146. if (light instanceof babylonjs_1.ShadowLight) {
  93147. if (lightConfig.target) {
  93148. if (light.setDirectionToTarget) {
  93149. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  93150. light.setDirectionToTarget(target);
  93151. }
  93152. }
  93153. else if (lightConfig.direction) {
  93154. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  93155. light.direction = direction;
  93156. }
  93157. var shadowGenerator = light.getShadowGenerator();
  93158. if (lightConfig.shadowEnabled && _this.maxShadows) {
  93159. if (!shadowGenerator) {
  93160. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  93161. }
  93162. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  93163. var shadownMap = shadowGenerator.getShadowMap();
  93164. if (!shadownMap)
  93165. return;
  93166. var renderList = shadownMap.renderList;
  93167. for (var index = 0; index < focusMeshes.length; index++) {
  93168. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  93169. renderList && renderList.push(focusMeshes[index]);
  93170. }
  93171. }
  93172. }
  93173. else if (shadowGenerator) {
  93174. shadowGenerator.dispose();
  93175. }
  93176. }
  93177. });
  93178. };
  93179. AbstractViewer.prototype.configureModel = function (modelConfiguration, model) {
  93180. var focusMeshes = model ? model.meshes : this.scene.meshes;
  93181. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  93182. var updateMeshesWithNoParent = function (variable, value, param) {
  93183. meshesWithNoParent.forEach(function (mesh) {
  93184. if (param) {
  93185. mesh[variable][param] = value;
  93186. }
  93187. else {
  93188. mesh[variable] = value;
  93189. }
  93190. });
  93191. };
  93192. var updateXYZ = function (variable, configValues) {
  93193. if (configValues.x !== undefined) {
  93194. updateMeshesWithNoParent(variable, configValues.x, 'x');
  93195. }
  93196. if (configValues.y !== undefined) {
  93197. updateMeshesWithNoParent(variable, configValues.y, 'y');
  93198. }
  93199. if (configValues.z !== undefined) {
  93200. updateMeshesWithNoParent(variable, configValues.z, 'z');
  93201. }
  93202. if (configValues.w !== undefined) {
  93203. updateMeshesWithNoParent(variable, configValues.w, 'w');
  93204. }
  93205. };
  93206. if (modelConfiguration.position) {
  93207. updateXYZ('position', modelConfiguration.position);
  93208. }
  93209. if (modelConfiguration.rotation) {
  93210. if (modelConfiguration.rotation.w) {
  93211. meshesWithNoParent.forEach(function (mesh) {
  93212. if (!mesh.rotationQuaternion) {
  93213. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  93214. }
  93215. });
  93216. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  93217. }
  93218. else {
  93219. updateXYZ('rotation', modelConfiguration.rotation);
  93220. }
  93221. }
  93222. if (modelConfiguration.scaling) {
  93223. updateXYZ('scaling', modelConfiguration.scaling);
  93224. }
  93225. if (modelConfiguration.castShadow) {
  93226. focusMeshes.forEach(function (mesh) {
  93227. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  93228. });
  93229. }
  93230. if (modelConfiguration.normalize) {
  93231. var center = false;
  93232. var unitSize = false;
  93233. var parentIndex = void 0;
  93234. if (modelConfiguration.normalize === true) {
  93235. center = true;
  93236. unitSize = true;
  93237. parentIndex = 0;
  93238. }
  93239. else {
  93240. center = !!modelConfiguration.normalize.center;
  93241. unitSize = !!modelConfiguration.normalize.unitSize;
  93242. parentIndex = modelConfiguration.normalize.parentIndex;
  93243. }
  93244. var meshesToNormalize = [];
  93245. if (parentIndex !== undefined) {
  93246. meshesToNormalize.push(focusMeshes[parentIndex]);
  93247. }
  93248. else {
  93249. meshesToNormalize = meshesWithNoParent;
  93250. }
  93251. if (unitSize) {
  93252. meshesToNormalize.forEach(function (mesh) {
  93253. mesh.normalizeToUnitCube(true);
  93254. mesh.computeWorldMatrix(true);
  93255. });
  93256. }
  93257. if (center) {
  93258. meshesToNormalize.forEach(function (mesh) {
  93259. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  93260. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  93261. var halfSizeVec = sizeVec.scale(0.5);
  93262. var center = boundingInfo.min.add(halfSizeVec);
  93263. mesh.position = center.scale(-1);
  93264. mesh.position.y += halfSizeVec.y;
  93265. mesh.computeWorldMatrix(true);
  93266. });
  93267. }
  93268. }
  93269. };
  93270. AbstractViewer.prototype.dispose = function () {
  93271. window.removeEventListener('resize', this.resize);
  93272. if (this.sceneOptimizer) {
  93273. this.sceneOptimizer.stop();
  93274. this.sceneOptimizer.dispose();
  93275. }
  93276. if (this.scene.activeCamera) {
  93277. this.scene.activeCamera.detachControl(this.canvas);
  93278. }
  93279. this.scene.dispose();
  93280. this.engine.dispose();
  93281. this.templateManager.dispose();
  93282. };
  93283. AbstractViewer.prototype.onTemplatesLoaded = function () {
  93284. return Promise.resolve(this);
  93285. };
  93286. AbstractViewer.prototype._onTemplateLoaded = function () {
  93287. var _this = this;
  93288. return this.onTemplatesLoaded().then(function () {
  93289. var autoLoadModel = !!_this.configuration.model;
  93290. return _this.initEngine().then(function (engine) {
  93291. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  93292. }).then(function () {
  93293. if (autoLoadModel) {
  93294. return _this.loadModel().then(function () { return _this.scene; });
  93295. }
  93296. else {
  93297. return _this.scene || _this.initScene();
  93298. }
  93299. }).then(function (scene) {
  93300. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  93301. }).then(function () {
  93302. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  93303. });
  93304. });
  93305. };
  93306. AbstractViewer.prototype.initEngine = function () {
  93307. this.injectCustomShaders();
  93308. var canvasElement = this.templateManager.getCanvas();
  93309. if (!canvasElement) {
  93310. return Promise.reject('Canvas element not found!');
  93311. }
  93312. var config = this.configuration.engine || {};
  93313. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  93314. babylonjs_1.Database.IDBStorageEnabled = false;
  93315. if (!config.disableResize) {
  93316. window.addEventListener('resize', this.resize);
  93317. }
  93318. this.engine.runRenderLoop(this.render);
  93319. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  93320. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  93321. this.engine.setHardwareScalingLevel(scale);
  93322. }
  93323. this.handleHardwareLimitations();
  93324. return Promise.resolve(this.engine);
  93325. };
  93326. AbstractViewer.prototype.initScene = function () {
  93327. if (this.scene) {
  93328. this.scene.dispose();
  93329. }
  93330. this.scene = new babylonjs_1.Scene(this.engine);
  93331. this.scene.createDefaultLight(true);
  93332. if (this.configuration.scene) {
  93333. this.configureScene(this.configuration.scene);
  93334. if (this.configuration.optimizer) {
  93335. this.configureOptimizer(this.configuration.optimizer);
  93336. }
  93337. }
  93338. return Promise.resolve(this.scene);
  93339. };
  93340. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  93341. var _this = this;
  93342. if (modelConfig === void 0) { modelConfig = this.configuration.model; }
  93343. if (clearScene === void 0) { clearScene = true; }
  93344. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  93345. if (!modelUrl) {
  93346. return Promise.reject("no model configuration found");
  93347. }
  93348. if (this.isLoading) {
  93349. return Promise.reject("sanother model is curently being loaded.");
  93350. }
  93351. this.isLoading = true;
  93352. if ((typeof modelConfig === 'string')) {
  93353. if (this.configuration.model && typeof this.configuration.model === 'object') {
  93354. this.configuration.model.url = modelConfig;
  93355. }
  93356. }
  93357. else {
  93358. if (this.configuration.model) {
  93359. deepmerge(this.configuration.model, modelConfig);
  93360. }
  93361. else {
  93362. this.configuration.model = modelConfig;
  93363. }
  93364. }
  93365. return Promise.resolve(this.scene).then(function (scene) {
  93366. if (!scene)
  93367. return _this.initScene();
  93368. if (clearScene) {
  93369. _this.models.forEach(function (m) { return m.dispose(); });
  93370. _this.models.length = 0;
  93371. }
  93372. return scene;
  93373. }).then(function () {
  93374. return new Promise(function (resolve, reject) {
  93375. var model = new viewerModel_1.ViewerModel(_this.configuration.model, _this.scene);
  93376. _this.models.push(model);
  93377. _this.lastUsedLoader = model.loader;
  93378. model.onLoadedObservable.add(function (model) {
  93379. resolve(model);
  93380. });
  93381. model.onLoadErrorObservable.add(function (errorObject) {
  93382. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject).then(function () {
  93383. reject(errorObject.exception);
  93384. });
  93385. });
  93386. model.onLoadProgressObservable.add(function (progressEvent) {
  93387. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  93388. });
  93389. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  93390. });
  93391. }).then(function (model) {
  93392. return _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  93393. .then(function () {
  93394. _this.configureModel(_this.configuration.model || modelConfig, model);
  93395. _this.configureLights(_this.configuration.lights);
  93396. if (_this.configuration.camera) {
  93397. _this.configureCamera(_this.configuration.camera, model);
  93398. }
  93399. return _this.initEnvironment(model);
  93400. }).then(function () {
  93401. _this.isLoading = false;
  93402. return model;
  93403. });
  93404. });
  93405. };
  93406. AbstractViewer.prototype.initEnvironment = function (model) {
  93407. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  93408. return Promise.resolve(this.scene);
  93409. };
  93410. AbstractViewer.prototype.handleHardwareLimitations = function () {
  93411. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  93412. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  93413. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  93414. this.maxShadows = 0;
  93415. }
  93416. else {
  93417. this.maxShadows = 3;
  93418. }
  93419. var caps = this.engine.getCaps();
  93420. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  93421. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  93422. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  93423. if (linearHalfFloatTargets) {
  93424. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  93425. this.shadowGeneratorBias = 0.002;
  93426. }
  93427. else if (linearFloatTargets) {
  93428. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  93429. this.shadowGeneratorBias = 0.001;
  93430. }
  93431. else {
  93432. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  93433. this.shadowGeneratorBias = 0.001;
  93434. }
  93435. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  93436. };
  93437. AbstractViewer.prototype.injectCustomShaders = function () {
  93438. var customShaders = this.configuration.customShaders;
  93439. if (!customShaders) {
  93440. return;
  93441. }
  93442. if (customShaders.shaders) {
  93443. Object.keys(customShaders.shaders).forEach(function (key) {
  93444. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  93445. });
  93446. }
  93447. if (customShaders.includes) {
  93448. Object.keys(customShaders.includes).forEach(function (key) {
  93449. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  93450. });
  93451. }
  93452. };
  93453. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  93454. var _this = this;
  93455. if (!config)
  93456. return;
  93457. Object.keys(config).forEach(function (key) {
  93458. if (key in object && typeof object[key] !== 'function') {
  93459. if (typeof object[key] === 'object') {
  93460. _this.extendClassWithConfig(object[key], config[key]);
  93461. }
  93462. else {
  93463. if (config[key] !== undefined) {
  93464. object[key] = config[key];
  93465. }
  93466. }
  93467. }
  93468. });
  93469. };
  93470. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  93471. var behavior;
  93472. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  93473. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  93474. switch (type) {
  93475. case 0:
  93476. this.camera.useAutoRotationBehavior = true;
  93477. behavior = this.camera.autoRotationBehavior;
  93478. break;
  93479. case 1:
  93480. this.camera.useBouncingBehavior = true;
  93481. behavior = this.camera.bouncingBehavior;
  93482. break;
  93483. case 2:
  93484. this.camera.useFramingBehavior = true;
  93485. behavior = this.camera.framingBehavior;
  93486. break;
  93487. default:
  93488. behavior = null;
  93489. break;
  93490. }
  93491. if (behavior) {
  93492. if (typeof behaviorConfig === "object") {
  93493. this.extendClassWithConfig(behavior, behaviorConfig);
  93494. }
  93495. }
  93496. switch (type) {
  93497. case 0:
  93498. break;
  93499. case 1:
  93500. break;
  93501. case 2:
  93502. if (config.zoomOnBoundingInfo) {
  93503. var meshes = payload;
  93504. var bounding = meshes[0].getHierarchyBoundingVectors();
  93505. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  93506. }
  93507. break;
  93508. }
  93509. };
  93510. return AbstractViewer;
  93511. }());
  93512. exports.AbstractViewer = AbstractViewer;
  93513. /***/ }),
  93514. /* 6 */
  93515. /***/ (function(module, exports) {
  93516. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  93517. /***/ }),
  93518. /* 7 */
  93519. /***/ (function(module, exports) {
  93520. 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}}>";
  93521. /***/ }),
  93522. /* 8 */
  93523. /***/ (function(module, exports) {
  93524. 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=="
  93525. /***/ }),
  93526. /* 9 */
  93527. /***/ (function(module, exports) {
  93528. 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>";
  93529. /***/ }),
  93530. /* 10 */
  93531. /***/ (function(module, exports) {
  93532. 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>";
  93533. /***/ }),
  93534. /* 11 */
  93535. /***/ (function(module, exports) {
  93536. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  93537. /***/ }),
  93538. /* 12 */
  93539. /***/ (function(module, exports) {
  93540. module.exports = "Error loading the model";
  93541. /***/ }),
  93542. /* 13 */
  93543. /***/ (function(module, exports, __webpack_require__) {
  93544. (function (global, factory) {
  93545. true ? module.exports = factory() :
  93546. typeof define === 'function' && define.amd ? define(factory) :
  93547. (global.deepmerge = factory());
  93548. }(this, (function () { 'use strict';
  93549. var isMergeableObject = function isMergeableObject(value) {
  93550. return isNonNullObject(value)
  93551. && !isSpecial(value)
  93552. };
  93553. function isNonNullObject(value) {
  93554. return !!value && typeof value === 'object'
  93555. }
  93556. function isSpecial(value) {
  93557. var stringValue = Object.prototype.toString.call(value);
  93558. return stringValue === '[object RegExp]'
  93559. || stringValue === '[object Date]'
  93560. || isReactElement(value)
  93561. }
  93562. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  93563. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  93564. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  93565. function isReactElement(value) {
  93566. return value.$$typeof === REACT_ELEMENT_TYPE
  93567. }
  93568. function emptyTarget(val) {
  93569. return Array.isArray(val) ? [] : {}
  93570. }
  93571. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  93572. var clone = !optionsArgument || optionsArgument.clone !== false;
  93573. return (clone && isMergeableObject(value))
  93574. ? deepmerge(emptyTarget(value), value, optionsArgument)
  93575. : value
  93576. }
  93577. function defaultArrayMerge(target, source, optionsArgument) {
  93578. return target.concat(source).map(function(element) {
  93579. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  93580. })
  93581. }
  93582. function mergeObject(target, source, optionsArgument) {
  93583. var destination = {};
  93584. if (isMergeableObject(target)) {
  93585. Object.keys(target).forEach(function(key) {
  93586. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  93587. });
  93588. }
  93589. Object.keys(source).forEach(function(key) {
  93590. if (!isMergeableObject(source[key]) || !target[key]) {
  93591. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  93592. } else {
  93593. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  93594. }
  93595. });
  93596. return destination
  93597. }
  93598. function deepmerge(target, source, optionsArgument) {
  93599. var sourceIsArray = Array.isArray(source);
  93600. var targetIsArray = Array.isArray(target);
  93601. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  93602. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  93603. if (!sourceAndTargetTypesMatch) {
  93604. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  93605. } else if (sourceIsArray) {
  93606. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  93607. return arrayMerge(target, source, optionsArgument)
  93608. } else {
  93609. return mergeObject(target, source, optionsArgument)
  93610. }
  93611. }
  93612. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  93613. if (!Array.isArray(array)) {
  93614. throw new Error('first argument should be an array')
  93615. }
  93616. return array.reduce(function(prev, next) {
  93617. return deepmerge(prev, next, optionsArgument)
  93618. }, {})
  93619. };
  93620. var deepmerge_1 = deepmerge;
  93621. return deepmerge_1;
  93622. })));
  93623. /***/ }),
  93624. /* 14 */
  93625. /***/ (function(module, exports, __webpack_require__) {
  93626. module.exports = __webpack_require__(15);
  93627. /***/ }),
  93628. /* 15 */
  93629. /***/ (function(module, exports, __webpack_require__) {
  93630. "use strict";
  93631. Object.defineProperty(exports, "__esModule", { value: true });
  93632. var mappers_1 = __webpack_require__(1);
  93633. exports.mapperManager = mappers_1.mapperManager;
  93634. var viewerManager_1 = __webpack_require__(3);
  93635. exports.viewerManager = viewerManager_1.viewerManager;
  93636. var defaultViewer_1 = __webpack_require__(4);
  93637. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  93638. var viewer_1 = __webpack_require__(5);
  93639. exports.AbstractViewer = viewer_1.AbstractViewer;
  93640. var babylonjs_1 = __webpack_require__(0);
  93641. __webpack_require__(32);
  93642. __webpack_require__(33);
  93643. var initializer_1 = __webpack_require__(34);
  93644. exports.InitTags = initializer_1.InitTags;
  93645. babylonjs_1.PromisePolyfill.Apply();
  93646. exports.disableInit = false;
  93647. document.addEventListener("DOMContentLoaded", function (event) {
  93648. if (exports.disableInit)
  93649. return;
  93650. initializer_1.InitTags();
  93651. });
  93652. /***/ }),
  93653. /* 16 */
  93654. /***/ (function(module, exports) {
  93655. var g;
  93656. // This works in non-strict mode
  93657. g = (function() {
  93658. return this;
  93659. })();
  93660. try {
  93661. // This works if eval is allowed (see CSP)
  93662. g = g || Function("return this")() || (1,eval)("this");
  93663. } catch(e) {
  93664. // This works if the window reference is available
  93665. if(typeof window === "object")
  93666. g = window;
  93667. }
  93668. // g can still be undefined, but nothing to do about it...
  93669. // We return undefined, instead of nothing here, so it's
  93670. // easier to handle this case. if(!global) { ...}
  93671. module.exports = g;
  93672. /***/ }),
  93673. /* 17 */
  93674. /***/ (function(module, exports) {
  93675. module.exports = cannon;
  93676. /***/ }),
  93677. /* 18 */
  93678. /***/ (function(module, exports, __webpack_require__) {
  93679. /**
  93680. * from OimoPhysics DEV 1.1.0a AS3
  93681. * @author Saharan / http://el-ement.com/
  93682. *
  93683. * to Oimo.js 2015 JAVASCRIPT
  93684. * @author LoTh / http://lo-th.github.io/labs/
  93685. */
  93686. var OIMO = {
  93687. REVISION: "1.2",
  93688. // Global identification of next shape.
  93689. // This will be incremented every time a shape is created.
  93690. nextID: 0,
  93691. proxyID: 0,
  93692. // BroadPhase
  93693. BR_NULL: 0,
  93694. BR_BRUTE_FORCE: 1,
  93695. BR_SWEEP_AND_PRUNE: 2,
  93696. BR_BOUNDING_VOLUME_TREE: 3,
  93697. // body type
  93698. BODY_NULL: 0,
  93699. BODY_DYNAMIC: 1,
  93700. BODY_STATIC: 2,
  93701. // shape type
  93702. SHAPE_NULL: 0,
  93703. SHAPE_SPHERE: 1,
  93704. SHAPE_BOX: 2,
  93705. SHAPE_CYLINDER: 3,
  93706. SHAPE_TETRA: 4,
  93707. // joint type
  93708. JOINT_NULL: 0,
  93709. JOINT_DISTANCE: 1,
  93710. JOINT_BALL_AND_SOCKET: 2,
  93711. JOINT_HINGE: 3,
  93712. JOINT_WHEEL: 4,
  93713. JOINT_SLIDER: 5,
  93714. JOINT_PRISMATIC: 6,
  93715. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  93716. // scale all by 100 so object is between 10 to 10000 three unit.
  93717. WORLD_SCALE: 100,
  93718. INV_SCALE: 0.01,
  93719. // AABB aproximation
  93720. AABB_PROX: 0.005,
  93721. // Math function
  93722. sqrt: Math.sqrt,
  93723. abs: Math.abs,
  93724. floor: Math.floor,
  93725. cos: Math.cos,
  93726. sin: Math.sin,
  93727. acos: Math.acos,
  93728. asin: Math.asin,
  93729. atan2: Math.atan2,
  93730. round: Math.round,
  93731. pow: Math.pow,
  93732. max: Math.max,
  93733. min: Math.min,
  93734. random: Math.random,
  93735. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  93736. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  93737. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  93738. int: function (x) { return ~~x; },
  93739. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  93740. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  93741. degtorad: 0.0174532925199432957,
  93742. radtodeg: 57.295779513082320876,
  93743. PI: 3.141592653589793,
  93744. TwoPI: 6.283185307179586,
  93745. PI90: 1.570796326794896,
  93746. PI270: 4.712388980384689,
  93747. CustomError: null,
  93748. Error: function (Class, Msg) {
  93749. if (OIMO.CustomError == null) console.error(Class, Msg);
  93750. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  93751. }
  93752. };
  93753. var OIMO_ARRAY_TYPE;
  93754. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  93755. try {
  93756. (function (w) {
  93757. var perfNow;
  93758. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  93759. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  93760. var n = perfNowNames[i];
  93761. if (!!w['performance'][n]) {
  93762. perfNow = function () { return w['performance'][n]() };
  93763. break;
  93764. }
  93765. }
  93766. if (!perfNow) perfNow = Date.now;
  93767. //w.perfNow = perfNow;
  93768. OIMO.now = perfNow;
  93769. })(window);
  93770. } catch (e) { OIMO.now = function () { return 0; }; }
  93771. /**
  93772. * The class of physical computing world.
  93773. * You must be added to the world physical all computing objects
  93774. * @author saharan
  93775. * @author lo-th
  93776. */
  93777. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  93778. // The time between each step
  93779. this.timeStep = TimeStep || 0.01666; // 1/60;
  93780. // The number of iterations for constraint solvers.
  93781. this.numIterations = Iterations || 8;
  93782. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  93783. switch (BroadPhaseType || 2) {
  93784. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  93785. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  93786. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  93787. }
  93788. // This is the detailed information of the performance.
  93789. this.performance = null;
  93790. this.isNoStat = NoStat || false;
  93791. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  93792. // Whether the constraints randomizer is enabled or not.
  93793. this.enableRandomizer = true;
  93794. // The rigid body list
  93795. this.rigidBodies = null;
  93796. // number of rigid body
  93797. this.numRigidBodies = 0;
  93798. // The contact list
  93799. this.contacts = null;
  93800. this.unusedContacts = null;
  93801. // The number of contact
  93802. this.numContacts = 0;
  93803. // The number of contact points
  93804. this.numContactPoints = 0;
  93805. // The joint list
  93806. this.joints = null;
  93807. // The number of joints.
  93808. this.numJoints = 0;
  93809. // The number of simulation islands.
  93810. this.numIslands = 0;
  93811. // The gravity in the world.
  93812. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  93813. var numShapeTypes = 5;//4;//3;
  93814. this.detectors = [];
  93815. this.detectors.length = numShapeTypes;
  93816. var i = numShapeTypes;
  93817. while (i--) {
  93818. this.detectors[i] = [];
  93819. this.detectors[i].length = numShapeTypes;
  93820. }
  93821. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  93822. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  93823. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  93824. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  93825. // CYLINDER add
  93826. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  93827. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  93828. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  93829. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  93830. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  93831. // TETRA add
  93832. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  93833. this.randX = 65535;
  93834. this.randA = 98765;
  93835. this.randB = 123456789;
  93836. //this.maxIslandRigidBodies = 64;
  93837. this.islandRigidBodies = [];
  93838. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  93839. this.islandStack = [];
  93840. //this.islandStack.length = this.maxIslandRigidBodies;
  93841. //this.maxIslandConstraints = 128;
  93842. this.islandConstraints = [];
  93843. //this.islandConstraints.length = this.maxIslandConstraints;
  93844. };
  93845. OIMO.World.prototype = {
  93846. constructor: OIMO.World,
  93847. /**
  93848. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  93849. */
  93850. clear: function () {
  93851. this.randX = 65535;
  93852. while (this.joints !== null) {
  93853. this.removeJoint(this.joints);
  93854. }
  93855. while (this.contacts !== null) {
  93856. this.removeContact(this.contacts);
  93857. }
  93858. while (this.rigidBodies !== null) {
  93859. this.removeRigidBody(this.rigidBodies);
  93860. }
  93861. OIMO.nextID = 0;
  93862. OIMO.proxyID = 0;
  93863. },
  93864. /**
  93865. * I'll add a rigid body to the world.
  93866. * Rigid body that has been added will be the operands of each step.
  93867. * @param rigidBody Rigid body that you want to add
  93868. */
  93869. addRigidBody: function (rigidBody) {
  93870. if (rigidBody.parent) {
  93871. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  93872. }
  93873. rigidBody.parent = this;
  93874. rigidBody.awake();
  93875. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  93876. this.addShape(shape);
  93877. }
  93878. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  93879. this.rigidBodies = rigidBody;
  93880. this.numRigidBodies++;
  93881. },
  93882. /**
  93883. * I will remove the rigid body from the world.
  93884. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  93885. * @param rigidBody Rigid body to be removed
  93886. */
  93887. removeRigidBody: function (rigidBody) {
  93888. var remove = rigidBody;
  93889. if (remove.parent !== this) return;
  93890. remove.awake();
  93891. var js = remove.jointLink;
  93892. while (js != null) {
  93893. var joint = js.joint;
  93894. js = js.next;
  93895. this.removeJoint(joint);
  93896. }
  93897. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  93898. this.removeShape(shape);
  93899. }
  93900. var prev = remove.prev;
  93901. var next = remove.next;
  93902. if (prev !== null) prev.next = next;
  93903. if (next !== null) next.prev = prev;
  93904. if (this.rigidBodies == remove) this.rigidBodies = next;
  93905. remove.prev = null;
  93906. remove.next = null;
  93907. remove.parent = null;
  93908. this.numRigidBodies--;
  93909. },
  93910. getByName: function (name) {
  93911. var result = null;
  93912. var body = this.rigidBodies;
  93913. while (body !== null) {
  93914. if (body.name !== " " && body.name === name) result = body;
  93915. body = body.next;
  93916. }
  93917. var joint = this.joints;
  93918. while (joint !== null) {
  93919. if (joint.name !== "" && joint.name === name) result = joint;
  93920. joint = joint.next;
  93921. }
  93922. return result;
  93923. },
  93924. /**
  93925. * I'll add a shape to the world..
  93926. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  93927. * Shape will be added to the world automatically, please do not call from outside this method.
  93928. * @param shape Shape you want to add
  93929. */
  93930. addShape: function (shape) {
  93931. if (!shape.parent || !shape.parent.parent) {
  93932. OIMO.Error("World", "It is not possible to be added alone to shape world");
  93933. }
  93934. shape.proxy = this.broadPhase.createProxy(shape);
  93935. shape.updateProxy();
  93936. this.broadPhase.addProxy(shape.proxy);
  93937. },
  93938. /**
  93939. * I will remove the shape from the world.
  93940. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  93941. * Shape will be added to the world automatically, please do not call from outside this method.
  93942. * @param shape Shape you want to delete
  93943. */
  93944. removeShape: function (shape) {
  93945. this.broadPhase.removeProxy(shape.proxy);
  93946. shape.proxy = null;
  93947. },
  93948. /**
  93949. * I'll add a joint to the world.
  93950. * Joint that has been added will be the operands of each step.
  93951. * @param shape Joint to be added
  93952. */
  93953. addJoint: function (joint) {
  93954. if (joint.parent) {
  93955. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  93956. }
  93957. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  93958. this.joints = joint;
  93959. joint.parent = this;
  93960. this.numJoints++;
  93961. joint.awake();
  93962. joint.attach();
  93963. },
  93964. /**
  93965. * I will remove the joint from the world.
  93966. * Joint that has been added will be the operands of each step.
  93967. * @param shape Joint to be deleted
  93968. */
  93969. removeJoint: function (joint) {
  93970. var remove = joint;
  93971. var prev = remove.prev;
  93972. var next = remove.next;
  93973. if (prev !== null) prev.next = next;
  93974. if (next !== null) next.prev = prev;
  93975. if (this.joints == remove) this.joints = next;
  93976. remove.prev = null;
  93977. remove.next = null;
  93978. this.numJoints--;
  93979. remove.awake();
  93980. remove.detach();
  93981. remove.parent = null;
  93982. },
  93983. worldscale: function (scale) {
  93984. OIMO.WORLD_SCALE = scale || 100;
  93985. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  93986. },
  93987. addContact: function (s1, s2) {
  93988. var newContact;
  93989. if (this.unusedContacts !== null) {
  93990. newContact = this.unusedContacts;
  93991. this.unusedContacts = this.unusedContacts.next;
  93992. } else {
  93993. newContact = new OIMO.Contact();
  93994. }
  93995. newContact.attach(s1, s2);
  93996. newContact.detector = this.detectors[s1.type][s2.type];
  93997. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  93998. this.contacts = newContact;
  93999. this.numContacts++;
  94000. },
  94001. removeContact: function (contact) {
  94002. var prev = contact.prev;
  94003. var next = contact.next;
  94004. if (next) next.prev = prev;
  94005. if (prev) prev.next = next;
  94006. if (this.contacts == contact) this.contacts = next;
  94007. contact.prev = null;
  94008. contact.next = null;
  94009. contact.detach();
  94010. contact.next = this.unusedContacts;
  94011. this.unusedContacts = contact;
  94012. this.numContacts--;
  94013. },
  94014. checkContact: function (name1, name2) {
  94015. var n1, n2;
  94016. var contact = this.contacts;
  94017. while (contact !== null) {
  94018. n1 = contact.body1.name || ' ';
  94019. n2 = contact.body2.name || ' ';
  94020. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  94021. else contact = contact.next;
  94022. }
  94023. return false;
  94024. },
  94025. callSleep: function (body) {
  94026. if (!body.allowSleep) return false;
  94027. if (body.linearVelocity.lengthSq() > 0.04) return false;
  94028. if (body.angularVelocity.lengthSq() > 0.25) return false;
  94029. return true;
  94030. },
  94031. /**
  94032. * I will proceed only time step seconds time of World.
  94033. */
  94034. step: function () {
  94035. var time0, time1, time2, time3;
  94036. var stat = !this.isNoStat ? true : false;
  94037. if (stat) time0 = OIMO.now();
  94038. var body = this.rigidBodies;
  94039. while (body !== null) {
  94040. body.addedToIsland = false;
  94041. if (body.sleeping) {
  94042. if (
  94043. body.linearVelocity.testZero() ||
  94044. body.angularVelocity.testZero() ||
  94045. body.position.testDiff(body.sleepPosition) ||
  94046. body.orientation.testDiff(body.sleepOrientation)
  94047. ) body.awake(); // awake the body
  94048. }
  94049. body = body.next;
  94050. }
  94051. //------------------------------------------------------
  94052. // UPDATE CONTACT
  94053. //------------------------------------------------------
  94054. // broad phase
  94055. if (stat) time1 = OIMO.now();
  94056. this.broadPhase.detectPairs();
  94057. var pairs = this.broadPhase.pairs;
  94058. var i = this.broadPhase.numPairs;
  94059. //do{
  94060. while (i--) {
  94061. //for(var i=0, l=numPairs; i<l; i++){
  94062. var pair = pairs[i];
  94063. var s1;
  94064. var s2;
  94065. if (pair.shape1.id < pair.shape2.id) {
  94066. s1 = pair.shape1;
  94067. s2 = pair.shape2;
  94068. } else {
  94069. s1 = pair.shape2;
  94070. s2 = pair.shape1;
  94071. }
  94072. var link;
  94073. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  94074. else link = s2.contactLink;
  94075. var exists = false;
  94076. while (link) {
  94077. var contact = link.contact;
  94078. if (contact.shape1 == s1 && contact.shape2 == s2) {
  94079. contact.persisting = true;
  94080. exists = true;// contact already exists
  94081. break;
  94082. }
  94083. link = link.next;
  94084. }
  94085. if (!exists) {
  94086. this.addContact(s1, s2);
  94087. }
  94088. }// while(i-- >0);
  94089. if (stat) {
  94090. time2 = OIMO.now();
  94091. this.performance.broadPhaseTime = time2 - time1;
  94092. }
  94093. // update & narrow phase
  94094. this.numContactPoints = 0;
  94095. contact = this.contacts;
  94096. while (contact !== null) {
  94097. if (!contact.persisting) {
  94098. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  94099. /*var aabb1=contact.shape1.aabb;
  94100. var aabb2=contact.shape2.aabb;
  94101. if(
  94102. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  94103. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  94104. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  94105. ){*/
  94106. var next = contact.next;
  94107. this.removeContact(contact);
  94108. contact = next;
  94109. continue;
  94110. }
  94111. }
  94112. var b1 = contact.body1;
  94113. var b2 = contact.body2;
  94114. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  94115. contact.updateManifold();
  94116. }
  94117. this.numContactPoints += contact.manifold.numPoints;
  94118. contact.persisting = false;
  94119. contact.constraint.addedToIsland = false;
  94120. contact = contact.next;
  94121. }
  94122. if (stat) {
  94123. time3 = OIMO.now();
  94124. this.performance.narrowPhaseTime = time3 - time2;
  94125. }
  94126. //------------------------------------------------------
  94127. // SOLVE ISLANDS
  94128. //------------------------------------------------------
  94129. var invTimeStep = 1 / this.timeStep;
  94130. //var body;
  94131. var joint;
  94132. var constraint;
  94133. //var num;
  94134. for (joint = this.joints; joint !== null; joint = joint.next) {
  94135. joint.addedToIsland = false;
  94136. }
  94137. // clear old island array
  94138. this.islandRigidBodies = [];
  94139. this.islandConstraints = [];
  94140. this.islandStack = [];
  94141. // expand island buffers
  94142. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  94143. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  94144. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  94145. this.islandRigidBodies=[];
  94146. this.islandStack=[];
  94147. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  94148. this.islandStack.length = this.maxIslandRigidBodies;
  94149. }
  94150. var numConstraints=this.numJoints+this.numContacts;
  94151. if(this.maxIslandConstraints<numConstraints){
  94152. this.maxIslandConstraints=numConstraints<<1;
  94153. //this.maxIslandConstraints=numConstraints*2;
  94154. this.islandConstraints=[];
  94155. this.islandConstraints.length = this.maxIslandConstraints;
  94156. }*/
  94157. time1 = OIMO.now();
  94158. this.numIslands = 0;
  94159. // build and solve simulation islands
  94160. for (var base = this.rigidBodies; base !== null; base = base.next) {
  94161. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  94162. if (base.isLonely()) {// update single body
  94163. if (base.isDynamic) {
  94164. base.linearVelocity.addTime(this.gravity, this.timeStep);
  94165. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  94166. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  94167. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  94168. }
  94169. if (this.callSleep(base)) {
  94170. base.sleepTime += this.timeStep;
  94171. if (base.sleepTime > 0.5) base.sleep();
  94172. else base.updatePosition(this.timeStep);
  94173. } else {
  94174. base.sleepTime = 0;
  94175. base.updatePosition(this.timeStep);
  94176. }
  94177. this.numIslands++;
  94178. continue;
  94179. }
  94180. var islandNumRigidBodies = 0;
  94181. var islandNumConstraints = 0;
  94182. var stackCount = 1;
  94183. // add rigid body to stack
  94184. this.islandStack[0] = base;
  94185. base.addedToIsland = true;
  94186. // build an island
  94187. do {
  94188. // get rigid body from stack
  94189. body = this.islandStack[--stackCount];
  94190. this.islandStack[stackCount] = null;
  94191. body.sleeping = false;
  94192. // add rigid body to the island
  94193. this.islandRigidBodies[islandNumRigidBodies++] = body;
  94194. if (body.isStatic) continue;
  94195. // search connections
  94196. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  94197. var contact = cs.contact;
  94198. constraint = contact.constraint;
  94199. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  94200. // add constraint to the island
  94201. this.islandConstraints[islandNumConstraints++] = constraint;
  94202. constraint.addedToIsland = true;
  94203. var next = cs.body;
  94204. if (next.addedToIsland) continue;
  94205. // add rigid body to stack
  94206. this.islandStack[stackCount++] = next;
  94207. next.addedToIsland = true;
  94208. }
  94209. for (var js = body.jointLink; js !== null; js = js.next) {
  94210. constraint = js.joint;
  94211. if (constraint.addedToIsland) continue;// ignore
  94212. // add constraint to the island
  94213. this.islandConstraints[islandNumConstraints++] = constraint;
  94214. constraint.addedToIsland = true;
  94215. next = js.body;
  94216. if (next.addedToIsland || !next.isDynamic) continue;
  94217. // add rigid body to stack
  94218. this.islandStack[stackCount++] = next;
  94219. next.addedToIsland = true;
  94220. }
  94221. } while (stackCount != 0);
  94222. // update velocities
  94223. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  94224. /*var gx=this.gravity.x*this.timeStep;
  94225. var gy=this.gravity.y*this.timeStep;
  94226. var gz=this.gravity.z*this.timeStep;*/
  94227. var j = islandNumRigidBodies;
  94228. while (j--) {
  94229. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  94230. body = this.islandRigidBodies[j];
  94231. if (body.isDynamic) {
  94232. body.linearVelocity.addEqual(gVel);
  94233. /*body.linearVelocity.x+=gx;
  94234. body.linearVelocity.y+=gy;
  94235. body.linearVelocity.z+=gz;*/
  94236. }
  94237. }
  94238. // randomizing order
  94239. if (this.enableRandomizer) {
  94240. //for(var j=1, l=islandNumConstraints; j<l; j++){
  94241. j = islandNumConstraints;
  94242. while (j--) {
  94243. if (j !== 0) {
  94244. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  94245. constraint = this.islandConstraints[j];
  94246. this.islandConstraints[j] = this.islandConstraints[swap];
  94247. this.islandConstraints[swap] = constraint;
  94248. }
  94249. }
  94250. }
  94251. // solve contraints
  94252. j = islandNumConstraints;
  94253. while (j--) {
  94254. //for(j=0, l=islandNumConstraints; j<l; j++){
  94255. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  94256. }
  94257. var k = this.numIterations;
  94258. while (k--) {
  94259. //for(var k=0, l=this.numIterations; k<l; k++){
  94260. j = islandNumConstraints;
  94261. while (j--) {
  94262. //for(j=0, m=islandNumConstraints; j<m; j++){
  94263. this.islandConstraints[j].solve();// main-solve
  94264. }
  94265. }
  94266. j = islandNumConstraints;
  94267. while (j--) {
  94268. //for(j=0, l=islandNumConstraints; j<l; j++){
  94269. this.islandConstraints[j].postSolve();// post-solve
  94270. this.islandConstraints[j] = null;// gc
  94271. }
  94272. // sleeping check
  94273. var sleepTime = 10;
  94274. j = islandNumRigidBodies;
  94275. while (j--) {
  94276. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  94277. body = this.islandRigidBodies[j];
  94278. if (this.callSleep(body)) {
  94279. body.sleepTime += this.timeStep;
  94280. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  94281. } else {
  94282. body.sleepTime = 0;
  94283. sleepTime = 0;
  94284. continue;
  94285. }
  94286. }
  94287. if (sleepTime > 0.5) {
  94288. // sleep the island
  94289. j = islandNumRigidBodies;
  94290. while (j--) {
  94291. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  94292. this.islandRigidBodies[j].sleep();
  94293. this.islandRigidBodies[j] = null;// gc
  94294. }
  94295. } else {
  94296. // update positions
  94297. j = islandNumRigidBodies;
  94298. while (j--) {
  94299. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  94300. this.islandRigidBodies[j].updatePosition(this.timeStep);
  94301. this.islandRigidBodies[j] = null;// gc
  94302. }
  94303. }
  94304. this.numIslands++;
  94305. }
  94306. if (stat) {
  94307. time2 = OIMO.now();
  94308. this.performance.solvingTime = time2 - time1;
  94309. //------------------------------------------------------
  94310. // END SIMULATION
  94311. //------------------------------------------------------
  94312. time2 = OIMO.now();
  94313. // fps update
  94314. this.performance.upfps();
  94315. this.performance.totalTime = time2 - time0;
  94316. }
  94317. }
  94318. }
  94319. /**
  94320. * The class of rigid body.
  94321. * Rigid body has the shape of a single or multiple collision processing,
  94322. * I can set the parameters individually.
  94323. * @author saharan
  94324. */
  94325. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  94326. this.name = " ";
  94327. // The maximum number of shapes that can be added to a one rigid.
  94328. this.MAX_SHAPES = 64;//64;
  94329. this.prev = null;
  94330. this.next = null;
  94331. // I represent the kind of rigid body.
  94332. // Please do not change from the outside this variable.
  94333. // If you want to change the type of rigid body, always
  94334. // Please specify the type you want to set the arguments of setupMass method.
  94335. this.type = OIMO.BODY_NULL;
  94336. this.massInfo = new OIMO.MassInfo();
  94337. // It is the world coordinate of the center of gravity.
  94338. this.position = new OIMO.Vec3(x, y, z);
  94339. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  94340. this.newPosition = new OIMO.Vec3();
  94341. this.controlPos = false;
  94342. this.newOrientation = new OIMO.Quat();
  94343. this.newRotation = new OIMO.Vec3();
  94344. this.currentRotation = new OIMO.Vec3();
  94345. this.controlRot = false;
  94346. this.controlRotInTime = false;
  94347. // Is the translational velocity.
  94348. this.linearVelocity = new OIMO.Vec3();
  94349. // Is the angular velocity.
  94350. this.angularVelocity = new OIMO.Vec3();
  94351. // return matrix for three.js
  94352. this.matrix = new OIMO.Mat44();
  94353. //--------------------------------------------
  94354. // Please do not change from the outside this variables.
  94355. //--------------------------------------------
  94356. // It is a world that rigid body has been added.
  94357. this.parent = null;
  94358. this.contactLink = null;
  94359. this.numContacts = 0;
  94360. // An array of shapes that are included in the rigid body.
  94361. this.shapes = null;
  94362. // The number of shapes that are included in the rigid body.
  94363. this.numShapes = 0;
  94364. // It is the link array of joint that is connected to the rigid body.
  94365. this.jointLink = null;
  94366. // The number of joints that are connected to the rigid body.
  94367. this.numJoints = 0;
  94368. // It is the world coordinate of the center of gravity in the sleep just before.
  94369. this.sleepPosition = new OIMO.Vec3();
  94370. // It is a quaternion that represents the attitude of sleep just before.
  94371. this.sleepOrientation = new OIMO.Quat();
  94372. // I will show this rigid body to determine whether it is a rigid body static.
  94373. this.isStatic = false;
  94374. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  94375. this.isDynamic = false;
  94376. // It is a rotation matrix representing the orientation.
  94377. this.rotation = new OIMO.Mat33();
  94378. //--------------------------------------------
  94379. // It will be recalculated automatically from the shape, which is included.
  94380. //--------------------------------------------
  94381. // This is the weight.
  94382. this.mass = NaN;
  94383. // It is the reciprocal of the mass.
  94384. this.inverseMass = NaN;
  94385. // It is the inverse of the inertia tensor in the world system.
  94386. this.inverseInertia = new OIMO.Mat33();
  94387. // It is the inertia tensor in the initial state.
  94388. this.localInertia = new OIMO.Mat33();
  94389. // It is the inverse of the inertia tensor in the initial state.
  94390. this.inverseLocalInertia = new OIMO.Mat33();
  94391. // I indicates rigid body whether it has been added to the simulation Island.
  94392. this.addedToIsland = false;
  94393. // It shows how to sleep rigid body.
  94394. this.allowSleep = true;
  94395. // This is the time from when the rigid body at rest.
  94396. this.sleepTime = 0;
  94397. // I shows rigid body to determine whether it is a sleep state.
  94398. this.sleeping = false;
  94399. };
  94400. OIMO.RigidBody.prototype = {
  94401. constructor: OIMO.RigidBody,
  94402. /**
  94403. * I'll add a shape to rigid body.
  94404. * If you add a shape, please call the setupMass method to step up to the start of the next.
  94405. * @param shape shape to Add
  94406. */
  94407. addShape: function (shape) {
  94408. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  94409. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  94410. this.shapes = shape;
  94411. shape.parent = this;
  94412. if (this.parent) this.parent.addShape(shape);
  94413. this.numShapes++;
  94414. },
  94415. /**
  94416. * I will delete the shape from the rigid body.
  94417. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  94418. * @param shape shape to Delete
  94419. */
  94420. removeShape: function (shape) {
  94421. var remove = shape;
  94422. if (remove.parent != this) return;
  94423. var prev = remove.prev;
  94424. var next = remove.next;
  94425. if (prev != null) prev.next = next;
  94426. if (next != null) next.prev = prev;
  94427. if (this.shapes == remove) this.shapes = next;
  94428. remove.prev = null;
  94429. remove.next = null;
  94430. remove.parent = null;
  94431. if (this.parent) this.parent.removeShape(remove);
  94432. this.numShapes--;
  94433. },
  94434. remove: function () {
  94435. this.dispose();
  94436. },
  94437. dispose: function () {
  94438. this.parent.removeRigidBody(this);
  94439. },
  94440. checkContact: function (name) {
  94441. this.parent.checkContact(this.name, name);
  94442. },
  94443. /**
  94444. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  94445. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  94446. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  94447. * the rigid body's position will be adjusted to the center of gravity.
  94448. * @param type
  94449. * @param adjustPosition
  94450. */
  94451. setupMass: function (type, AdjustPosition) {
  94452. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  94453. this.type = type || OIMO.BODY_DYNAMIC;
  94454. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  94455. this.isStatic = this.type == OIMO.BODY_STATIC;
  94456. this.mass = 0;
  94457. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  94458. var te = this.localInertia.elements;
  94459. //
  94460. var tmpM = new OIMO.Mat33();
  94461. var tmpV = new OIMO.Vec3();
  94462. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94463. shape.calculateMassInfo(this.massInfo);
  94464. var shapeMass = this.massInfo.mass;
  94465. var relX = shape.relativePosition.x;
  94466. var relY = shape.relativePosition.y;
  94467. var relZ = shape.relativePosition.z;
  94468. /*tmpV.x+=relX*shapeMass;
  94469. tmpV.y+=relY*shapeMass;
  94470. tmpV.z+=relZ*shapeMass;*/
  94471. tmpV.addScale(shape.relativePosition, shapeMass);
  94472. this.mass += shapeMass;
  94473. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  94474. this.localInertia.addEqual(tmpM);
  94475. // add offset inertia
  94476. te[0] += shapeMass * (relY * relY + relZ * relZ);
  94477. te[4] += shapeMass * (relX * relX + relZ * relZ);
  94478. te[8] += shapeMass * (relX * relX + relY * relY);
  94479. var xy = shapeMass * relX * relY;
  94480. var yz = shapeMass * relY * relZ;
  94481. var zx = shapeMass * relZ * relX;
  94482. te[1] -= xy;
  94483. te[3] -= xy;
  94484. te[2] -= yz;
  94485. te[6] -= yz;
  94486. te[5] -= zx;
  94487. te[7] -= zx;
  94488. }
  94489. this.inverseMass = 1 / this.mass;
  94490. tmpV.scaleEqual(this.inverseMass);
  94491. if (adjustPosition) {
  94492. this.position.addEqual(tmpV);
  94493. for (shape = this.shapes; shape != null; shape = shape.next) {
  94494. shape.relativePosition.subEqual(tmpV);
  94495. }
  94496. // subtract offset inertia
  94497. relX = tmpV.x;
  94498. relY = tmpV.y;
  94499. relZ = tmpV.z;
  94500. //var te = this.localInertia.elements;
  94501. te[0] -= this.mass * (relY * relY + relZ * relZ);
  94502. te[4] -= this.mass * (relX * relX + relZ * relZ);
  94503. te[8] -= this.mass * (relX * relX + relY * relY);
  94504. xy = this.mass * relX * relY;
  94505. yz = this.mass * relY * relZ;
  94506. zx = this.mass * relZ * relX;
  94507. te[1] += xy;
  94508. te[3] += xy;
  94509. te[2] += yz;
  94510. te[6] += yz;
  94511. te[5] += zx;
  94512. te[7] += zx;
  94513. }
  94514. this.inverseLocalInertia.invert(this.localInertia);
  94515. if (this.type == OIMO.BODY_STATIC) {
  94516. this.inverseMass = 0;
  94517. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  94518. }
  94519. this.syncShapes();
  94520. this.awake();
  94521. },
  94522. /**
  94523. * Awake the rigid body.
  94524. */
  94525. awake: function () {
  94526. if (!this.allowSleep || !this.sleeping) return;
  94527. this.sleeping = false;
  94528. this.sleepTime = 0;
  94529. // awake connected constraints
  94530. var cs = this.contactLink;
  94531. while (cs != null) {
  94532. cs.body.sleepTime = 0;
  94533. cs.body.sleeping = false;
  94534. cs = cs.next;
  94535. }
  94536. var js = this.jointLink;
  94537. while (js != null) {
  94538. js.body.sleepTime = 0;
  94539. js.body.sleeping = false;
  94540. js = js.next;
  94541. }
  94542. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94543. shape.updateProxy();
  94544. }
  94545. },
  94546. /**
  94547. * Sleep the rigid body.
  94548. */
  94549. sleep: function () {
  94550. if (!this.allowSleep || this.sleeping) return;
  94551. this.linearVelocity.set(0, 0, 0);
  94552. this.angularVelocity.set(0, 0, 0);
  94553. this.sleepPosition.copy(this.position);
  94554. this.sleepOrientation.copy(this.orientation);
  94555. /*this.linearVelocity.x=0;
  94556. this.linearVelocity.y=0;
  94557. this.linearVelocity.z=0;
  94558. this.angularVelocity.x=0;
  94559. this.angularVelocity.y=0;
  94560. this.angularVelocity.z=0;
  94561. this.sleepPosition.x=this.position.x;
  94562. this.sleepPosition.y=this.position.y;
  94563. this.sleepPosition.z=this.position.z;*/
  94564. /*this.sleepOrientation.s=this.orientation.s;
  94565. this.sleepOrientation.x=this.orientation.x;
  94566. this.sleepOrientation.y=this.orientation.y;
  94567. this.sleepOrientation.z=this.orientation.z;*/
  94568. this.sleepTime = 0;
  94569. this.sleeping = true;
  94570. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94571. shape.updateProxy();
  94572. }
  94573. },
  94574. /**
  94575. * Get whether the rigid body has not any connection with others.
  94576. * @return
  94577. */
  94578. isLonely: function () {
  94579. return this.numJoints == 0 && this.numContacts == 0;
  94580. },
  94581. /**
  94582. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  94583. * This method is invoked automatically when calling the step of the World,
  94584. * There is no need to call from outside usually.
  94585. * @param timeStep time
  94586. */
  94587. updatePosition: function (timeStep) {
  94588. switch (this.type) {
  94589. case OIMO.BODY_STATIC:
  94590. this.linearVelocity.set(0, 0, 0);
  94591. this.angularVelocity.set(0, 0, 0);
  94592. // ONLY FOR TEST
  94593. if (this.controlPos) {
  94594. this.position.copy(this.newPosition);
  94595. this.controlPos = false;
  94596. }
  94597. if (this.controlRot) {
  94598. this.orientation.copy(this.newOrientation);
  94599. this.controlRot = false;
  94600. }
  94601. /*this.linearVelocity.x=0;
  94602. this.linearVelocity.y=0;
  94603. this.linearVelocity.z=0;
  94604. this.angularVelocity.x=0;
  94605. this.angularVelocity.y=0;
  94606. this.angularVelocity.z=0;*/
  94607. break;
  94608. case OIMO.BODY_DYNAMIC:
  94609. if (this.controlPos) {
  94610. this.angularVelocity.set(0, 0, 0);
  94611. this.linearVelocity.set(0, 0, 0);
  94612. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  94613. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  94614. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  94615. this.controlPos = false;
  94616. }
  94617. if (this.controlRot) {
  94618. this.angularVelocity.set(0, 0, 0);
  94619. this.orientation.copy(this.newOrientation);
  94620. //var t=timeStep//*0.5;
  94621. //var q = new OIMO.Quat();
  94622. //q.sub(this.newOrientation, this.orientation);
  94623. //q.normalize(q);
  94624. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  94625. q.x = (this.newOrientation.x - this.orientation.x)/t;
  94626. q.y = (this.newOrientation.y - this.orientation.y)/t;
  94627. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  94628. //this.angularVelocity.applyQuaternion(q);
  94629. //this.angularVelocity.x = this.angularVelocity.x/t;
  94630. //this.angularVelocity.y = this.angularVelocity.y/t;
  94631. //this.angularVelocity.z = this.angularVelocity.z/t;
  94632. this.controlRot = false;
  94633. }
  94634. this.position.addTime(this.linearVelocity, timeStep);
  94635. this.orientation.addTime(this.angularVelocity, timeStep);
  94636. break;
  94637. default: OIMO.Error("RigidBody", "Invalid type.");
  94638. }
  94639. this.syncShapes();
  94640. },
  94641. rotateInertia: function (rot, inertia, out) {
  94642. var tm1 = rot.elements;
  94643. var tm2 = inertia.elements;
  94644. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  94645. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  94646. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  94647. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  94648. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  94649. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  94650. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  94651. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  94652. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  94653. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  94654. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  94655. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  94656. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  94657. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  94658. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  94659. var oe = out.elements;
  94660. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  94661. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  94662. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  94663. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  94664. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  94665. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  94666. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  94667. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  94668. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  94669. },
  94670. syncShapes: function () {
  94671. var s = this.orientation.s;
  94672. var x = this.orientation.x;
  94673. var y = this.orientation.y;
  94674. var z = this.orientation.z;
  94675. var x2 = 2 * x;
  94676. var y2 = 2 * y;
  94677. var z2 = 2 * z;
  94678. var xx = x * x2;
  94679. var yy = y * y2;
  94680. var zz = z * z2;
  94681. var xy = x * y2;
  94682. var yz = y * z2;
  94683. var xz = x * z2;
  94684. var sx = s * x2;
  94685. var sy = s * y2;
  94686. var sz = s * z2;
  94687. var tr = this.rotation.elements;
  94688. tr[0] = 1 - yy - zz;
  94689. tr[1] = xy - sz;
  94690. tr[2] = xz + sy;
  94691. tr[3] = xy + sz;
  94692. tr[4] = 1 - xx - zz;
  94693. tr[5] = yz - sx;
  94694. tr[6] = xz - sy;
  94695. tr[7] = yz + sx;
  94696. tr[8] = 1 - xx - yy;
  94697. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  94698. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94699. //var relPos=shape.relativePosition;
  94700. //var relRot=shape.relativeRotation;
  94701. //var rot=shape.rotation;
  94702. /*var lx=relPos.x;
  94703. var ly=relPos.y;
  94704. var lz=relPos.z;
  94705. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  94706. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  94707. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  94708. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  94709. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  94710. // add by QuaziKb
  94711. shape.rotation.mul(this.rotation, shape.relativeRotation);
  94712. shape.updateProxy();
  94713. }
  94714. },
  94715. applyImpulse: function (position, force) {
  94716. this.linearVelocity.addScale(force, this.inverseMass);
  94717. /*this.linearVelocity.x+=force.x*this.inverseMass;
  94718. this.linearVelocity.y+=force.y*this.inverseMass;
  94719. this.linearVelocity.z+=force.z*this.inverseMass;*/
  94720. var rel = new OIMO.Vec3();
  94721. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  94722. this.angularVelocity.addEqual(rel);
  94723. /*this.angularVelocity.x+=rel.x;
  94724. this.angularVelocity.y+=rel.y;
  94725. this.angularVelocity.z+=rel.z;*/
  94726. },
  94727. //---------------------------------------------
  94728. //
  94729. // FOR THREE JS
  94730. //
  94731. //---------------------------------------------
  94732. rotationVectToQuad: function (rot) {
  94733. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  94734. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  94735. },
  94736. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  94737. var len = ax * ax + ay * ay + az * az;
  94738. if (len > 0) {
  94739. len = 1 / OIMO.sqrt(len);
  94740. ax *= len;
  94741. ay *= len;
  94742. az *= len;
  94743. }
  94744. var sin = OIMO.sin(rad * 0.5);
  94745. var cos = OIMO.cos(rad * 0.5);
  94746. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  94747. },
  94748. //---------------------------------------------
  94749. // SET DYNAMIQUE POSITION AND ROTATION
  94750. //---------------------------------------------
  94751. setPosition: function (pos) {
  94752. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  94753. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  94754. this.controlPos = true;
  94755. },
  94756. setQuaternion: function (q) {
  94757. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  94758. this.newOrientation.set(q.x, q.y, q.z, q.w);
  94759. this.controlRot = true;
  94760. },
  94761. setRotation: function (rot) {
  94762. this.newOrientation = this.rotationVectToQuad(rot);
  94763. this.controlRot = true;
  94764. },
  94765. //---------------------------------------------
  94766. // RESET DYNAMIQUE POSITION AND ROTATION
  94767. //---------------------------------------------
  94768. resetPosition: function (x, y, z) {
  94769. this.linearVelocity.set(0, 0, 0);
  94770. this.angularVelocity.set(0, 0, 0);
  94771. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  94772. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  94773. this.awake();
  94774. },
  94775. resetQuaternion: function (q) {
  94776. this.angularVelocity.set(0, 0, 0);
  94777. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  94778. this.awake();
  94779. },
  94780. resetRotation: function (x, y, z) {
  94781. this.angularVelocity.set(0, 0, 0);
  94782. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  94783. this.awake();
  94784. },
  94785. //---------------------------------------------
  94786. // GET POSITION AND ROTATION
  94787. //---------------------------------------------
  94788. getPosition: function () {
  94789. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  94790. },
  94791. getRotation: function () {
  94792. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  94793. },
  94794. getQuaternion: function () {
  94795. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  94796. },
  94797. getMatrix: function () {
  94798. var m = this.matrix.elements;
  94799. var r, p;
  94800. if (!this.sleeping) {
  94801. // rotation matrix
  94802. r = this.rotation.elements;
  94803. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  94804. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  94805. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  94806. // position matrix
  94807. p = this.position;
  94808. m[12] = p.x * OIMO.WORLD_SCALE;
  94809. m[13] = p.y * OIMO.WORLD_SCALE;
  94810. m[14] = p.z * OIMO.WORLD_SCALE;
  94811. // sleep or not ?
  94812. m[15] = 0;
  94813. } else {
  94814. m[15] = 1;
  94815. }
  94816. return m;
  94817. }
  94818. };
  94819. /**
  94820. * The main class of body.
  94821. * is for simplify creation process and data access of rigidRody
  94822. * Rigid body has the shape of a single or multiple collision processing,
  94823. * all setting in object
  94824. *
  94825. * @author loth
  94826. */
  94827. OIMO.Body = function (Obj) {
  94828. var obj = Obj || {};
  94829. if (!obj.world) return;
  94830. if (obj.type === undefined) obj.type = "box";
  94831. this.name = obj.name || '';
  94832. // obsolete use world.add(obj)
  94833. this.body = obj.world.add(obj);
  94834. /*
  94835. // the world where i am
  94836. this.parent = obj.world;
  94837. // Yep my name
  94838. this.name = obj.name || '';
  94839. // I'm dynamique or not
  94840. var move = obj.move || false;
  94841. // I can sleep or not
  94842. var noSleep = obj.noSleep || false;
  94843. // My start position
  94844. var p = obj.pos || [0,0,0];
  94845. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  94846. // My size
  94847. var s = obj.size || [1,1,1];
  94848. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  94849. // My rotation in degre
  94850. var rot = obj.rot || [0,0,0];
  94851. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  94852. var r = [];
  94853. for (var i=0; i<rot.length/3; i++){
  94854. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  94855. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  94856. }
  94857. // My physics setting
  94858. var sc = obj.sc || new OIMO.ShapeConfig();
  94859. if(obj.config){
  94860. // The density of the shape.
  94861. sc.density = obj.config[0] || 1;
  94862. // The coefficient of friction of the shape.
  94863. sc.friction = obj.config[1] || 0.4;
  94864. // The coefficient of restitution of the shape.
  94865. sc.restitution = obj.config[2] || 0.2;
  94866. // The bits of the collision groups to which the shape belongs.
  94867. sc.belongsTo = obj.config[3] || 1;
  94868. // The bits of the collision groups with which the shape collides.
  94869. sc.collidesWith = obj.config[4] || 0xffffffff;
  94870. }
  94871. if(obj.massPos){
  94872. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  94873. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  94874. }
  94875. if(obj.massRot){
  94876. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  94877. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  94878. }
  94879. // My rigidbody
  94880. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  94881. // My shapes
  94882. var shapes = [];
  94883. var type = obj.type || "box";
  94884. if( typeof type === 'string' ) type = [type];// single shape
  94885. var n, n2;
  94886. for(var i=0; i<type.length; i++){
  94887. n = i*3;
  94888. n2 = i*4;
  94889. switch(type[i]){
  94890. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  94891. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  94892. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  94893. }
  94894. this.body.addShape(shapes[i]);
  94895. if(i>0){
  94896. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  94897. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  94898. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  94899. }
  94900. }
  94901. // I'm static or i move
  94902. if(move){
  94903. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  94904. else this.body.setupMass(0x1, true);
  94905. if(noSleep) this.body.allowSleep = false;
  94906. else this.body.allowSleep = true;
  94907. } else {
  94908. this.body.setupMass(0x2);
  94909. }
  94910. this.body.name = this.name;
  94911. this.sleeping = this.body.sleeping;
  94912. // finaly add to physics world
  94913. this.parent.addRigidBody(this.body);*/
  94914. }
  94915. OIMO.Body.prototype = {
  94916. constructor: OIMO.Body,
  94917. // SET
  94918. setPosition: function (pos) {
  94919. this.body.setPosition(pos);
  94920. },
  94921. setQuaternion: function (q) {
  94922. this.body.setQuaternion(q);
  94923. },
  94924. setRotation: function (rot) {
  94925. this.body.setRotation(rot);
  94926. },
  94927. // GET
  94928. getPosition: function () {
  94929. return this.body.getPosition();
  94930. },
  94931. getRotation: function () {
  94932. return this.body.getRotation();
  94933. },
  94934. getQuaternion: function () {
  94935. return this.body.getQuaternion();
  94936. },
  94937. getMatrix: function () {
  94938. return this.body.getMatrix();
  94939. },
  94940. getSleep: function () {
  94941. return this.body.sleeping;
  94942. },
  94943. // RESET
  94944. resetPosition: function (x, y, z) {
  94945. this.body.resetPosition(x, y, z);
  94946. },
  94947. resetRotation: function (x, y, z) {
  94948. this.body.resetRotation(x, y, z);
  94949. },
  94950. // force wakeup
  94951. awake: function () {
  94952. this.body.awake();
  94953. },
  94954. // remove rigidbody
  94955. remove: function () {
  94956. this.body.dispose();
  94957. //this.parent.removeRigidBody(this.body);
  94958. },
  94959. // test if this object hit another
  94960. checkContact: function (name) {
  94961. this.body.checkContact(name);
  94962. //this.parent.checkContact(this.name, name);
  94963. }
  94964. }
  94965. /**
  94966. * The main class of link.
  94967. * is for simplify creation process and data access of Joint
  94968. * all setting in object
  94969. *
  94970. * @author loth
  94971. */
  94972. OIMO.Link = function (Obj) {
  94973. var obj = Obj || {};
  94974. if (!obj.world) return;
  94975. if (obj.type === undefined) obj.type = "jointHinge";
  94976. this.name = obj.name || '';
  94977. // obsolete use world.add(obj)
  94978. this.joint = obj.world.add(obj);
  94979. // the world where i am
  94980. /*this.parent = obj.world;
  94981. this.name = obj.name || '';
  94982. var type = obj.type || "jointHinge";
  94983. var axe1 = obj.axe1 || [1,0,0];
  94984. var axe2 = obj.axe2 || [1,0,0];
  94985. var pos1 = obj.pos1 || [0,0,0];
  94986. var pos2 = obj.pos2 || [0,0,0];
  94987. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  94988. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  94989. var min, max;
  94990. if(type==="jointDistance"){
  94991. min = obj.min || 0;
  94992. max = obj.max || 10;
  94993. min = min*OIMO.INV_SCALE;
  94994. max = max*OIMO.INV_SCALE;
  94995. }else{
  94996. min = obj.min || 57.29578;
  94997. max = obj.max || 0;
  94998. min = min*OIMO.TO_RAD;
  94999. max = max*OIMO.TO_RAD;
  95000. }
  95001. var limit = obj.limit || null;
  95002. var spring = obj.spring || null;
  95003. var motor = obj.motor || null;
  95004. // joint setting
  95005. var jc = new OIMO.JointConfig();
  95006. jc.allowCollision = obj.collision || false;;
  95007. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  95008. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  95009. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  95010. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  95011. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  95012. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  95013. jc.body1 = obj.body1;
  95014. jc.body2 = obj.body2;
  95015. switch(type){
  95016. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  95017. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  95018. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  95019. break;
  95020. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  95021. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  95022. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  95023. break;
  95024. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  95025. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  95026. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  95027. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  95028. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  95029. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  95030. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  95031. break;
  95032. }
  95033. this.joint.name = this.name;
  95034. // finaly add to physics world
  95035. this.parent.addJoint(this.joint);*/
  95036. }
  95037. OIMO.Link.prototype = {
  95038. constructor: OIMO.Link,
  95039. getPosition: function () {
  95040. // array of two vect3 [point1, point2]
  95041. return this.joint.getPosition();
  95042. },
  95043. getMatrix: function () {
  95044. return this.joint.getMatrix();
  95045. },
  95046. // remove joint
  95047. remove: function () {
  95048. this.joint.dispose();
  95049. //this.parent.removeJoint(this.joint);
  95050. },
  95051. // force wakeup linked body
  95052. awake: function () {
  95053. this.joint.awake();
  95054. }
  95055. }
  95056. /**
  95057. * The Dictionary class for testing
  95058. * @author lo-th
  95059. */
  95060. OIMO.Dictionary = function () {
  95061. this.data = {};
  95062. this.keys = [];
  95063. };
  95064. OIMO.Dictionary.prototype = {
  95065. constructor: OIMO.Dictionary,
  95066. set: function (value) {
  95067. var key = value.id;
  95068. if (!this.get[key]) this.keys.push(key);
  95069. this.data[key] = value;
  95070. },
  95071. get: function (id) {
  95072. return this.data[id];
  95073. },
  95074. del: function (value) {
  95075. var k = this.keys;
  95076. var n = k.indexOf(value.id);
  95077. if (n > -1) {
  95078. delete this.data[k[n]];
  95079. k.splice(n, 1);
  95080. }
  95081. },
  95082. reset: function () {
  95083. var data = this.data, keys = this.keys, key;
  95084. while (keys.length > 0) {
  95085. key = keys.pop();
  95086. delete data[key];
  95087. }
  95088. }
  95089. };
  95090. OIMO.Performance = function (world) {
  95091. this.parent = world;
  95092. this.infos = new OIMO_ARRAY_TYPE(13);
  95093. this.f = [0, 0, 0];
  95094. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  95095. this.broadPhase = this.types[this.parent.broadPhase.types];
  95096. this.version = OIMO.REVISION;
  95097. this.fps = 0;
  95098. this.broadPhaseTime = 0;
  95099. this.narrowPhaseTime = 0;
  95100. this.solvingTime = 0;
  95101. //this.updatingTime = 0;
  95102. this.totalTime = 0;
  95103. };
  95104. OIMO.Performance.prototype = {
  95105. upfps: function () {
  95106. this.f[1] = Date.now();
  95107. 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]++;
  95108. },
  95109. updatingTime: function () {
  95110. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  95111. },
  95112. show: function () {
  95113. var info = [
  95114. "Oimo.js " + this.version + "<br>",
  95115. this.broadPhase + "<br><br>",
  95116. "FPS: " + this.fps + " fps<br><br>",
  95117. "rigidbody " + this.parent.numRigidBodies + "<br>",
  95118. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  95119. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  95120. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  95121. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  95122. "Time in milliseconde<br><br>",
  95123. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  95124. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  95125. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  95126. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  95127. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  95128. ].join("\n");
  95129. return info;
  95130. },
  95131. toArray: function () {
  95132. this.infos[0] = this.parent.broadPhase.types;
  95133. this.infos[1] = this.parent.numRigidBodies;
  95134. this.infos[2] = this.parent.numContacts;
  95135. this.infos[3] = this.parent.broadPhase.numPairChecks;
  95136. this.infos[4] = this.parent.numContactPoints;
  95137. this.infos[5] = this.parent.numIslands;
  95138. this.infos[6] = this.broadPhaseTime;
  95139. this.infos[7] = this.narrowPhaseTime;
  95140. this.infos[8] = this.solvingTime;
  95141. this.infos[9] = this.updatingTime();
  95142. this.infos[10] = this.totalTime;
  95143. this.infos[11] = this.fps;
  95144. return this.infos;
  95145. }
  95146. };
  95147. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  95148. this.elements = new OIMO_ARRAY_TYPE(16);
  95149. var te = this.elements;
  95150. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  95151. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  95152. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  95153. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  95154. };
  95155. OIMO.Mat44.prototype = {
  95156. constructor: OIMO.Mat44,
  95157. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  95158. var te = this.elements;
  95159. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  95160. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  95161. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  95162. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  95163. return this;
  95164. }/*,
  95165. extractRotation: function () {
  95166. var v1 = new THREE.Vector3();
  95167. return function ( m ) {
  95168. var te = this.elements;
  95169. var me = m.elements;
  95170. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  95171. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  95172. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  95173. te[ 0 ] = me[ 0 ] * scaleX;
  95174. te[ 1 ] = me[ 1 ] * scaleX;
  95175. te[ 2 ] = me[ 2 ] * scaleX;
  95176. te[ 4 ] = me[ 4 ] * scaleY;
  95177. te[ 5 ] = me[ 5 ] * scaleY;
  95178. te[ 6 ] = me[ 6 ] * scaleY;
  95179. te[ 8 ] = me[ 8 ] * scaleZ;
  95180. te[ 9 ] = me[ 9 ] * scaleZ;
  95181. te[ 10 ] = me[ 10 ] * scaleZ;
  95182. return this;
  95183. };
  95184. }() */
  95185. }
  95186. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  95187. this.elements = new OIMO_ARRAY_TYPE(9);
  95188. var te = this.elements;
  95189. this.init(
  95190. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  95191. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  95192. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  95193. );
  95194. };
  95195. OIMO.Mat33.prototype = {
  95196. constructor: OIMO.Mat33,
  95197. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  95198. var te = this.elements;
  95199. te[0] = e00; te[1] = e01; te[2] = e02;
  95200. te[3] = e10; te[4] = e11; te[5] = e12;
  95201. te[6] = e20; te[7] = e21; te[8] = e22;
  95202. return this;
  95203. },
  95204. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  95205. var te = this.elements;
  95206. te[0] = e00; te[1] = e01; te[2] = e02;
  95207. te[3] = e10; te[4] = e11; te[5] = e12;
  95208. te[6] = e20; te[7] = e21; te[8] = e22;
  95209. return this;
  95210. },
  95211. multiply: function (s) {
  95212. var te = this.elements;
  95213. te[0] *= s; te[1] *= s; te[2] *= s;
  95214. te[3] *= s; te[4] *= s; te[5] *= s;
  95215. te[6] *= s; te[7] *= s; te[8] *= s;
  95216. return this;
  95217. },
  95218. add: function (m1, m2) {
  95219. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  95220. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  95221. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  95222. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  95223. return this;
  95224. },
  95225. addEqual: function (m) {
  95226. var te = this.elements, tem = m.elements;
  95227. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  95228. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  95229. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  95230. return this;
  95231. },
  95232. sub: function (m1, m2) {
  95233. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  95234. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  95235. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  95236. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  95237. return this;
  95238. },
  95239. subEqual: function (m) {
  95240. var te = this.elements, tem = m.elements;
  95241. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  95242. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  95243. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  95244. return this;
  95245. },
  95246. scale: function (m, s) {
  95247. var te = this.elements, tm = m.elements;
  95248. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  95249. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  95250. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  95251. return this;
  95252. },
  95253. scaleEqual: function (s) {
  95254. var te = this.elements;
  95255. te[0] *= s; te[1] *= s; te[2] *= s;
  95256. te[3] *= s; te[4] *= s; te[5] *= s;
  95257. te[6] *= s; te[7] *= s; te[8] *= s;
  95258. return this;
  95259. },
  95260. mul: function (m1, m2) {
  95261. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  95262. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  95263. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  95264. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  95265. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  95266. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  95267. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  95268. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  95269. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  95270. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  95271. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  95272. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  95273. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  95274. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  95275. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  95276. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  95277. return this;
  95278. },
  95279. mulScale: function (m, sx, sy, sz, Prepend) {
  95280. var prepend = Prepend || false;
  95281. var te = this.elements, tm = m.elements;
  95282. if (prepend) {
  95283. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  95284. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  95285. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  95286. } else {
  95287. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  95288. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  95289. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  95290. }
  95291. return this;
  95292. },
  95293. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  95294. var prepend = Prepend || false;
  95295. var s = OIMO.sin(rad);
  95296. var c = OIMO.cos(rad);
  95297. var c1 = 1 - c;
  95298. var r00 = ax * ax * c1 + c;
  95299. var r01 = ax * ay * c1 - az * s;
  95300. var r02 = ax * az * c1 + ay * s;
  95301. var r10 = ay * ax * c1 + az * s;
  95302. var r11 = ay * ay * c1 + c;
  95303. var r12 = ay * az * c1 - ax * s;
  95304. var r20 = az * ax * c1 - ay * s;
  95305. var r21 = az * ay * c1 + ax * s;
  95306. var r22 = az * az * c1 + c;
  95307. var tm = m.elements;
  95308. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  95309. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  95310. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  95311. var te = this.elements;
  95312. if (prepend) {
  95313. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  95314. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  95315. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  95316. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  95317. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  95318. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  95319. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  95320. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  95321. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  95322. } else {
  95323. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  95324. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  95325. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  95326. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  95327. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  95328. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  95329. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  95330. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  95331. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  95332. }
  95333. return this;
  95334. },
  95335. transpose: function (m) {
  95336. var te = this.elements, tm = m.elements;
  95337. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  95338. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  95339. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  95340. return this;
  95341. },
  95342. setQuat: function (q) {
  95343. var te = this.elements,
  95344. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  95345. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  95346. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  95347. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  95348. te[0] = 1 - yy - zz;
  95349. te[1] = xy - sz;
  95350. te[2] = xz + sy;
  95351. te[3] = xy + sz;
  95352. te[4] = 1 - xx - zz;
  95353. te[5] = yz - sx;
  95354. te[6] = xz - sy;
  95355. te[7] = yz + sx;
  95356. te[8] = 1 - xx - yy;
  95357. return this;
  95358. },
  95359. invert: function (m) {
  95360. var te = this.elements, tm = m.elements,
  95361. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  95362. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  95363. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  95364. b01 = a4 * a8 - a7 * a5,
  95365. b11 = a7 * a2 - a1 * a8,
  95366. b21 = a1 * a5 - a4 * a2,
  95367. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  95368. if (dt != 0) { dt = 1.0 / dt; }
  95369. te[0] = dt * b01;//(a4*a8 - a5*a7);
  95370. te[1] = dt * b11;//(a2*a7 - a1*a8);
  95371. te[2] = dt * b21;//(a1*a5 - a2*a4);
  95372. te[3] = dt * (a5 * a6 - a3 * a8);
  95373. te[4] = dt * (a0 * a8 - a2 * a6);
  95374. te[5] = dt * (a2 * a3 - a0 * a5);
  95375. te[6] = dt * (a3 * a7 - a4 * a6);
  95376. te[7] = dt * (a1 * a6 - a0 * a7);
  95377. te[8] = dt * (a0 * a4 - a1 * a3);
  95378. return this;
  95379. },
  95380. /*copy: function(m){
  95381. var te = this.elements, tem = m.elements;
  95382. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  95383. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  95384. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  95385. return this;
  95386. },*/
  95387. toEuler: function () { // not work !!
  95388. function clamp(x) {
  95389. return OIMO.min(OIMO.max(x, -1), 1);
  95390. }
  95391. var te = this.elements;
  95392. var m11 = te[0], m12 = te[3], m13 = te[6];
  95393. var m21 = te[1], m22 = te[4], m23 = te[7];
  95394. var m31 = te[2], m32 = te[5], m33 = te[8];
  95395. var p = new OIMO.Vec3();
  95396. var d = new OIMO.Quat();
  95397. var s;
  95398. p.y = OIMO.asin(clamp(m13));
  95399. if (OIMO.abs(m13) < 0.99999) {
  95400. p.x = OIMO.atan2(-m23, m33);
  95401. p.z = OIMO.atan2(-m12, m11);
  95402. } else {
  95403. p.x = OIMO.atan2(m32, m22);
  95404. p.z = 0;
  95405. }
  95406. return p;
  95407. },
  95408. /*clone: function(){
  95409. var te = this.elements;
  95410. return new OIMO.Mat33(
  95411. te[0], te[1], te[2],
  95412. te[3], te[4], te[5],
  95413. te[6], te[7], te[8]
  95414. );
  95415. },*/
  95416. toString: function () {
  95417. var te = this.elements;
  95418. var text =
  95419. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  95420. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  95421. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  95422. return text;
  95423. },
  95424. // OK
  95425. multiplyScalar: function (s) {
  95426. var te = this.elements;
  95427. te[0] *= s; te[3] *= s; te[6] *= s;
  95428. te[1] *= s; te[4] *= s; te[7] *= s;
  95429. te[2] *= s; te[5] *= s; te[8] *= s;
  95430. return this;
  95431. },
  95432. identity: function () {
  95433. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  95434. return this;
  95435. },
  95436. clone: function () {
  95437. return new this.constructor().fromArray(this.elements);
  95438. },
  95439. copy: function (m) {
  95440. var me = m.elements;
  95441. this.set(
  95442. me[0], me[3], me[6],
  95443. me[1], me[4], me[7],
  95444. me[2], me[5], me[8]
  95445. );
  95446. return this;
  95447. },
  95448. fromArray: function (array) {
  95449. this.elements.set(array);
  95450. return this;
  95451. },
  95452. toArray: function () {
  95453. var te = this.elements;
  95454. return [
  95455. te[0], te[1], te[2],
  95456. te[3], te[4], te[5],
  95457. te[6], te[7], te[8]
  95458. ];
  95459. }
  95460. };
  95461. OIMO.Quat = function (s, x, y, z) {
  95462. this.s = (s !== undefined) ? s : 1;
  95463. this.x = x || 0;
  95464. this.y = y || 0;
  95465. this.z = z || 0;
  95466. };
  95467. OIMO.Quat.prototype = {
  95468. constructor: OIMO.Quat,
  95469. set: function (x, y, z, w) {
  95470. this.x = x;
  95471. this.y = y;
  95472. this.z = z;
  95473. this.s = w;
  95474. return this;
  95475. },
  95476. init: function (s, x, y, z) {
  95477. this.s = (s !== undefined) ? s : 1;
  95478. this.x = x || 0;
  95479. this.y = y || 0;
  95480. this.z = z || 0;
  95481. return this;
  95482. },
  95483. add: function (q1, q2) {
  95484. this.s = q1.s + q2.s;
  95485. this.x = q1.x + q2.x;
  95486. this.y = q1.y + q2.y;
  95487. this.z = q1.z + q2.z;
  95488. return this;
  95489. },
  95490. addTime: function (v, t) {
  95491. var x = v.x;
  95492. var y = v.y;
  95493. var z = v.z;
  95494. var qs = this.s;
  95495. var qx = this.x;
  95496. var qy = this.y;
  95497. var qz = this.z;
  95498. t *= 0.5;
  95499. var ns = (-x * qx - y * qy - z * qz) * t;
  95500. var nx = (x * qs + y * qz - z * qy) * t;
  95501. var ny = (-x * qz + y * qs + z * qx) * t;
  95502. var nz = (x * qy - y * qx + z * qs) * t;
  95503. qs += ns;
  95504. qx += nx;
  95505. qy += ny;
  95506. qz += nz;
  95507. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  95508. this.s = qs * s;
  95509. this.x = qx * s;
  95510. this.y = qy * s;
  95511. this.z = qz * s;
  95512. return this;
  95513. },
  95514. sub: function (q1, q2) {
  95515. this.s = q1.s - q2.s;
  95516. this.x = q1.x - q2.x;
  95517. this.y = q1.y - q2.y;
  95518. this.z = q1.z - q2.z;
  95519. return this;
  95520. },
  95521. scale: function (q, s) {
  95522. this.s = q.s * s;
  95523. this.x = q.x * s;
  95524. this.y = q.y * s;
  95525. this.z = q.z * s;
  95526. return this;
  95527. },
  95528. mul: function (q1, q2) {
  95529. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  95530. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  95531. this.x = ax * bs + as * bx + ay * bz - az * by;
  95532. this.y = ay * bs + as * by + az * bx - ax * bz;
  95533. this.z = az * bs + as * bz + ax * by - ay * bx;
  95534. this.s = as * bs - ax * bx - ay * by - az * bz;
  95535. return this;
  95536. },
  95537. arc: function (v1, v2) {
  95538. var x1 = v1.x;
  95539. var y1 = v1.y;
  95540. var z1 = v1.z;
  95541. var x2 = v2.x;
  95542. var y2 = v2.y;
  95543. var z2 = v2.z;
  95544. var d = x1 * x2 + y1 * y2 + z1 * z2;
  95545. if (d == -1) {
  95546. x2 = y1 * x1 - z1 * z1;
  95547. y2 = -z1 * y1 - x1 * x1;
  95548. z2 = x1 * z1 + y1 * y1;
  95549. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  95550. this.s = 0;
  95551. this.x = x2 * d;
  95552. this.y = y2 * d;
  95553. this.z = z2 * d;
  95554. return this;
  95555. }
  95556. var cx = y1 * z2 - z1 * y2;
  95557. var cy = z1 * x2 - x1 * z2;
  95558. var cz = x1 * y2 - y1 * x2;
  95559. this.s = OIMO.sqrt((1 + d) * 0.5);
  95560. d = 0.5 / this.s;
  95561. this.x = cx * d;
  95562. this.y = cy * d;
  95563. this.z = cz * d;
  95564. return this;
  95565. },
  95566. normalize: function (q) {
  95567. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  95568. if (len > 0) { len = 1 / len; }
  95569. this.s = q.s * len;
  95570. this.x = q.x * len;
  95571. this.y = q.y * len;
  95572. this.z = q.z * len;
  95573. return this;
  95574. },
  95575. invert: function (q) {
  95576. this.s = q.s;
  95577. this.x = -q.x;
  95578. this.y = -q.y;
  95579. this.z = -q.z;
  95580. return this;
  95581. },
  95582. length: function () {
  95583. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  95584. },
  95585. copy: function (q) {
  95586. this.s = q.s;
  95587. this.x = q.x;
  95588. this.y = q.y;
  95589. this.z = q.z;
  95590. return this;
  95591. },
  95592. testDiff: function (q) {
  95593. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  95594. else return false;
  95595. },
  95596. clone: function (q) {
  95597. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  95598. },
  95599. toString: function () {
  95600. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  95601. }
  95602. }
  95603. // for three easy export
  95604. OIMO.Quaternion = function (x, y, z, w) {
  95605. this.x = x || 0;
  95606. this.y = y || 0;
  95607. this.z = z || 0;
  95608. this.w = (w !== undefined) ? w : 1;
  95609. };
  95610. OIMO.Quaternion.prototype = {
  95611. constructor: OIMO.Quaternion,
  95612. setFromRotationMatrix: function (m) {
  95613. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  95614. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  95615. var te = m.elements,
  95616. m11 = te[0], m12 = te[1], m13 = te[2],
  95617. m21 = te[3], m22 = te[4], m23 = te[5],
  95618. m31 = te[6], m32 = te[7], m33 = te[8],
  95619. trace = m11 + m22 + m33,
  95620. s;
  95621. if (trace > 0) {
  95622. s = 0.5 / OIMO.sqrt(trace + 1.0);
  95623. this.w = 0.25 / s;
  95624. this.x = (m32 - m23) * s;
  95625. this.y = (m13 - m31) * s;
  95626. this.z = (m21 - m12) * s;
  95627. } else if (m11 > m22 && m11 > m33) {
  95628. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  95629. this.w = (m32 - m23) / s;
  95630. this.x = 0.25 * s;
  95631. this.y = (m12 + m21) / s;
  95632. this.z = (m13 + m31) / s;
  95633. } else if (m22 > m33) {
  95634. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  95635. this.w = (m13 - m31) / s;
  95636. this.x = (m12 + m21) / s;
  95637. this.y = 0.25 * s;
  95638. this.z = (m23 + m32) / s;
  95639. } else {
  95640. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  95641. this.w = (m21 - m12) / s;
  95642. this.x = (m13 + m31) / s;
  95643. this.y = (m23 + m32) / s;
  95644. this.z = 0.25 * s;
  95645. }
  95646. //this.onChangeCallback();
  95647. return this;
  95648. }
  95649. }
  95650. OIMO.Vec3 = function (x, y, z) {
  95651. this.x = x || 0;
  95652. this.y = y || 0;
  95653. this.z = z || 0;
  95654. };
  95655. OIMO.Vec3.prototype = {
  95656. constructor: OIMO.Vec3,
  95657. init: function (x, y, z) {
  95658. this.x = x || 0;
  95659. this.y = y || 0;
  95660. this.z = z || 0;
  95661. return this;
  95662. },
  95663. set: function (x, y, z) {
  95664. this.x = x;
  95665. this.y = y;
  95666. this.z = z;
  95667. return this;
  95668. },
  95669. add: function (v1, v2) {
  95670. this.x = v1.x + v2.x;
  95671. this.y = v1.y + v2.y;
  95672. this.z = v1.z + v2.z;
  95673. return this;
  95674. },
  95675. addEqual: function (v) {
  95676. this.x += v.x;
  95677. this.y += v.y;
  95678. this.z += v.z;
  95679. return this;
  95680. },
  95681. addTime: function (v, t) {
  95682. this.x += v.x * t;
  95683. this.y += v.y * t;
  95684. this.z += v.z * t;
  95685. return this;
  95686. },
  95687. sub: function (v1, v2) {
  95688. this.x = v1.x - v2.x;
  95689. this.y = v1.y - v2.y;
  95690. this.z = v1.z - v2.z;
  95691. return this;
  95692. },
  95693. subEqual: function (v) {
  95694. this.x -= v.x;
  95695. this.y -= v.y;
  95696. this.z -= v.z;
  95697. return this;
  95698. },
  95699. addScale: function (v, s) {
  95700. this.x += v.x * s;
  95701. this.y += v.y * s;
  95702. this.z += v.z * s;
  95703. return this;
  95704. },
  95705. scale: function (v, s) {
  95706. this.x = v.x * s;
  95707. this.y = v.y * s;
  95708. this.z = v.z * s;
  95709. return this;
  95710. },
  95711. scaleEqual: function (s) {
  95712. this.x *= s;
  95713. this.y *= s;
  95714. this.z *= s;
  95715. return this;
  95716. },
  95717. /*dot: function(v){
  95718. return this.x*v.x+this.y*v.y+this.z*v.z;
  95719. },*/
  95720. cross: function (v1, v2) {
  95721. var ax = v1.x, ay = v1.y, az = v1.z,
  95722. bx = v2.x, by = v2.y, bz = v2.z;
  95723. this.x = ay * bz - az * by;
  95724. this.y = az * bx - ax * bz;
  95725. this.z = ax * by - ay * bx;
  95726. return this;
  95727. },
  95728. mul: function (o, v, m) {
  95729. var te = m.elements;
  95730. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  95731. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  95732. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  95733. return this;
  95734. },
  95735. mulMat: function (m, v) {
  95736. var te = m.elements;
  95737. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  95738. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  95739. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  95740. return this;
  95741. },
  95742. normalize: function (v) {
  95743. var x = v.x, y = v.y, z = v.z;
  95744. var l = x * x + y * y + z * z;
  95745. if (l > 0) {
  95746. l = 1 / OIMO.sqrt(l);
  95747. this.x = x * l;
  95748. this.y = y * l;
  95749. this.z = z * l;
  95750. }
  95751. return this;
  95752. },
  95753. /*norm: function(){
  95754. var x = this.x, y = this.y, z = this.z;
  95755. var l = x*x + y*y + z*z;
  95756. if (l > 0) {
  95757. l = 1 / OIMO.sqrt(l);
  95758. this.x = x*l;
  95759. this.y = y*l;
  95760. this.z = z*l;
  95761. }
  95762. return this;
  95763. },*/
  95764. invert: function (v) {
  95765. this.x = -v.x;
  95766. this.y = -v.y;
  95767. this.z = -v.z;
  95768. return this;
  95769. },
  95770. /*length: function(){
  95771. var x = this.x, y = this.y, z = this.z;
  95772. return OIMO.sqrt(x*x + y*y + z*z);
  95773. },*/
  95774. negate: function () {
  95775. this.x = -this.x;
  95776. this.y = -this.y;
  95777. this.z = -this.z;
  95778. return this;
  95779. },
  95780. dot: function (v) {
  95781. return this.x * v.x + this.y * v.y + this.z * v.z;
  95782. },
  95783. lengthSq: function () {
  95784. return this.x * this.x + this.y * this.y + this.z * this.z;
  95785. },
  95786. length: function () {
  95787. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  95788. },
  95789. /*len: function(){
  95790. var x = this.x, y = this.y, z = this.z;
  95791. return x*x + y*y + z*z;
  95792. },*/
  95793. copy: function (v) {
  95794. this.x = v.x;
  95795. this.y = v.y;
  95796. this.z = v.z;
  95797. return this;
  95798. },
  95799. applyQuaternion: function (q) {
  95800. var x = this.x;
  95801. var y = this.y;
  95802. var z = this.z;
  95803. var qx = q.x;
  95804. var qy = q.y;
  95805. var qz = q.z;
  95806. var qs = q.s;
  95807. // calculate quat * vector
  95808. var ix = qs * x + qy * z - qz * y;
  95809. var iy = qs * y + qz * x - qx * z;
  95810. var iz = qs * z + qx * y - qy * x;
  95811. var iw = -qx * x - qy * y - qz * z;
  95812. // calculate result * inverse quat
  95813. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  95814. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  95815. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  95816. return this;
  95817. },
  95818. testZero: function () {
  95819. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  95820. else return false;
  95821. },
  95822. testDiff: function (v) {
  95823. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  95824. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  95825. //else return false;
  95826. },
  95827. equals: function (v) {
  95828. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  95829. },
  95830. clone: function () {
  95831. return new this.constructor(this.x, this.y, this.z);
  95832. },
  95833. toString: function () {
  95834. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  95835. },
  95836. multiplyScalar: function (scalar) {
  95837. if (isFinite(scalar)) {
  95838. this.x *= scalar;
  95839. this.y *= scalar;
  95840. this.z *= scalar;
  95841. } else {
  95842. this.x = 0;
  95843. this.y = 0;
  95844. this.z = 0;
  95845. }
  95846. return this;
  95847. },
  95848. divideScalar: function (scalar) {
  95849. return this.multiplyScalar(1 / scalar);
  95850. },
  95851. // TODO rename to normalize
  95852. norm: function () {
  95853. return this.divideScalar(this.length());
  95854. },
  95855. }
  95856. OIMO.Euler = function (x, y, z, order) {
  95857. this._x = x || 0;
  95858. this._y = y || 0;
  95859. this._z = z || 0;
  95860. this._order = order || OIMO.Euler.DefaultOrder;
  95861. };
  95862. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  95863. OIMO.Euler.DefaultOrder = 'XYZ';
  95864. OIMO.clamp = function (x, a, b) {
  95865. return (x < a) ? a : ((x > b) ? b : x);
  95866. }
  95867. OIMO.Euler.prototype = {
  95868. constructor: OIMO.Euler,
  95869. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  95870. get x() {
  95871. return this._x;
  95872. },
  95873. set x(value) {
  95874. this._x = value;
  95875. this.onChangeCallback();
  95876. },
  95877. get y() {
  95878. return this._y;
  95879. },
  95880. set y(value) {
  95881. this._y = value;
  95882. this.onChangeCallback();
  95883. },
  95884. get z() {
  95885. return this._z;
  95886. },
  95887. set z(value) {
  95888. this._z = value;
  95889. this.onChangeCallback();
  95890. },
  95891. get order() {
  95892. return this._order;
  95893. },
  95894. set order(value) {
  95895. this._order = value;
  95896. this.onChangeCallback();
  95897. },
  95898. set: function (x, y, z, order) {
  95899. this._x = x;
  95900. this._y = y;
  95901. this._z = z;
  95902. this._order = order || this._order;
  95903. this.onChangeCallback();
  95904. return this;
  95905. },
  95906. copy: function (euler) {
  95907. this._x = euler._x;
  95908. this._y = euler._y;
  95909. this._z = euler._z;
  95910. this._order = euler._order;
  95911. this.onChangeCallback();
  95912. return this;
  95913. },
  95914. setFromRotationMatrix: function (m, order) {
  95915. var clamp = OIMO.clamp;
  95916. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  95917. var te = m.elements;
  95918. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  95919. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  95920. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  95921. var m11 = te[0], m12 = te[1], m13 = te[2],
  95922. m21 = te[3], m22 = te[4], m23 = te[5],
  95923. m31 = te[6], m32 = te[7], m33 = te[8];
  95924. order = order || this._order;
  95925. if (order === 'XYZ') {
  95926. this._y = OIMO.asin(clamp(m13, -1, 1));
  95927. if (OIMO.abs(m13) < 0.99999) {
  95928. this._x = OIMO.atan2(-m23, m33);
  95929. this._z = OIMO.atan2(-m12, m11);
  95930. } else {
  95931. this._x = OIMO.atan2(m32, m22);
  95932. this._z = 0;
  95933. }
  95934. } else if (order === 'YXZ') {
  95935. this._x = OIMO.asin(-clamp(m23, -1, 1));
  95936. if (OIMO.abs(m23) < 0.99999) {
  95937. this._y = OIMO.atan2(m13, m33);
  95938. this._z = OIMO.atan2(m21, m22);
  95939. } else {
  95940. this._y = OIMO.atan2(-m31, m11);
  95941. this._z = 0;
  95942. }
  95943. } else if (order === 'ZXY') {
  95944. this._x = OIMO.asin(clamp(m32, -1, 1));
  95945. if (OIMO.abs(m32) < 0.99999) {
  95946. this._y = OIMO.atan2(-m31, m33);
  95947. this._z = OIMO.atan2(-m12, m22);
  95948. } else {
  95949. this._y = 0;
  95950. this._z = OIMO.atan2(m21, m11);
  95951. }
  95952. } else if (order === 'ZYX') {
  95953. this._y = OIMO.asin(-clamp(m31, -1, 1));
  95954. if (OIMO.abs(m31) < 0.99999) {
  95955. this._x = OIMO.atan2(m32, m33);
  95956. this._z = OIMO.atan2(m21, m11);
  95957. } else {
  95958. this._x = 0;
  95959. this._z = OIMO.atan2(-m12, m22);
  95960. }
  95961. } else if (order === 'YZX') {
  95962. this._z = OIMO.asin(clamp(m21, -1, 1));
  95963. if (OIMO.abs(m21) < 0.99999) {
  95964. this._x = OIMO.atan2(-m23, m22);
  95965. this._y = OIMO.atan2(-m31, m11);
  95966. } else {
  95967. this._x = 0;
  95968. this._y = OIMO.atan2(m13, m33);
  95969. }
  95970. } else if (order === 'XZY') {
  95971. this._z = OIMO.asin(-clamp(m12, -1, 1));
  95972. if (OIMO.abs(m12) < 0.99999) {
  95973. this._x = OIMO.atan2(m32, m22);
  95974. this._y = OIMO.atan2(m13, m11);
  95975. } else {
  95976. this._x = OIMO.atan2(-m23, m33);
  95977. this._y = 0;
  95978. }
  95979. } else {
  95980. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  95981. }
  95982. this._order = order;
  95983. this.onChangeCallback();
  95984. return this;
  95985. },
  95986. setFromQuaternion: function (q, order, update) {
  95987. var clamp = OIMO.clamp;
  95988. // q is assumed to be normalized
  95989. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  95990. var sqx = q.x * q.x;
  95991. var sqy = q.y * q.y;
  95992. var sqz = q.z * q.z;
  95993. var sqw = q.s * q.s;
  95994. order = order || this._order;
  95995. if (order === 'XYZ') {
  95996. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  95997. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  95998. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  95999. } else if (order === 'YXZ') {
  96000. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  96001. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  96002. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  96003. } else if (order === 'ZXY') {
  96004. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  96005. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  96006. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  96007. } else if (order === 'ZYX') {
  96008. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  96009. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  96010. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  96011. } else if (order === 'YZX') {
  96012. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  96013. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  96014. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  96015. } else if (order === 'XZY') {
  96016. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  96017. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  96018. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  96019. } else {
  96020. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  96021. }
  96022. this._order = order;
  96023. if (update !== false) this.onChangeCallback();
  96024. return this;
  96025. },
  96026. reorder: function () {
  96027. // WARNING: this discards revolution information -bhouston
  96028. var q = new OIMO.Quat();
  96029. return function (newOrder) {
  96030. q.setFromEuler(this);
  96031. this.setFromQuaternion(q, newOrder);
  96032. };
  96033. }(),
  96034. equals: function (euler) {
  96035. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  96036. },
  96037. fromArray: function (array) {
  96038. this._x = array[0];
  96039. this._y = array[1];
  96040. this._z = array[2];
  96041. if (array[3] !== undefined) this._order = array[3];
  96042. this.onChangeCallback();
  96043. return this;
  96044. },
  96045. toArray: function () {
  96046. return [this._x, this._y, this._z, this._order];
  96047. },
  96048. onChange: function (callback) {
  96049. this.onChangeCallback = callback;
  96050. return this;
  96051. },
  96052. onChangeCallback: function () { },
  96053. clone: function () {
  96054. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  96055. }
  96056. };
  96057. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  96058. var c1 = OIMO.cos(oy * 0.5);//heading
  96059. var s1 = OIMO.sin(oy * 0.5);
  96060. var c2 = OIMO.cos(oz * 0.5);//altitude
  96061. var s2 = OIMO.sin(oz * 0.5);
  96062. var c3 = OIMO.cos(ox * 0.5);//bank
  96063. var s3 = OIMO.sin(ox * 0.5);
  96064. var c1c2 = c1 * c2;
  96065. var s1s2 = s1 * s2;
  96066. var w = c1c2 * c3 - s1s2 * s3;
  96067. var x = c1c2 * s3 + s1s2 * c3;
  96068. var y = s1 * c2 * c3 + c1 * s2 * s3;
  96069. var z = c1 * s2 * c3 - s1 * c2 * s3;
  96070. var angle = 2 * OIMO.acos(w);
  96071. var norm = x * x + y * y + z * z;
  96072. if (norm < 0.001) {
  96073. x = 1;
  96074. y = z = 0;
  96075. } else {
  96076. norm = OIMO.sqrt(norm);
  96077. x /= norm;
  96078. y /= norm;
  96079. z /= norm;
  96080. }
  96081. return [angle, x, y, z];
  96082. }
  96083. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  96084. var ch = OIMO.cos(oy);//heading
  96085. var sh = OIMO.sin(oy);
  96086. var ca = OIMO.cos(oz);//altitude
  96087. var sa = OIMO.sin(oz);
  96088. var cb = OIMO.cos(ox);//bank
  96089. var sb = OIMO.sin(ox);
  96090. var mtx = new OIMO.Mat33();
  96091. var te = mtx.elements;
  96092. te[0] = ch * ca;
  96093. te[1] = sh * sb - ch * sa * cb;
  96094. te[2] = ch * sa * sb + sh * cb;
  96095. te[3] = sa;
  96096. te[4] = ca * cb;
  96097. te[5] = -ca * sb;
  96098. te[6] = -sh * ca;
  96099. te[7] = sh * sa * cb + ch * sb;
  96100. te[8] = -sh * sa * sb + ch * cb;
  96101. return mtx;
  96102. }
  96103. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  96104. var te = mtx.elements;
  96105. var x, y, z;
  96106. if (te[3] > 0.998) { // singularity at north pole
  96107. y = OIMO.atan2(te[2], te[8]);
  96108. z = OIMO.PI / 2;
  96109. x = 0;
  96110. } else if (te[3] < -0.998) { // singularity at south pole
  96111. y = OIMO.atan2(te[2], te[8]);
  96112. z = -OIMO.PI / 2;
  96113. x = 0;
  96114. } else {
  96115. y = OIMO.atan2(-te[6], te[0]);
  96116. x = OIMO.atan2(-te[5], te[4]);
  96117. z = OIMO.asin(te[3]);
  96118. }
  96119. return [x, y, z];
  96120. }
  96121. OIMO.unwrapDegrees = function (r) {
  96122. r = r % 360;
  96123. if (r > 180) r -= 360;
  96124. if (r < -180) r += 360;
  96125. return r;
  96126. }
  96127. OIMO.unwrapRadian = function (r) {
  96128. r = r % OIMO.TwoPI;
  96129. if (r > OIMO.PI) r -= OIMO.TwoPI;
  96130. if (r < -OIMO.PI) r += OIMO.TwoPI;
  96131. return r;
  96132. }
  96133. OIMO.Distance3d = function (p1, p2) {
  96134. var xd = p2[0] - p1[0];
  96135. var yd = p2[1] - p1[1];
  96136. var zd = p2[2] - p1[2];
  96137. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  96138. }
  96139. /**
  96140. * The base class of all type of the constraints.
  96141. * @author saharan
  96142. */
  96143. OIMO.Constraint = function () {
  96144. // The parent world of the constraint.
  96145. this.parent = null;
  96146. // The first body of the constraint.
  96147. this.body1 = null;
  96148. // The second body of the constraint.
  96149. this.body2 = null;
  96150. // Internal
  96151. this.addedToIsland = false;
  96152. }
  96153. OIMO.Constraint.prototype = {
  96154. constructor: OIMO.Constraint,
  96155. /**
  96156. * Prepare for solving the constraint.
  96157. * @param timeStep
  96158. * @param invTimeStep
  96159. */
  96160. preSolve: function (timeStep, invTimeStep) {
  96161. OIMO.Error("Constraint", "Inheritance error.");
  96162. },
  96163. /**
  96164. * Solve the constraint.
  96165. * This is usually called iteratively.
  96166. */
  96167. solve: function () {
  96168. OIMO.Error("Constraint", "Inheritance error.");
  96169. },
  96170. /**
  96171. * Do the post-processing.
  96172. */
  96173. postSolve: function () {
  96174. OIMO.Error("Constraint", "Inheritance error.");
  96175. }
  96176. }
  96177. /**
  96178. * Joints are used to constrain the motion between two rigid bodies.
  96179. * @author saharan
  96180. * @author lo-th
  96181. */
  96182. OIMO.Joint = function (config) {
  96183. OIMO.Constraint.call(this);
  96184. // joint name
  96185. this.name = "";
  96186. // The type of the joint.
  96187. this.type = OIMO.JOINT_NULL;
  96188. // The previous joint in the world.
  96189. this.prev = null;
  96190. // The next joint in the world.
  96191. this.next = null;
  96192. this.body1 = config.body1;
  96193. this.body2 = config.body2;
  96194. // The anchor point on the first rigid body in local coordinate system.
  96195. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  96196. // The anchor point on the second rigid body in local coordinate system.
  96197. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  96198. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  96199. this.relativeAnchorPoint1 = new OIMO.Vec3();
  96200. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  96201. this.relativeAnchorPoint2 = new OIMO.Vec3();
  96202. // The anchor point on the first rigid body in world coordinate system.
  96203. this.anchorPoint1 = new OIMO.Vec3();
  96204. // The anchor point on the second rigid body in world coordinate system.
  96205. this.anchorPoint2 = new OIMO.Vec3();
  96206. // Whether allow collision between connected rigid bodies or not.
  96207. this.allowCollision = config.allowCollision;
  96208. this.b1Link = new OIMO.JointLink(this);
  96209. this.b2Link = new OIMO.JointLink(this);
  96210. this.matrix = new OIMO.Mat44();
  96211. };
  96212. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  96213. OIMO.Joint.prototype.constructor = OIMO.Joint;
  96214. // Update all the anchor points.
  96215. OIMO.Joint.prototype.updateAnchorPoints = function () {
  96216. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  96217. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  96218. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  96219. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  96220. };
  96221. // Attach the joint from the bodies.
  96222. OIMO.Joint.prototype.attach = function () {
  96223. this.b1Link.body = this.body2;
  96224. this.b2Link.body = this.body1;
  96225. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  96226. else this.b1Link.next = null;
  96227. this.body1.jointLink = this.b1Link;
  96228. this.body1.numJoints++;
  96229. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  96230. else this.b2Link.next = null;
  96231. this.body2.jointLink = this.b2Link;
  96232. this.body2.numJoints++;
  96233. };
  96234. // Detach the joint from the bodies.
  96235. OIMO.Joint.prototype.detach = function () {
  96236. var prev = this.b1Link.prev;
  96237. var next = this.b1Link.next;
  96238. if (prev != null) prev.next = next;
  96239. if (next != null) next.prev = prev;
  96240. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  96241. this.b1Link.prev = null;
  96242. this.b1Link.next = null;
  96243. this.b1Link.body = null;
  96244. this.body1.numJoints--;
  96245. prev = this.b2Link.prev;
  96246. next = this.b2Link.next;
  96247. if (prev != null) prev.next = next;
  96248. if (next != null) next.prev = prev;
  96249. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  96250. this.b2Link.prev = null;
  96251. this.b2Link.next = null;
  96252. this.b2Link.body = null;
  96253. this.body2.numJoints--;
  96254. this.b1Link.body = null;
  96255. this.b2Link.body = null;
  96256. };
  96257. // Awake the bodies.
  96258. OIMO.Joint.prototype.awake = function () {
  96259. this.body1.awake();
  96260. this.body2.awake();
  96261. };
  96262. // calculation function
  96263. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  96264. };
  96265. OIMO.Joint.prototype.solve = function () {
  96266. };
  96267. OIMO.Joint.prototype.postSolve = function () {
  96268. };
  96269. // Delete process
  96270. OIMO.Joint.prototype.remove = function () {
  96271. this.dispose();
  96272. };
  96273. OIMO.Joint.prototype.dispose = function () {
  96274. this.parent.removeJoint(this);
  96275. };
  96276. // Three js add
  96277. OIMO.Joint.prototype.getPosition = function () {
  96278. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  96279. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  96280. return [p1, p2];
  96281. };
  96282. OIMO.Joint.prototype.getMatrix = function () {
  96283. var m = this.matrix.elements;
  96284. var p1 = this.anchorPoint1;
  96285. var p2 = this.anchorPoint2;
  96286. m[0] = p1.x * OIMO.WORLD_SCALE;
  96287. m[1] = p1.y * OIMO.WORLD_SCALE;
  96288. m[2] = p1.z * OIMO.WORLD_SCALE;
  96289. m[3] = 0;
  96290. m[4] = p2.x * OIMO.WORLD_SCALE;
  96291. m[5] = p2.y * OIMO.WORLD_SCALE;
  96292. m[6] = p2.z * OIMO.WORLD_SCALE;
  96293. m[7] = 0;
  96294. return m;
  96295. };
  96296. /**
  96297. * A joint configuration holds all configuration data for constructing a joint.
  96298. * Joint configurations can be reused safely.
  96299. * @author saharan
  96300. */
  96301. OIMO.JointConfig = function () {
  96302. // The first rigid body of the joint.
  96303. this.body1 = null;
  96304. // The second rigid body of the joint.
  96305. this.body2 = null;
  96306. // The anchor point on the first rigid body in local coordinate system.
  96307. this.localAnchorPoint1 = new OIMO.Vec3();
  96308. // The anchor point on the second rigid body in local coordinate system.
  96309. this.localAnchorPoint2 = new OIMO.Vec3();
  96310. // The axis in the first body's coordinate system.
  96311. // his property is available in some joints.
  96312. this.localAxis1 = new OIMO.Vec3();
  96313. // The axis in the second body's coordinate system.
  96314. // This property is available in some joints.
  96315. this.localAxis2 = new OIMO.Vec3();
  96316. // Whether allow collision between connected rigid bodies or not.
  96317. this.allowCollision = false;
  96318. };
  96319. /**
  96320. * A link list of joints.
  96321. * @author saharan
  96322. */
  96323. OIMO.JointLink = function (joint) {
  96324. // The previous joint link.
  96325. this.prev = null;
  96326. // The next joint link.
  96327. this.next = null;
  96328. // The other rigid body connected to the joint.
  96329. this.body = null;
  96330. // The joint of the link.
  96331. this.joint = joint;
  96332. };
  96333. /**
  96334. * An information of limit and motor.
  96335. * @author saharan
  96336. */
  96337. OIMO.LimitMotor = function (axis, fixed) {
  96338. fixed = fixed || false;
  96339. // The axis of the constraint.
  96340. this.axis = axis;
  96341. // The current angle for rotational constraints.
  96342. this.angle = 0;
  96343. // The lower limit. Set lower > upper to disable
  96344. this.lowerLimit = fixed ? 0 : 1;
  96345. //if(fixed)this.lowerLimit = 0;
  96346. //else this.lowerLimit = 1;
  96347. // The upper limit. Set lower > upper to disable.
  96348. this.upperLimit = 0;
  96349. // The target motor speed.
  96350. this.motorSpeed = 0;
  96351. // The maximum motor force or torque. Set 0 to disable.
  96352. this.maxMotorForce = 0;
  96353. // The frequency of the spring. Set 0 to disable.
  96354. this.frequency = 0;
  96355. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  96356. this.dampingRatio = 0;
  96357. };
  96358. OIMO.LimitMotor.prototype = {
  96359. constructor: OIMO.LimitMotor,
  96360. /**
  96361. * Set limit data into this constraint.
  96362. * @param lowerLimit
  96363. * @param upperLimit
  96364. */
  96365. setLimit: function (lowerLimit, upperLimit) {
  96366. this.lowerLimit = lowerLimit;
  96367. this.upperLimit = upperLimit;
  96368. },
  96369. /**
  96370. * Set motor data into this constraint.
  96371. * @param motorSpeed
  96372. * @param maxMotorForce
  96373. */
  96374. setMotor: function (motorSpeed, maxMotorForce) {
  96375. this.motorSpeed = motorSpeed;
  96376. this.maxMotorForce = maxMotorForce;
  96377. },
  96378. /**
  96379. * Set spring data into this constraint.
  96380. * @param frequency
  96381. * @param dampingRatio
  96382. */
  96383. setSpring: function (frequency, dampingRatio) {
  96384. this.frequency = frequency;
  96385. this.dampingRatio = dampingRatio;
  96386. }
  96387. };
  96388. /**
  96389. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  96390. * @author saharan
  96391. * @author lo-th
  96392. */
  96393. OIMO.BallAndSocketJoint = function (config) {
  96394. OIMO.Joint.call(this, config);
  96395. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  96396. this.lc = new OIMO.LinearConstraint(this);
  96397. };
  96398. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  96399. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  96400. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96401. this.updateAnchorPoints();
  96402. this.lc.preSolve(timeStep, invTimeStep);
  96403. };
  96404. OIMO.BallAndSocketJoint.prototype.solve = function () {
  96405. this.lc.solve();
  96406. };
  96407. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  96408. };
  96409. /**
  96410. * A distance joint limits the distance between two anchor points on rigid bodies.
  96411. * @author saharan
  96412. * @author lo-th
  96413. */
  96414. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  96415. OIMO.Joint.call(this, config);
  96416. this.type = OIMO.JOINT_DISTANCE;
  96417. this.normal = new OIMO.Vec3();
  96418. this.nr = new OIMO.Vec3();
  96419. // The limit and motor information of the joint.
  96420. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  96421. this.limitMotor.lowerLimit = minDistance;
  96422. this.limitMotor.upperLimit = maxDistance;
  96423. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  96424. };
  96425. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  96426. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  96427. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96428. this.updateAnchorPoints();
  96429. //var nr = this.nr;
  96430. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  96431. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  96432. //if(len>0) len = 1/len;
  96433. //this.normal.scale( nr, len );
  96434. this.normal.normalize(this.nr);
  96435. this.t.preSolve(timeStep, invTimeStep);
  96436. };
  96437. OIMO.DistanceJoint.prototype.solve = function () {
  96438. this.t.solve();
  96439. };
  96440. OIMO.DistanceJoint.prototype.postSolve = function () {
  96441. };
  96442. /**
  96443. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  96444. * @author saharan
  96445. * @author lo-th
  96446. */
  96447. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  96448. OIMO.Joint.call(this, config);
  96449. this.type = OIMO.JOINT_HINGE;
  96450. // The axis in the first body's coordinate system.
  96451. this.localAxis1 = config.localAxis1.clone().norm();
  96452. // The axis in the second body's coordinate system.
  96453. this.localAxis2 = config.localAxis2.clone().norm();
  96454. // make angle axis 1
  96455. this.localAngle1 = new OIMO.Vec3(
  96456. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  96457. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  96458. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  96459. ).norm();
  96460. // make angle axis 2
  96461. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96462. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  96463. this.nor = new OIMO.Vec3();
  96464. this.tan = new OIMO.Vec3();
  96465. this.bin = new OIMO.Vec3();
  96466. this.ax1 = new OIMO.Vec3();
  96467. this.ax2 = new OIMO.Vec3();
  96468. this.an1 = new OIMO.Vec3();
  96469. this.an2 = new OIMO.Vec3();
  96470. // The rotational limit and motor information of the joint.
  96471. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  96472. this.limitMotor.lowerLimit = lowerAngleLimit;
  96473. this.limitMotor.upperLimit = upperAngleLimit;
  96474. this.lc = new OIMO.LinearConstraint(this);
  96475. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  96476. };
  96477. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  96478. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  96479. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96480. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  96481. this.updateAnchorPoints();
  96482. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  96483. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  96484. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  96485. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  96486. this.nor.set(
  96487. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  96488. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  96489. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  96490. ).norm();
  96491. this.tan.set(
  96492. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  96493. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  96494. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  96495. ).norm();
  96496. this.bin.set(
  96497. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  96498. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  96499. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  96500. );
  96501. // calculate hinge angle
  96502. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  96503. if (
  96504. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  96505. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  96506. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  96507. ) {
  96508. this.limitMotor.angle = -limite;
  96509. } else {
  96510. this.limitMotor.angle = limite;
  96511. }
  96512. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  96513. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  96514. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  96515. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  96516. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  96517. this.r3.preSolve(timeStep, invTimeStep);
  96518. this.lc.preSolve(timeStep, invTimeStep);
  96519. };
  96520. OIMO.HingeJoint.prototype.solve = function () {
  96521. this.r3.solve();
  96522. this.lc.solve();
  96523. };
  96524. OIMO.HingeJoint.prototype.postSolve = function () {
  96525. };
  96526. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  96527. if (cos > 1) return 0;
  96528. else if (cos < -1) return OIMO.PI;
  96529. else return OIMO.acos(cos);
  96530. };
  96531. /**
  96532. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  96533. * @author saharan
  96534. * @author lo-th
  96535. */
  96536. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  96537. OIMO.Joint.call(this, config);
  96538. this.type = OIMO.JOINT_PRISMATIC;
  96539. // The axis in the first body's coordinate system.
  96540. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  96541. // The axis in the second body's coordinate system.
  96542. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  96543. this.localAxis1X = this.localAxis1.x;
  96544. this.localAxis1Y = this.localAxis1.y;
  96545. this.localAxis1Z = this.localAxis1.z;
  96546. this.localAxis2X = this.localAxis2.x;
  96547. this.localAxis2Y = this.localAxis2.y;
  96548. this.localAxis2Z = this.localAxis2.z;
  96549. this.nor = new OIMO.Vec3();
  96550. this.tan = new OIMO.Vec3();
  96551. this.bin = new OIMO.Vec3();
  96552. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96553. // The translational limit and motor information of the joint.
  96554. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  96555. this.limitMotor.lowerLimit = lowerTranslation;
  96556. this.limitMotor.upperLimit = upperTranslation;
  96557. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  96558. };
  96559. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  96560. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  96561. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96562. var tmpM;
  96563. var tmp1X;
  96564. var tmp1Y;
  96565. var tmp1Z;
  96566. this.updateAnchorPoints();
  96567. tmpM = this.body1.rotation.elements;
  96568. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  96569. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  96570. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  96571. tmpM = this.body2.rotation.elements;
  96572. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  96573. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  96574. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  96575. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  96576. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  96577. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  96578. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  96579. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96580. nx *= tmp1X;
  96581. ny *= tmp1X;
  96582. nz *= tmp1X;
  96583. var tx = ny * nx - nz * nz;
  96584. var ty = -nz * ny - nx * nx;
  96585. var tz = nx * nz + ny * ny;
  96586. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  96587. tx *= tmp1X;
  96588. ty *= tmp1X;
  96589. tz *= tmp1X;
  96590. var bx = ny * tz - nz * ty;
  96591. var by = nz * tx - nx * tz;
  96592. var bz = nx * ty - ny * tx;
  96593. this.nor.init(nx, ny, nz);
  96594. this.tan.init(tx, ty, tz);
  96595. this.bin.init(bx, by, bz);
  96596. this.ac.preSolve(timeStep, invTimeStep);
  96597. this.t3.preSolve(timeStep, invTimeStep);
  96598. };
  96599. OIMO.PrismaticJoint.prototype.solve = function () {
  96600. this.ac.solve();
  96601. this.t3.solve();
  96602. };
  96603. OIMO.PrismaticJoint.prototype.postSolve = function () {
  96604. };
  96605. /**
  96606. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  96607. * @author saharan
  96608. * @author lo-th
  96609. */
  96610. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  96611. OIMO.Joint.call(this, config);
  96612. this.type = OIMO.JOINT_SLIDER;
  96613. // The first axis in local coordinate system.
  96614. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  96615. // The second axis in local coordinate system.
  96616. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  96617. var len;
  96618. this.localAxis1X = this.localAxis1.x;
  96619. this.localAxis1Y = this.localAxis1.y;
  96620. this.localAxis1Z = this.localAxis1.z;
  96621. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  96622. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  96623. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  96624. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  96625. this.localAngAxis1X *= len;
  96626. this.localAngAxis1Y *= len;
  96627. this.localAngAxis1Z *= len;
  96628. this.localAxis2X = this.localAxis2.x;
  96629. this.localAxis2Y = this.localAxis2.y;
  96630. this.localAxis2Z = this.localAxis2.z;
  96631. // make angle axis 2
  96632. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96633. var tarc = arc.elements;
  96634. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  96635. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  96636. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  96637. this.nor = new OIMO.Vec3();
  96638. this.tan = new OIMO.Vec3();
  96639. this.bin = new OIMO.Vec3();
  96640. // The limit and motor for the rotation
  96641. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  96642. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  96643. // The limit and motor for the translation.
  96644. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  96645. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  96646. this.translationalLimitMotor.upperLimit = upperTranslation;
  96647. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  96648. };
  96649. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  96650. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  96651. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96652. var tmpM;
  96653. var tmp1X;
  96654. var tmp1Y;
  96655. var tmp1Z;
  96656. this.updateAnchorPoints();
  96657. tmpM = this.body1.rotation.elements;
  96658. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  96659. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  96660. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  96661. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  96662. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  96663. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  96664. tmpM = this.body2.rotation.elements;
  96665. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  96666. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  96667. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  96668. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  96669. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  96670. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  96671. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  96672. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  96673. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  96674. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  96675. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96676. nx *= tmp1X;
  96677. ny *= tmp1X;
  96678. nz *= tmp1X;
  96679. var tx = ny * nx - nz * nz;
  96680. var ty = -nz * ny - nx * nx;
  96681. var tz = nx * nz + ny * ny;
  96682. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  96683. tx *= tmp1X;
  96684. ty *= tmp1X;
  96685. tz *= tmp1X;
  96686. var bx = ny * tz - nz * ty;
  96687. var by = nz * tx - nx * tz;
  96688. var bz = nx * ty - ny * tx;
  96689. this.nor.init(nx, ny, nz);
  96690. this.tan.init(tx, ty, tz);
  96691. this.bin.init(bx, by, bz);
  96692. // ----------------------------------------------
  96693. // calculate hinge angle
  96694. // ----------------------------------------------
  96695. if (
  96696. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  96697. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  96698. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  96699. ) {
  96700. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  96701. } else {
  96702. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  96703. }
  96704. // angular error
  96705. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  96706. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  96707. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  96708. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  96709. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  96710. this.r3.preSolve(timeStep, invTimeStep);
  96711. this.t3.preSolve(timeStep, invTimeStep);
  96712. };
  96713. OIMO.SliderJoint.prototype.solve = function () {
  96714. this.r3.solve();
  96715. this.t3.solve();
  96716. };
  96717. OIMO.SliderJoint.prototype.postSolve = function () {
  96718. };
  96719. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  96720. if (cos > 1) return 0;
  96721. else if (cos < -1) return OIMO.PI;
  96722. else return OIMO.acos(cos);
  96723. };
  96724. /**
  96725. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  96726. * The wheel joint also allows for relative translation for the suspension.
  96727. * @author saharan
  96728. * @author lo-th
  96729. */
  96730. OIMO.WheelJoint = function (config) {
  96731. OIMO.Joint.call(this, config);
  96732. this.type = OIMO.JOINT_WHEEL;
  96733. // The first axis in local coordinate system.
  96734. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  96735. // The second axis in local coordinate system.
  96736. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  96737. var len;
  96738. this.localAxis1X = this.localAxis1.x;
  96739. this.localAxis1Y = this.localAxis1.y;
  96740. this.localAxis1Z = this.localAxis1.z;
  96741. this.localAxis2X = this.localAxis2.x;
  96742. this.localAxis2Y = this.localAxis2.y;
  96743. this.localAxis2Z = this.localAxis2.z;
  96744. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  96745. if (dot > -1 && dot < 1) {
  96746. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  96747. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  96748. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  96749. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  96750. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  96751. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  96752. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  96753. this.localAngAxis1X *= len;
  96754. this.localAngAxis1Y *= len;
  96755. this.localAngAxis1Z *= len;
  96756. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  96757. this.localAngAxis2X *= len;
  96758. this.localAngAxis2Y *= len;
  96759. this.localAngAxis2Z *= len;
  96760. } else {
  96761. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  96762. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  96763. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  96764. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  96765. this.localAngAxis1X *= len;
  96766. this.localAngAxis1Y *= len;
  96767. this.localAngAxis1Z *= len;
  96768. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96769. var tarc = arc.elements;
  96770. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  96771. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  96772. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  96773. }
  96774. this.nor = new OIMO.Vec3();
  96775. this.tan = new OIMO.Vec3();
  96776. this.bin = new OIMO.Vec3();
  96777. // The translational limit and motor information of the joint.
  96778. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  96779. this.translationalLimitMotor.frequency = 8;
  96780. this.translationalLimitMotor.dampingRatio = 1;
  96781. // The first rotational limit and motor information of the joint.
  96782. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  96783. // The second rotational limit and motor information of the joint.
  96784. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  96785. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  96786. this.t3.weight = 1;
  96787. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  96788. };
  96789. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  96790. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  96791. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96792. var tmpM;
  96793. var tmp1X;
  96794. var tmp1Y;
  96795. var tmp1Z;
  96796. this.updateAnchorPoints();
  96797. tmpM = this.body1.rotation.elements;
  96798. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  96799. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  96800. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  96801. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  96802. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  96803. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  96804. tmpM = this.body2.rotation.elements;
  96805. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  96806. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  96807. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  96808. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  96809. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  96810. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  96811. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  96812. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  96813. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  96814. } else {
  96815. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  96816. }
  96817. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  96818. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  96819. } else {
  96820. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  96821. }
  96822. var nx = y2 * z1 - z2 * y1;
  96823. var ny = z2 * x1 - x2 * z1;
  96824. var nz = x2 * y1 - y2 * x1;
  96825. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  96826. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96827. nx *= tmp1X;
  96828. ny *= tmp1X;
  96829. nz *= tmp1X;
  96830. var tx = ny * z2 - nz * y2;
  96831. var ty = nz * x2 - nx * z2;
  96832. var tz = nx * y2 - ny * x2;
  96833. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  96834. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96835. tx *= tmp1X;
  96836. ty *= tmp1X;
  96837. tz *= tmp1X;
  96838. var bx = y1 * nz - z1 * ny;
  96839. var by = z1 * nx - x1 * nz;
  96840. var bz = x1 * ny - y1 * nx;
  96841. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  96842. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96843. bx *= tmp1X;
  96844. by *= tmp1X;
  96845. bz *= tmp1X;
  96846. this.nor.init(nx, ny, nz);
  96847. this.tan.init(tx, ty, tz);
  96848. this.bin.init(bx, by, bz);
  96849. this.r3.preSolve(timeStep, invTimeStep);
  96850. this.t3.preSolve(timeStep, invTimeStep);
  96851. };
  96852. OIMO.WheelJoint.prototype.solve = function () {
  96853. this.r3.solve();
  96854. this.t3.solve();
  96855. };
  96856. OIMO.WheelJoint.prototype.postSolve = function () {
  96857. };
  96858. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  96859. if (cos > 1) return 0;
  96860. else if (cos < -1) return OIMO.PI;
  96861. else return OIMO.acos(cos);
  96862. };
  96863. /**
  96864. * An angular constraint for all axes for various joints.
  96865. * @author saharan
  96866. */
  96867. OIMO.AngularConstraint = function (joint, targetOrientation) {
  96868. this.joint = joint;
  96869. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  96870. this.relativeOrientation = new OIMO.Quat();
  96871. this.ii1 = null;
  96872. this.ii2 = null;
  96873. this.dd = null;
  96874. this.vel = new OIMO.Vec3();
  96875. this.imp = new OIMO.Vec3();
  96876. this.rn0 = new OIMO.Vec3();
  96877. this.rn1 = new OIMO.Vec3();
  96878. this.rn2 = new OIMO.Vec3();
  96879. this.b1 = joint.body1;
  96880. this.b2 = joint.body2;
  96881. this.a1 = this.b1.angularVelocity;
  96882. this.a2 = this.b2.angularVelocity;
  96883. this.i1 = this.b1.inverseInertia;
  96884. this.i2 = this.b2.inverseInertia;
  96885. };
  96886. OIMO.AngularConstraint.prototype = {
  96887. constructor: OIMO.AngularConstraint,
  96888. preSolve: function (timeStep, invTimeStep) {
  96889. var inv, len, v, vv;
  96890. this.ii1 = this.i1.clone();
  96891. this.ii2 = this.i2.clone();
  96892. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  96893. 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]));
  96894. this.dd = new OIMO.Mat33(
  96895. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  96896. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  96897. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  96898. ).multiply(inv);
  96899. this.relativeOrientation.invert(this.b1.orientation);
  96900. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  96901. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  96902. inv = this.relativeOrientation.s * 2;
  96903. this.vel.scale(this.relativeOrientation, inv);
  96904. len = this.vel.length();
  96905. if (len > 0.02) {
  96906. len = (0.02 - len) / len * invTimeStep * 0.05;
  96907. this.vel.scaleEqual(len);
  96908. } else {
  96909. this.vel.init();
  96910. }
  96911. this.rn1.mulMat(this.ii1, this.imp);
  96912. this.rn2.mulMat(this.ii2, this.imp);
  96913. this.a1.addEqual(this.rn1);
  96914. this.a2.subEqual(this.rn2);
  96915. },
  96916. solve: function () {
  96917. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  96918. this.rn0.mulMat(this.dd, r);
  96919. this.rn1.mulMat(this.ii1, this.rn0);
  96920. this.rn2.mulMat(this.ii2, this.rn0);
  96921. this.imp.addEqual(this.rn0);
  96922. this.a1.addEqual(this.rn1);
  96923. this.a2.subEqual(this.rn2);
  96924. }
  96925. };
  96926. /**
  96927. * A linear constraint for all axes for various joints.
  96928. * @author saharan
  96929. */
  96930. OIMO.LinearConstraint = function (joint) {
  96931. this.m1 = NaN;
  96932. this.m2 = NaN;
  96933. this.ii1 = null;
  96934. this.ii2 = null;
  96935. this.dd = null;
  96936. this.r1x = NaN;
  96937. this.r1y = NaN;
  96938. this.r1z = NaN;
  96939. this.r2x = NaN;
  96940. this.r2y = NaN;
  96941. this.r2z = NaN;
  96942. this.ax1x = NaN;
  96943. this.ax1y = NaN;
  96944. this.ax1z = NaN;
  96945. this.ay1x = NaN;
  96946. this.ay1y = NaN;
  96947. this.ay1z = NaN;
  96948. this.az1x = NaN;
  96949. this.az1y = NaN;
  96950. this.az1z = NaN;
  96951. this.ax2x = NaN;
  96952. this.ax2y = NaN;
  96953. this.ax2z = NaN;
  96954. this.ay2x = NaN;
  96955. this.ay2y = NaN;
  96956. this.ay2z = NaN;
  96957. this.az2x = NaN;
  96958. this.az2y = NaN;
  96959. this.az2z = NaN;
  96960. this.vel = NaN;
  96961. this.velx = NaN;
  96962. this.vely = NaN;
  96963. this.velz = NaN;
  96964. this.joint = joint;
  96965. this.r1 = joint.relativeAnchorPoint1;
  96966. this.r2 = joint.relativeAnchorPoint2;
  96967. this.p1 = joint.anchorPoint1;
  96968. this.p2 = joint.anchorPoint2;
  96969. this.b1 = joint.body1;
  96970. this.b2 = joint.body2;
  96971. this.l1 = this.b1.linearVelocity;
  96972. this.l2 = this.b2.linearVelocity;
  96973. this.a1 = this.b1.angularVelocity;
  96974. this.a2 = this.b2.angularVelocity;
  96975. this.i1 = this.b1.inverseInertia;
  96976. this.i2 = this.b2.inverseInertia;
  96977. this.impx = 0;
  96978. this.impy = 0;
  96979. this.impz = 0;
  96980. }
  96981. OIMO.LinearConstraint.prototype = {
  96982. constructor: OIMO.LinearConstraint,
  96983. preSolve: function (timeStep, invTimeStep) {
  96984. this.r1x = this.r1.x;
  96985. this.r1y = this.r1.y;
  96986. this.r1z = this.r1.z;
  96987. this.r2x = this.r2.x;
  96988. this.r2y = this.r2.y;
  96989. this.r2z = this.r2.z;
  96990. this.m1 = this.b1.inverseMass;
  96991. this.m2 = this.b2.inverseMass;
  96992. this.ii1 = this.i1.clone();
  96993. this.ii2 = this.i2.clone();
  96994. var ii1 = this.ii1.elements;
  96995. var ii2 = this.ii2.elements;
  96996. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  96997. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  96998. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  96999. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  97000. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  97001. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  97002. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  97003. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  97004. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  97005. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  97006. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  97007. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  97008. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  97009. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  97010. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  97011. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  97012. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  97013. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  97014. // calculate point-to-point mass matrix
  97015. // from impulse equation
  97016. //
  97017. // M = ([/m] - [r^][/I][r^]) ^ -1
  97018. //
  97019. // where
  97020. //
  97021. // [/m] = |1/m, 0, 0|
  97022. // |0, 1/m, 0|
  97023. // |0, 0, 1/m|
  97024. //
  97025. // [r^] = |0, -rz, ry|
  97026. // |rz, 0, -rx|
  97027. // |-ry, rx, 0|
  97028. //
  97029. // [/I] = Inverted moment inertia
  97030. var rxx = this.m1 + this.m2;
  97031. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  97032. var k = kk.elements;
  97033. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  97034. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  97035. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  97036. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  97037. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  97038. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  97039. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  97040. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  97041. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  97042. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  97043. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  97044. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  97045. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  97046. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  97047. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  97048. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  97049. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  97050. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  97051. 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]));
  97052. this.dd = new OIMO.Mat33(
  97053. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  97054. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  97055. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  97056. ).multiply(inv);
  97057. this.velx = this.p2.x - this.p1.x;
  97058. this.vely = this.p2.y - this.p1.y;
  97059. this.velz = this.p2.z - this.p1.z;
  97060. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  97061. if (len > 0.005) {
  97062. len = (0.005 - len) / len * invTimeStep * 0.05;
  97063. this.velx *= len;
  97064. this.vely *= len;
  97065. this.velz *= len;
  97066. } else {
  97067. this.velx = 0;
  97068. this.vely = 0;
  97069. this.velz = 0;
  97070. }
  97071. this.impx *= 0.95;
  97072. this.impy *= 0.95;
  97073. this.impz *= 0.95;
  97074. this.l1.x += this.impx * this.m1;
  97075. this.l1.y += this.impy * this.m1;
  97076. this.l1.z += this.impz * this.m1;
  97077. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  97078. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  97079. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  97080. this.l2.x -= this.impx * this.m2;
  97081. this.l2.y -= this.impy * this.m2;
  97082. this.l2.z -= this.impz * this.m2;
  97083. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  97084. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  97085. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  97086. },
  97087. solve: function () {
  97088. var d = this.dd.elements;
  97089. 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;
  97090. 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;
  97091. 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;
  97092. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  97093. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  97094. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  97095. this.impx += nimpx;
  97096. this.impy += nimpy;
  97097. this.impz += nimpz;
  97098. this.l1.x += nimpx * this.m1;
  97099. this.l1.y += nimpy * this.m1;
  97100. this.l1.z += nimpz * this.m1;
  97101. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  97102. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  97103. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  97104. this.l2.x -= nimpx * this.m2;
  97105. this.l2.y -= nimpy * this.m2;
  97106. this.l2.z -= nimpz * this.m2;
  97107. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  97108. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  97109. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  97110. }
  97111. }
  97112. /**
  97113. * A three-axis rotational constraint for various joints.
  97114. * @author saharan
  97115. */
  97116. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  97117. this.cfm1 = NaN;
  97118. this.cfm2 = NaN;
  97119. this.cfm3 = NaN;
  97120. this.i1e00 = NaN;
  97121. this.i1e01 = NaN;
  97122. this.i1e02 = NaN;
  97123. this.i1e10 = NaN;
  97124. this.i1e11 = NaN;
  97125. this.i1e12 = NaN;
  97126. this.i1e20 = NaN;
  97127. this.i1e21 = NaN;
  97128. this.i1e22 = NaN;
  97129. this.i2e00 = NaN;
  97130. this.i2e01 = NaN;
  97131. this.i2e02 = NaN;
  97132. this.i2e10 = NaN;
  97133. this.i2e11 = NaN;
  97134. this.i2e12 = NaN;
  97135. this.i2e20 = NaN;
  97136. this.i2e21 = NaN;
  97137. this.i2e22 = NaN;
  97138. this.ax1 = NaN;
  97139. this.ay1 = NaN;
  97140. this.az1 = NaN;
  97141. this.ax2 = NaN;
  97142. this.ay2 = NaN;
  97143. this.az2 = NaN;
  97144. this.ax3 = NaN;
  97145. this.ay3 = NaN;
  97146. this.az3 = NaN;
  97147. this.a1x1 = NaN; // jacoians
  97148. this.a1y1 = NaN;
  97149. this.a1z1 = NaN;
  97150. this.a2x1 = NaN;
  97151. this.a2y1 = NaN;
  97152. this.a2z1 = NaN;
  97153. this.a1x2 = NaN;
  97154. this.a1y2 = NaN;
  97155. this.a1z2 = NaN;
  97156. this.a2x2 = NaN;
  97157. this.a2y2 = NaN;
  97158. this.a2z2 = NaN;
  97159. this.a1x3 = NaN;
  97160. this.a1y3 = NaN;
  97161. this.a1z3 = NaN;
  97162. this.a2x3 = NaN;
  97163. this.a2y3 = NaN;
  97164. this.a2z3 = NaN;
  97165. this.lowerLimit1 = NaN;
  97166. this.upperLimit1 = NaN;
  97167. this.limitVelocity1 = NaN;
  97168. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97169. this.enableMotor1 = false;
  97170. this.motorSpeed1 = NaN;
  97171. this.maxMotorForce1 = NaN;
  97172. this.maxMotorImpulse1 = NaN;
  97173. this.lowerLimit2 = NaN;
  97174. this.upperLimit2 = NaN;
  97175. this.limitVelocity2 = NaN;
  97176. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97177. this.enableMotor2 = false;
  97178. this.motorSpeed2 = NaN;
  97179. this.maxMotorForce2 = NaN;
  97180. this.maxMotorImpulse2 = NaN;
  97181. this.lowerLimit3 = NaN;
  97182. this.upperLimit3 = NaN;
  97183. this.limitVelocity3 = NaN;
  97184. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97185. this.enableMotor3 = false;
  97186. this.motorSpeed3 = NaN;
  97187. this.maxMotorForce3 = NaN;
  97188. this.maxMotorImpulse3 = NaN;
  97189. this.k00 = NaN; // K = J*M*JT
  97190. this.k01 = NaN;
  97191. this.k02 = NaN;
  97192. this.k10 = NaN;
  97193. this.k11 = NaN;
  97194. this.k12 = NaN;
  97195. this.k20 = NaN;
  97196. this.k21 = NaN;
  97197. this.k22 = NaN;
  97198. this.kv00 = NaN; // diagonals without CFMs
  97199. this.kv11 = NaN;
  97200. this.kv22 = NaN;
  97201. this.dv00 = NaN; // ...inverted
  97202. this.dv11 = NaN;
  97203. this.dv22 = NaN;
  97204. this.d00 = NaN; // K^-1
  97205. this.d01 = NaN;
  97206. this.d02 = NaN;
  97207. this.d10 = NaN;
  97208. this.d11 = NaN;
  97209. this.d12 = NaN;
  97210. this.d20 = NaN;
  97211. this.d21 = NaN;
  97212. this.d22 = NaN;
  97213. this.limitMotor1 = limitMotor1;
  97214. this.limitMotor2 = limitMotor2;
  97215. this.limitMotor3 = limitMotor3;
  97216. this.b1 = joint.body1;
  97217. this.b2 = joint.body2;
  97218. this.a1 = this.b1.angularVelocity;
  97219. this.a2 = this.b2.angularVelocity;
  97220. this.i1 = this.b1.inverseInertia;
  97221. this.i2 = this.b2.inverseInertia;
  97222. this.limitImpulse1 = 0;
  97223. this.motorImpulse1 = 0;
  97224. this.limitImpulse2 = 0;
  97225. this.motorImpulse2 = 0;
  97226. this.limitImpulse3 = 0;
  97227. this.motorImpulse3 = 0;
  97228. }
  97229. OIMO.Rotational3Constraint.prototype = {
  97230. constructor: OIMO.Rotational3Constraint,
  97231. preSolve: function (timeStep, invTimeStep) {
  97232. this.ax1 = this.limitMotor1.axis.x;
  97233. this.ay1 = this.limitMotor1.axis.y;
  97234. this.az1 = this.limitMotor1.axis.z;
  97235. this.ax2 = this.limitMotor2.axis.x;
  97236. this.ay2 = this.limitMotor2.axis.y;
  97237. this.az2 = this.limitMotor2.axis.z;
  97238. this.ax3 = this.limitMotor3.axis.x;
  97239. this.ay3 = this.limitMotor3.axis.y;
  97240. this.az3 = this.limitMotor3.axis.z;
  97241. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  97242. this.upperLimit1 = this.limitMotor1.upperLimit;
  97243. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  97244. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  97245. this.enableMotor1 = this.maxMotorForce1 > 0;
  97246. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  97247. this.upperLimit2 = this.limitMotor2.upperLimit;
  97248. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  97249. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  97250. this.enableMotor2 = this.maxMotorForce2 > 0;
  97251. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  97252. this.upperLimit3 = this.limitMotor3.upperLimit;
  97253. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  97254. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  97255. this.enableMotor3 = this.maxMotorForce3 > 0;
  97256. var ti1 = this.i1.elements;
  97257. var ti2 = this.i2.elements;
  97258. this.i1e00 = ti1[0];
  97259. this.i1e01 = ti1[1];
  97260. this.i1e02 = ti1[2];
  97261. this.i1e10 = ti1[3];
  97262. this.i1e11 = ti1[4];
  97263. this.i1e12 = ti1[5];
  97264. this.i1e20 = ti1[6];
  97265. this.i1e21 = ti1[7];
  97266. this.i1e22 = ti1[8];
  97267. this.i2e00 = ti2[0];
  97268. this.i2e01 = ti2[1];
  97269. this.i2e02 = ti2[2];
  97270. this.i2e10 = ti2[3];
  97271. this.i2e11 = ti2[4];
  97272. this.i2e12 = ti2[5];
  97273. this.i2e20 = ti2[6];
  97274. this.i2e21 = ti2[7];
  97275. this.i2e22 = ti2[8];
  97276. var frequency1 = this.limitMotor1.frequency;
  97277. var frequency2 = this.limitMotor2.frequency;
  97278. var frequency3 = this.limitMotor3.frequency;
  97279. var enableSpring1 = frequency1 > 0;
  97280. var enableSpring2 = frequency2 > 0;
  97281. var enableSpring3 = frequency3 > 0;
  97282. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  97283. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  97284. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  97285. var angle1 = this.limitMotor1.angle;
  97286. if (enableLimit1) {
  97287. if (this.lowerLimit1 == this.upperLimit1) {
  97288. if (this.limitState1 != 0) {
  97289. this.limitState1 = 0;
  97290. this.limitImpulse1 = 0;
  97291. }
  97292. this.limitVelocity1 = this.lowerLimit1 - angle1;
  97293. } else if (angle1 < this.lowerLimit1) {
  97294. if (this.limitState1 != -1) {
  97295. this.limitState1 = -1;
  97296. this.limitImpulse1 = 0;
  97297. }
  97298. this.limitVelocity1 = this.lowerLimit1 - angle1;
  97299. } else if (angle1 > this.upperLimit1) {
  97300. if (this.limitState1 != 1) {
  97301. this.limitState1 = 1;
  97302. this.limitImpulse1 = 0;
  97303. }
  97304. this.limitVelocity1 = this.upperLimit1 - angle1;
  97305. } else {
  97306. this.limitState1 = 2;
  97307. this.limitImpulse1 = 0;
  97308. this.limitVelocity1 = 0;
  97309. }
  97310. if (!enableSpring1) {
  97311. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  97312. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  97313. else this.limitVelocity1 = 0;
  97314. }
  97315. } else {
  97316. this.limitState1 = 2;
  97317. this.limitImpulse1 = 0;
  97318. }
  97319. var angle2 = this.limitMotor2.angle;
  97320. if (enableLimit2) {
  97321. if (this.lowerLimit2 == this.upperLimit2) {
  97322. if (this.limitState2 != 0) {
  97323. this.limitState2 = 0;
  97324. this.limitImpulse2 = 0;
  97325. }
  97326. this.limitVelocity2 = this.lowerLimit2 - angle2;
  97327. } else if (angle2 < this.lowerLimit2) {
  97328. if (this.limitState2 != -1) {
  97329. this.limitState2 = -1;
  97330. this.limitImpulse2 = 0;
  97331. }
  97332. this.limitVelocity2 = this.lowerLimit2 - angle2;
  97333. } else if (angle2 > this.upperLimit2) {
  97334. if (this.limitState2 != 1) {
  97335. this.limitState2 = 1;
  97336. this.limitImpulse2 = 0;
  97337. }
  97338. this.limitVelocity2 = this.upperLimit2 - angle2;
  97339. } else {
  97340. this.limitState2 = 2;
  97341. this.limitImpulse2 = 0;
  97342. this.limitVelocity2 = 0;
  97343. }
  97344. if (!enableSpring2) {
  97345. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  97346. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  97347. else this.limitVelocity2 = 0;
  97348. }
  97349. } else {
  97350. this.limitState2 = 2;
  97351. this.limitImpulse2 = 0;
  97352. }
  97353. var angle3 = this.limitMotor3.angle;
  97354. if (enableLimit3) {
  97355. if (this.lowerLimit3 == this.upperLimit3) {
  97356. if (this.limitState3 != 0) {
  97357. this.limitState3 = 0;
  97358. this.limitImpulse3 = 0;
  97359. }
  97360. this.limitVelocity3 = this.lowerLimit3 - angle3;
  97361. } else if (angle3 < this.lowerLimit3) {
  97362. if (this.limitState3 != -1) {
  97363. this.limitState3 = -1;
  97364. this.limitImpulse3 = 0;
  97365. }
  97366. this.limitVelocity3 = this.lowerLimit3 - angle3;
  97367. } else if (angle3 > this.upperLimit3) {
  97368. if (this.limitState3 != 1) {
  97369. this.limitState3 = 1;
  97370. this.limitImpulse3 = 0;
  97371. }
  97372. this.limitVelocity3 = this.upperLimit3 - angle3;
  97373. } else {
  97374. this.limitState3 = 2;
  97375. this.limitImpulse3 = 0;
  97376. this.limitVelocity3 = 0;
  97377. }
  97378. if (!enableSpring3) {
  97379. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  97380. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  97381. else this.limitVelocity3 = 0;
  97382. }
  97383. } else {
  97384. this.limitState3 = 2;
  97385. this.limitImpulse3 = 0;
  97386. }
  97387. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  97388. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  97389. } else {
  97390. this.motorImpulse1 = 0;
  97391. this.maxMotorImpulse1 = 0;
  97392. }
  97393. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  97394. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  97395. } else {
  97396. this.motorImpulse2 = 0;
  97397. this.maxMotorImpulse2 = 0;
  97398. }
  97399. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  97400. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  97401. } else {
  97402. this.motorImpulse3 = 0;
  97403. this.maxMotorImpulse3 = 0;
  97404. }
  97405. // build jacobians
  97406. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  97407. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  97408. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  97409. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  97410. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  97411. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  97412. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  97413. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  97414. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  97415. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  97416. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  97417. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  97418. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  97419. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  97420. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  97421. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  97422. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  97423. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  97424. // build an impulse matrix
  97425. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  97426. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  97427. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  97428. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  97429. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  97430. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  97431. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  97432. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  97433. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  97434. this.kv00 = this.k00;
  97435. this.kv11 = this.k11;
  97436. this.kv22 = this.k22;
  97437. this.dv00 = 1 / this.kv00;
  97438. this.dv11 = 1 / this.kv11;
  97439. this.dv22 = 1 / this.kv22;
  97440. if (enableSpring1 && this.limitState1 != 2) {
  97441. var omega = 6.2831853 * frequency1;
  97442. var k = omega * omega * timeStep;
  97443. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  97444. this.cfm1 = this.kv00 * dmp;
  97445. this.limitVelocity1 *= k * dmp;
  97446. } else {
  97447. this.cfm1 = 0;
  97448. this.limitVelocity1 *= invTimeStep * 0.05;
  97449. }
  97450. if (enableSpring2 && this.limitState2 != 2) {
  97451. omega = 6.2831853 * frequency2;
  97452. k = omega * omega * timeStep;
  97453. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  97454. this.cfm2 = this.kv11 * dmp;
  97455. this.limitVelocity2 *= k * dmp;
  97456. } else {
  97457. this.cfm2 = 0;
  97458. this.limitVelocity2 *= invTimeStep * 0.05;
  97459. }
  97460. if (enableSpring3 && this.limitState3 != 2) {
  97461. omega = 6.2831853 * frequency3;
  97462. k = omega * omega * timeStep;
  97463. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  97464. this.cfm3 = this.kv22 * dmp;
  97465. this.limitVelocity3 *= k * dmp;
  97466. } else {
  97467. this.cfm3 = 0;
  97468. this.limitVelocity3 *= invTimeStep * 0.05;
  97469. }
  97470. this.k00 += this.cfm1;
  97471. this.k11 += this.cfm2;
  97472. this.k22 += this.cfm3;
  97473. var inv = 1 / (
  97474. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  97475. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  97476. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  97477. );
  97478. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  97479. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  97480. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  97481. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  97482. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  97483. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  97484. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  97485. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  97486. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  97487. this.limitImpulse1 *= 0.95;
  97488. this.motorImpulse1 *= 0.95;
  97489. this.limitImpulse2 *= 0.95;
  97490. this.motorImpulse2 *= 0.95;
  97491. this.limitImpulse3 *= 0.95;
  97492. this.motorImpulse3 *= 0.95;
  97493. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  97494. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  97495. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  97496. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  97497. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  97498. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  97499. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  97500. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  97501. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  97502. },
  97503. solve_: function () {
  97504. var rvx = this.a2.x - this.a1.x;
  97505. var rvy = this.a2.y - this.a1.y;
  97506. var rvz = this.a2.z - this.a1.z;
  97507. this.limitVelocity3 = 30;
  97508. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  97509. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  97510. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  97511. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  97512. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  97513. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  97514. this.limitImpulse1 += dLimitImpulse1;
  97515. this.limitImpulse2 += dLimitImpulse2;
  97516. this.limitImpulse3 += dLimitImpulse3;
  97517. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  97518. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  97519. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  97520. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  97521. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  97522. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  97523. },
  97524. solve: function () {
  97525. var rvx = this.a2.x - this.a1.x;
  97526. var rvy = this.a2.y - this.a1.y;
  97527. var rvz = this.a2.z - this.a1.z;
  97528. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  97529. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  97530. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  97531. var oldMotorImpulse1 = this.motorImpulse1;
  97532. var oldMotorImpulse2 = this.motorImpulse2;
  97533. var oldMotorImpulse3 = this.motorImpulse3;
  97534. var dMotorImpulse1 = 0;
  97535. var dMotorImpulse2 = 0;
  97536. var dMotorImpulse3 = 0;
  97537. if (this.enableMotor1) {
  97538. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  97539. this.motorImpulse1 += dMotorImpulse1;
  97540. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  97541. this.motorImpulse1 = this.maxMotorImpulse1;
  97542. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  97543. this.motorImpulse1 = -this.maxMotorImpulse1;
  97544. }
  97545. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  97546. }
  97547. if (this.enableMotor2) {
  97548. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  97549. this.motorImpulse2 += dMotorImpulse2;
  97550. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  97551. this.motorImpulse2 = this.maxMotorImpulse2;
  97552. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  97553. this.motorImpulse2 = -this.maxMotorImpulse2;
  97554. }
  97555. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  97556. }
  97557. if (this.enableMotor3) {
  97558. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  97559. this.motorImpulse3 += dMotorImpulse3;
  97560. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  97561. this.motorImpulse3 = this.maxMotorImpulse3;
  97562. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  97563. this.motorImpulse3 = -this.maxMotorImpulse3;
  97564. }
  97565. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  97566. }
  97567. // apply motor impulse to relative velocity
  97568. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  97569. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  97570. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  97571. // subtract target velocity and applied impulse
  97572. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  97573. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  97574. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  97575. var oldLimitImpulse1 = this.limitImpulse1;
  97576. var oldLimitImpulse2 = this.limitImpulse2;
  97577. var oldLimitImpulse3 = this.limitImpulse3;
  97578. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  97579. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  97580. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  97581. this.limitImpulse1 += dLimitImpulse1;
  97582. this.limitImpulse2 += dLimitImpulse2;
  97583. this.limitImpulse3 += dLimitImpulse3;
  97584. // clamp
  97585. var clampState = 0;
  97586. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  97587. dLimitImpulse1 = -oldLimitImpulse1;
  97588. rvn2 += dLimitImpulse1 * this.k10;
  97589. rvn3 += dLimitImpulse1 * this.k20;
  97590. clampState |= 1;
  97591. }
  97592. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  97593. dLimitImpulse2 = -oldLimitImpulse2;
  97594. rvn1 += dLimitImpulse2 * this.k01;
  97595. rvn3 += dLimitImpulse2 * this.k21;
  97596. clampState |= 2;
  97597. }
  97598. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  97599. dLimitImpulse3 = -oldLimitImpulse3;
  97600. rvn1 += dLimitImpulse3 * this.k02;
  97601. rvn2 += dLimitImpulse3 * this.k12;
  97602. clampState |= 4;
  97603. }
  97604. // update un-clamped impulse
  97605. // TODO: isolate division
  97606. var det;
  97607. switch (clampState) {
  97608. case 1: // update 2 3
  97609. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  97610. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  97611. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  97612. break;
  97613. case 2: // update 1 3
  97614. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  97615. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  97616. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  97617. break;
  97618. case 3: // update 3
  97619. dLimitImpulse3 = rvn3 / this.k22;
  97620. break;
  97621. case 4: // update 1 2
  97622. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  97623. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  97624. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  97625. break;
  97626. case 5: // update 2
  97627. dLimitImpulse2 = rvn2 / this.k11;
  97628. break;
  97629. case 6: // update 1
  97630. dLimitImpulse1 = rvn1 / this.k00;
  97631. break;
  97632. }
  97633. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  97634. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  97635. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  97636. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  97637. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  97638. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  97639. // apply impulse
  97640. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  97641. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  97642. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  97643. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  97644. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  97645. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  97646. rvx = this.a2.x - this.a1.x;
  97647. rvy = this.a2.y - this.a1.y;
  97648. rvz = this.a2.z - this.a1.z;
  97649. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  97650. }
  97651. }
  97652. /**
  97653. * A rotational constraint for various joints.
  97654. * @author saharan
  97655. */
  97656. OIMO.RotationalConstraint = function (joint, limitMotor) {
  97657. this.cfm = NaN;
  97658. this.i1e00 = NaN;
  97659. this.i1e01 = NaN;
  97660. this.i1e02 = NaN;
  97661. this.i1e10 = NaN;
  97662. this.i1e11 = NaN;
  97663. this.i1e12 = NaN;
  97664. this.i1e20 = NaN;
  97665. this.i1e21 = NaN;
  97666. this.i1e22 = NaN;
  97667. this.i2e00 = NaN;
  97668. this.i2e01 = NaN;
  97669. this.i2e02 = NaN;
  97670. this.i2e10 = NaN;
  97671. this.i2e11 = NaN;
  97672. this.i2e12 = NaN;
  97673. this.i2e20 = NaN;
  97674. this.i2e21 = NaN;
  97675. this.i2e22 = NaN;
  97676. this.motorDenom = NaN;
  97677. this.invMotorDenom = NaN;
  97678. this.invDenom = NaN;
  97679. this.ax = NaN;
  97680. this.ay = NaN;
  97681. this.az = NaN;
  97682. this.a1x = NaN;
  97683. this.a1y = NaN;
  97684. this.a1z = NaN;
  97685. this.a2x = NaN;
  97686. this.a2y = NaN;
  97687. this.a2z = NaN;
  97688. this.enableLimit = false;
  97689. this.lowerLimit = NaN;
  97690. this.upperLimit = NaN;
  97691. this.limitVelocity = NaN;
  97692. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97693. this.enableMotor = false;
  97694. this.motorSpeed = NaN;
  97695. this.maxMotorForce = NaN;
  97696. this.maxMotorImpulse = NaN;
  97697. this.limitMotor = limitMotor;
  97698. this.b1 = joint.body1;
  97699. this.b2 = joint.body2;
  97700. this.a1 = this.b1.angularVelocity;
  97701. this.a2 = this.b2.angularVelocity;
  97702. this.i1 = this.b1.inverseInertia;
  97703. this.i2 = this.b2.inverseInertia;
  97704. this.limitImpulse = 0;
  97705. this.motorImpulse = 0;
  97706. }
  97707. OIMO.RotationalConstraint.prototype = {
  97708. constructor: OIMO.RotationalConstraint,
  97709. preSolve: function (timeStep, invTimeStep) {
  97710. this.ax = this.limitMotor.axis.x;
  97711. this.ay = this.limitMotor.axis.y;
  97712. this.az = this.limitMotor.axis.z;
  97713. this.lowerLimit = this.limitMotor.lowerLimit;
  97714. this.upperLimit = this.limitMotor.upperLimit;
  97715. this.motorSpeed = this.limitMotor.motorSpeed;
  97716. this.maxMotorForce = this.limitMotor.maxMotorForce;
  97717. this.enableMotor = this.maxMotorForce > 0;
  97718. var ti1 = this.i1.elements;
  97719. var ti2 = this.i2.elements;
  97720. this.i1e00 = ti1[0];
  97721. this.i1e01 = ti1[1];
  97722. this.i1e02 = ti1[2];
  97723. this.i1e10 = ti1[3];
  97724. this.i1e11 = ti1[4];
  97725. this.i1e12 = ti1[5];
  97726. this.i1e20 = ti1[6];
  97727. this.i1e21 = ti1[7];
  97728. this.i1e22 = ti1[8];
  97729. this.i2e00 = ti2[0];
  97730. this.i2e01 = ti2[1];
  97731. this.i2e02 = ti2[2];
  97732. this.i2e10 = ti2[3];
  97733. this.i2e11 = ti2[4];
  97734. this.i2e12 = ti2[5];
  97735. this.i2e20 = ti2[6];
  97736. this.i2e21 = ti2[7];
  97737. this.i2e22 = ti2[8];
  97738. var frequency = this.limitMotor.frequency;
  97739. var enableSpring = frequency > 0;
  97740. var enableLimit = this.lowerLimit <= this.upperLimit;
  97741. var angle = this.limitMotor.angle;
  97742. if (enableLimit) {
  97743. if (this.lowerLimit == this.upperLimit) {
  97744. if (this.limitState != 0) {
  97745. this.limitState = 0;
  97746. this.limitImpulse = 0;
  97747. }
  97748. this.limitVelocity = this.lowerLimit - angle;
  97749. } else if (angle < this.lowerLimit) {
  97750. if (this.limitState != -1) {
  97751. this.limitState = -1;
  97752. this.limitImpulse = 0;
  97753. }
  97754. this.limitVelocity = this.lowerLimit - angle;
  97755. } else if (angle > this.upperLimit) {
  97756. if (this.limitState != 1) {
  97757. this.limitState = 1;
  97758. this.limitImpulse = 0;
  97759. }
  97760. this.limitVelocity = this.upperLimit - angle;
  97761. } else {
  97762. this.limitState = 2;
  97763. this.limitImpulse = 0;
  97764. this.limitVelocity = 0;
  97765. }
  97766. if (!enableSpring) {
  97767. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  97768. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  97769. else this.limitVelocity = 0;
  97770. }
  97771. } else {
  97772. this.limitState = 2;
  97773. this.limitImpulse = 0;
  97774. }
  97775. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  97776. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  97777. } else {
  97778. this.motorImpulse = 0;
  97779. this.maxMotorImpulse = 0;
  97780. }
  97781. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  97782. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  97783. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  97784. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  97785. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  97786. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  97787. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  97788. this.invMotorDenom = 1 / this.motorDenom;
  97789. if (enableSpring && this.limitState != 2) {
  97790. var omega = 6.2831853 * frequency;
  97791. var k = omega * omega * timeStep;
  97792. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  97793. this.cfm = this.motorDenom * dmp;
  97794. this.limitVelocity *= k * dmp;
  97795. } else {
  97796. this.cfm = 0;
  97797. this.limitVelocity *= invTimeStep * 0.05;
  97798. }
  97799. this.invDenom = 1 / (this.motorDenom + this.cfm);
  97800. this.limitImpulse *= 0.95;
  97801. this.motorImpulse *= 0.95;
  97802. var totalImpulse = this.limitImpulse + this.motorImpulse;
  97803. this.a1.x += totalImpulse * this.a1x;
  97804. this.a1.y += totalImpulse * this.a1y;
  97805. this.a1.z += totalImpulse * this.a1z;
  97806. this.a2.x -= totalImpulse * this.a2x;
  97807. this.a2.y -= totalImpulse * this.a2y;
  97808. this.a2.z -= totalImpulse * this.a2z;
  97809. },
  97810. solve: function () {
  97811. 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);
  97812. // motor part
  97813. var newMotorImpulse;
  97814. if (this.enableMotor) {
  97815. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  97816. var oldMotorImpulse = this.motorImpulse;
  97817. this.motorImpulse += newMotorImpulse;
  97818. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  97819. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  97820. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  97821. rvn -= newMotorImpulse * this.motorDenom;
  97822. } else newMotorImpulse = 0;
  97823. // limit part
  97824. var newLimitImpulse;
  97825. if (this.limitState != 2) {
  97826. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  97827. var oldLimitImpulse = this.limitImpulse;
  97828. this.limitImpulse += newLimitImpulse;
  97829. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  97830. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  97831. } else newLimitImpulse = 0;
  97832. var totalImpulse = newLimitImpulse + newMotorImpulse;
  97833. this.a1.x += totalImpulse * this.a1x;
  97834. this.a1.y += totalImpulse * this.a1y;
  97835. this.a1.z += totalImpulse * this.a1z;
  97836. this.a2.x -= totalImpulse * this.a2x;
  97837. this.a2.y -= totalImpulse * this.a2y;
  97838. this.a2.z -= totalImpulse * this.a2z;
  97839. }
  97840. }
  97841. /**
  97842. * A three-axis translational constraint for various joints.
  97843. * @author saharan
  97844. */
  97845. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  97846. this.m1 = NaN;
  97847. this.m2 = NaN;
  97848. this.i1e00 = NaN;
  97849. this.i1e01 = NaN;
  97850. this.i1e02 = NaN;
  97851. this.i1e10 = NaN;
  97852. this.i1e11 = NaN;
  97853. this.i1e12 = NaN;
  97854. this.i1e20 = NaN;
  97855. this.i1e21 = NaN;
  97856. this.i1e22 = NaN;
  97857. this.i2e00 = NaN;
  97858. this.i2e01 = NaN;
  97859. this.i2e02 = NaN;
  97860. this.i2e10 = NaN;
  97861. this.i2e11 = NaN;
  97862. this.i2e12 = NaN;
  97863. this.i2e20 = NaN;
  97864. this.i2e21 = NaN;
  97865. this.i2e22 = NaN;
  97866. this.ax1 = NaN;
  97867. this.ay1 = NaN;
  97868. this.az1 = NaN;
  97869. this.ax2 = NaN;
  97870. this.ay2 = NaN;
  97871. this.az2 = NaN;
  97872. this.ax3 = NaN;
  97873. this.ay3 = NaN;
  97874. this.az3 = NaN;
  97875. this.r1x = NaN;
  97876. this.r1y = NaN;
  97877. this.r1z = NaN;
  97878. this.r2x = NaN;
  97879. this.r2y = NaN;
  97880. this.r2z = NaN;
  97881. this.t1x1 = NaN;// jacobians
  97882. this.t1y1 = NaN;
  97883. this.t1z1 = NaN;
  97884. this.t2x1 = NaN;
  97885. this.t2y1 = NaN;
  97886. this.t2z1 = NaN;
  97887. this.l1x1 = NaN;
  97888. this.l1y1 = NaN;
  97889. this.l1z1 = NaN;
  97890. this.l2x1 = NaN;
  97891. this.l2y1 = NaN;
  97892. this.l2z1 = NaN;
  97893. this.a1x1 = NaN;
  97894. this.a1y1 = NaN;
  97895. this.a1z1 = NaN;
  97896. this.a2x1 = NaN;
  97897. this.a2y1 = NaN;
  97898. this.a2z1 = NaN;
  97899. this.t1x2 = NaN;
  97900. this.t1y2 = NaN;
  97901. this.t1z2 = NaN;
  97902. this.t2x2 = NaN;
  97903. this.t2y2 = NaN;
  97904. this.t2z2 = NaN;
  97905. this.l1x2 = NaN;
  97906. this.l1y2 = NaN;
  97907. this.l1z2 = NaN;
  97908. this.l2x2 = NaN;
  97909. this.l2y2 = NaN;
  97910. this.l2z2 = NaN;
  97911. this.a1x2 = NaN;
  97912. this.a1y2 = NaN;
  97913. this.a1z2 = NaN;
  97914. this.a2x2 = NaN;
  97915. this.a2y2 = NaN;
  97916. this.a2z2 = NaN;
  97917. this.t1x3 = NaN;
  97918. this.t1y3 = NaN;
  97919. this.t1z3 = NaN;
  97920. this.t2x3 = NaN;
  97921. this.t2y3 = NaN;
  97922. this.t2z3 = NaN;
  97923. this.l1x3 = NaN;
  97924. this.l1y3 = NaN;
  97925. this.l1z3 = NaN;
  97926. this.l2x3 = NaN;
  97927. this.l2y3 = NaN;
  97928. this.l2z3 = NaN;
  97929. this.a1x3 = NaN;
  97930. this.a1y3 = NaN;
  97931. this.a1z3 = NaN;
  97932. this.a2x3 = NaN;
  97933. this.a2y3 = NaN;
  97934. this.a2z3 = NaN;
  97935. this.lowerLimit1 = NaN;
  97936. this.upperLimit1 = NaN;
  97937. this.limitVelocity1 = NaN;
  97938. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  97939. this.enableMotor1 = false;
  97940. this.motorSpeed1 = NaN;
  97941. this.maxMotorForce1 = NaN;
  97942. this.maxMotorImpulse1 = NaN;
  97943. this.lowerLimit2 = NaN;
  97944. this.upperLimit2 = NaN;
  97945. this.limitVelocity2 = NaN;
  97946. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  97947. this.enableMotor2 = false;
  97948. this.motorSpeed2 = NaN;
  97949. this.maxMotorForce2 = NaN;
  97950. this.maxMotorImpulse2 = NaN;
  97951. this.lowerLimit3 = NaN;
  97952. this.upperLimit3 = NaN;
  97953. this.limitVelocity3 = NaN;
  97954. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  97955. this.enableMotor3 = false;
  97956. this.motorSpeed3 = NaN;
  97957. this.maxMotorForce3 = NaN;
  97958. this.maxMotorImpulse3 = NaN;
  97959. this.k00 = NaN; // K = J*M*JT
  97960. this.k01 = NaN;
  97961. this.k02 = NaN;
  97962. this.k10 = NaN;
  97963. this.k11 = NaN;
  97964. this.k12 = NaN;
  97965. this.k20 = NaN;
  97966. this.k21 = NaN;
  97967. this.k22 = NaN;
  97968. this.kv00 = NaN; // diagonals without CFMs
  97969. this.kv11 = NaN;
  97970. this.kv22 = NaN;
  97971. this.dv00 = NaN; // ...inverted
  97972. this.dv11 = NaN;
  97973. this.dv22 = NaN;
  97974. this.d00 = NaN; // K^-1
  97975. this.d01 = NaN;
  97976. this.d02 = NaN;
  97977. this.d10 = NaN;
  97978. this.d11 = NaN;
  97979. this.d12 = NaN;
  97980. this.d20 = NaN;
  97981. this.d21 = NaN;
  97982. this.d22 = NaN;
  97983. this.limitMotor1 = limitMotor1;
  97984. this.limitMotor2 = limitMotor2;
  97985. this.limitMotor3 = limitMotor3;
  97986. this.b1 = joint.body1;
  97987. this.b2 = joint.body2;
  97988. this.p1 = joint.anchorPoint1;
  97989. this.p2 = joint.anchorPoint2;
  97990. this.r1 = joint.relativeAnchorPoint1;
  97991. this.r2 = joint.relativeAnchorPoint2;
  97992. this.l1 = this.b1.linearVelocity;
  97993. this.l2 = this.b2.linearVelocity;
  97994. this.a1 = this.b1.angularVelocity;
  97995. this.a2 = this.b2.angularVelocity;
  97996. this.i1 = this.b1.inverseInertia;
  97997. this.i2 = this.b2.inverseInertia;
  97998. this.limitImpulse1 = 0;
  97999. this.motorImpulse1 = 0;
  98000. this.limitImpulse2 = 0;
  98001. this.motorImpulse2 = 0;
  98002. this.limitImpulse3 = 0;
  98003. this.motorImpulse3 = 0;
  98004. this.cfm1 = 0;// Constraint Force Mixing
  98005. this.cfm2 = 0;
  98006. this.cfm3 = 0;
  98007. this.weight = -1;
  98008. }
  98009. OIMO.Translational3Constraint.prototype = {
  98010. constructor: OIMO.Translational3Constraint,
  98011. preSolve: function (timeStep, invTimeStep) {
  98012. this.ax1 = this.limitMotor1.axis.x;
  98013. this.ay1 = this.limitMotor1.axis.y;
  98014. this.az1 = this.limitMotor1.axis.z;
  98015. this.ax2 = this.limitMotor2.axis.x;
  98016. this.ay2 = this.limitMotor2.axis.y;
  98017. this.az2 = this.limitMotor2.axis.z;
  98018. this.ax3 = this.limitMotor3.axis.x;
  98019. this.ay3 = this.limitMotor3.axis.y;
  98020. this.az3 = this.limitMotor3.axis.z;
  98021. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  98022. this.upperLimit1 = this.limitMotor1.upperLimit;
  98023. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  98024. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  98025. this.enableMotor1 = this.maxMotorForce1 > 0;
  98026. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  98027. this.upperLimit2 = this.limitMotor2.upperLimit;
  98028. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  98029. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  98030. this.enableMotor2 = this.maxMotorForce2 > 0;
  98031. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  98032. this.upperLimit3 = this.limitMotor3.upperLimit;
  98033. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  98034. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  98035. this.enableMotor3 = this.maxMotorForce3 > 0;
  98036. this.m1 = this.b1.inverseMass;
  98037. this.m2 = this.b2.inverseMass;
  98038. var ti1 = this.i1.elements;
  98039. var ti2 = this.i2.elements;
  98040. this.i1e00 = ti1[0];
  98041. this.i1e01 = ti1[1];
  98042. this.i1e02 = ti1[2];
  98043. this.i1e10 = ti1[3];
  98044. this.i1e11 = ti1[4];
  98045. this.i1e12 = ti1[5];
  98046. this.i1e20 = ti1[6];
  98047. this.i1e21 = ti1[7];
  98048. this.i1e22 = ti1[8];
  98049. this.i2e00 = ti2[0];
  98050. this.i2e01 = ti2[1];
  98051. this.i2e02 = ti2[2];
  98052. this.i2e10 = ti2[3];
  98053. this.i2e11 = ti2[4];
  98054. this.i2e12 = ti2[5];
  98055. this.i2e20 = ti2[6];
  98056. this.i2e21 = ti2[7];
  98057. this.i2e22 = ti2[8];
  98058. var dx = this.p2.x - this.p1.x;
  98059. var dy = this.p2.y - this.p1.y;
  98060. var dz = this.p2.z - this.p1.z;
  98061. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  98062. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  98063. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  98064. var frequency1 = this.limitMotor1.frequency;
  98065. var frequency2 = this.limitMotor2.frequency;
  98066. var frequency3 = this.limitMotor3.frequency;
  98067. var enableSpring1 = frequency1 > 0;
  98068. var enableSpring2 = frequency2 > 0;
  98069. var enableSpring3 = frequency3 > 0;
  98070. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  98071. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  98072. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  98073. // for stability
  98074. if (enableSpring1 && d1 > 20 || d1 < -20) {
  98075. enableSpring1 = false;
  98076. }
  98077. if (enableSpring2 && d2 > 20 || d2 < -20) {
  98078. enableSpring2 = false;
  98079. }
  98080. if (enableSpring3 && d3 > 20 || d3 < -20) {
  98081. enableSpring3 = false;
  98082. }
  98083. if (enableLimit1) {
  98084. if (this.lowerLimit1 == this.upperLimit1) {
  98085. if (this.limitState1 != 0) {
  98086. this.limitState1 = 0;
  98087. this.limitImpulse1 = 0;
  98088. }
  98089. this.limitVelocity1 = this.lowerLimit1 - d1;
  98090. if (!enableSpring1) d1 = this.lowerLimit1;
  98091. } else if (d1 < this.lowerLimit1) {
  98092. if (this.limitState1 != -1) {
  98093. this.limitState1 = -1;
  98094. this.limitImpulse1 = 0;
  98095. }
  98096. this.limitVelocity1 = this.lowerLimit1 - d1;
  98097. if (!enableSpring1) d1 = this.lowerLimit1;
  98098. } else if (d1 > this.upperLimit1) {
  98099. if (this.limitState1 != 1) {
  98100. this.limitState1 = 1;
  98101. this.limitImpulse1 = 0;
  98102. }
  98103. this.limitVelocity1 = this.upperLimit1 - d1;
  98104. if (!enableSpring1) d1 = this.upperLimit1;
  98105. } else {
  98106. this.limitState1 = 2;
  98107. this.limitImpulse1 = 0;
  98108. this.limitVelocity1 = 0;
  98109. }
  98110. if (!enableSpring1) {
  98111. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  98112. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  98113. else this.limitVelocity1 = 0;
  98114. }
  98115. } else {
  98116. this.limitState1 = 2;
  98117. this.limitImpulse1 = 0;
  98118. }
  98119. if (enableLimit2) {
  98120. if (this.lowerLimit2 == this.upperLimit2) {
  98121. if (this.limitState2 != 0) {
  98122. this.limitState2 = 0;
  98123. this.limitImpulse2 = 0;
  98124. }
  98125. this.limitVelocity2 = this.lowerLimit2 - d2;
  98126. if (!enableSpring2) d2 = this.lowerLimit2;
  98127. } else if (d2 < this.lowerLimit2) {
  98128. if (this.limitState2 != -1) {
  98129. this.limitState2 = -1;
  98130. this.limitImpulse2 = 0;
  98131. }
  98132. this.limitVelocity2 = this.lowerLimit2 - d2;
  98133. if (!enableSpring2) d2 = this.lowerLimit2;
  98134. } else if (d2 > this.upperLimit2) {
  98135. if (this.limitState2 != 1) {
  98136. this.limitState2 = 1;
  98137. this.limitImpulse2 = 0;
  98138. }
  98139. this.limitVelocity2 = this.upperLimit2 - d2;
  98140. if (!enableSpring2) d2 = this.upperLimit2;
  98141. } else {
  98142. this.limitState2 = 2;
  98143. this.limitImpulse2 = 0;
  98144. this.limitVelocity2 = 0;
  98145. }
  98146. if (!enableSpring2) {
  98147. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  98148. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  98149. else this.limitVelocity2 = 0;
  98150. }
  98151. } else {
  98152. this.limitState2 = 2;
  98153. this.limitImpulse2 = 0;
  98154. }
  98155. if (enableLimit3) {
  98156. if (this.lowerLimit3 == this.upperLimit3) {
  98157. if (this.limitState3 != 0) {
  98158. this.limitState3 = 0;
  98159. this.limitImpulse3 = 0;
  98160. }
  98161. this.limitVelocity3 = this.lowerLimit3 - d3;
  98162. if (!enableSpring3) d3 = this.lowerLimit3;
  98163. } else if (d3 < this.lowerLimit3) {
  98164. if (this.limitState3 != -1) {
  98165. this.limitState3 = -1;
  98166. this.limitImpulse3 = 0;
  98167. }
  98168. this.limitVelocity3 = this.lowerLimit3 - d3;
  98169. if (!enableSpring3) d3 = this.lowerLimit3;
  98170. } else if (d3 > this.upperLimit3) {
  98171. if (this.limitState3 != 1) {
  98172. this.limitState3 = 1;
  98173. this.limitImpulse3 = 0;
  98174. }
  98175. this.limitVelocity3 = this.upperLimit3 - d3;
  98176. if (!enableSpring3) d3 = this.upperLimit3;
  98177. } else {
  98178. this.limitState3 = 2;
  98179. this.limitImpulse3 = 0;
  98180. this.limitVelocity3 = 0;
  98181. }
  98182. if (!enableSpring3) {
  98183. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  98184. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  98185. else this.limitVelocity3 = 0;
  98186. }
  98187. } else {
  98188. this.limitState3 = 2;
  98189. this.limitImpulse3 = 0;
  98190. }
  98191. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  98192. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  98193. } else {
  98194. this.motorImpulse1 = 0;
  98195. this.maxMotorImpulse1 = 0;
  98196. }
  98197. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  98198. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  98199. } else {
  98200. this.motorImpulse2 = 0;
  98201. this.maxMotorImpulse2 = 0;
  98202. }
  98203. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  98204. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  98205. } else {
  98206. this.motorImpulse3 = 0;
  98207. this.maxMotorImpulse3 = 0;
  98208. }
  98209. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  98210. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  98211. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  98212. var w1 = this.m2 / (this.m1 + this.m2);
  98213. if (this.weight >= 0) w1 = this.weight; // use given weight
  98214. var w2 = 1 - w1;
  98215. this.r1x = this.r1.x + rdx * w1;
  98216. this.r1y = this.r1.y + rdy * w1;
  98217. this.r1z = this.r1.z + rdz * w1;
  98218. this.r2x = this.r2.x - rdx * w2;
  98219. this.r2y = this.r2.y - rdy * w2;
  98220. this.r2z = this.r2.z - rdz * w2;
  98221. // build jacobians
  98222. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  98223. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  98224. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  98225. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  98226. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  98227. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  98228. this.l1x1 = this.ax1 * this.m1;
  98229. this.l1y1 = this.ay1 * this.m1;
  98230. this.l1z1 = this.az1 * this.m1;
  98231. this.l2x1 = this.ax1 * this.m2;
  98232. this.l2y1 = this.ay1 * this.m2;
  98233. this.l2z1 = this.az1 * this.m2;
  98234. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  98235. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  98236. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  98237. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  98238. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  98239. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  98240. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  98241. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  98242. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  98243. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  98244. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  98245. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  98246. this.l1x2 = this.ax2 * this.m1;
  98247. this.l1y2 = this.ay2 * this.m1;
  98248. this.l1z2 = this.az2 * this.m1;
  98249. this.l2x2 = this.ax2 * this.m2;
  98250. this.l2y2 = this.ay2 * this.m2;
  98251. this.l2z2 = this.az2 * this.m2;
  98252. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  98253. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  98254. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  98255. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  98256. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  98257. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  98258. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  98259. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  98260. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  98261. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  98262. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  98263. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  98264. this.l1x3 = this.ax3 * this.m1;
  98265. this.l1y3 = this.ay3 * this.m1;
  98266. this.l1z3 = this.az3 * this.m1;
  98267. this.l2x3 = this.ax3 * this.m2;
  98268. this.l2y3 = this.ay3 * this.m2;
  98269. this.l2z3 = this.az3 * this.m2;
  98270. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  98271. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  98272. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  98273. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  98274. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  98275. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  98276. // build an impulse matrix
  98277. var m12 = this.m1 + this.m2;
  98278. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  98279. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  98280. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  98281. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  98282. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  98283. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  98284. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  98285. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  98286. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  98287. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  98288. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  98289. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  98290. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  98291. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  98292. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  98293. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  98294. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  98295. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  98296. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  98297. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  98298. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  98299. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  98300. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  98301. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  98302. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  98303. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  98304. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  98305. this.kv00 = this.k00;
  98306. this.kv11 = this.k11;
  98307. this.kv22 = this.k22;
  98308. this.dv00 = 1 / this.kv00;
  98309. this.dv11 = 1 / this.kv11;
  98310. this.dv22 = 1 / this.kv22;
  98311. if (enableSpring1 && this.limitState1 != 2) {
  98312. var omega = 6.2831853 * frequency1;
  98313. var k = omega * omega * timeStep;
  98314. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  98315. this.cfm1 = this.kv00 * dmp;
  98316. this.limitVelocity1 *= k * dmp;
  98317. } else {
  98318. this.cfm1 = 0;
  98319. this.limitVelocity1 *= invTimeStep * 0.05;
  98320. }
  98321. if (enableSpring2 && this.limitState2 != 2) {
  98322. omega = 6.2831853 * frequency2;
  98323. k = omega * omega * timeStep;
  98324. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  98325. this.cfm2 = this.kv11 * dmp;
  98326. this.limitVelocity2 *= k * dmp;
  98327. } else {
  98328. this.cfm2 = 0;
  98329. this.limitVelocity2 *= invTimeStep * 0.05;
  98330. }
  98331. if (enableSpring3 && this.limitState3 != 2) {
  98332. omega = 6.2831853 * frequency3;
  98333. k = omega * omega * timeStep;
  98334. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  98335. this.cfm3 = this.kv22 * dmp;
  98336. this.limitVelocity3 *= k * dmp;
  98337. } else {
  98338. this.cfm3 = 0;
  98339. this.limitVelocity3 *= invTimeStep * 0.05;
  98340. }
  98341. this.k00 += this.cfm1;
  98342. this.k11 += this.cfm2;
  98343. this.k22 += this.cfm3;
  98344. var inv = 1 / (
  98345. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  98346. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  98347. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  98348. );
  98349. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  98350. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  98351. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  98352. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  98353. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  98354. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  98355. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  98356. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  98357. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  98358. // warm starting
  98359. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  98360. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  98361. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  98362. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  98363. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  98364. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  98365. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  98366. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  98367. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  98368. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  98369. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  98370. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  98371. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  98372. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  98373. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  98374. },
  98375. solve: function () {
  98376. 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;
  98377. 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;
  98378. 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;
  98379. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  98380. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  98381. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  98382. var oldMotorImpulse1 = this.motorImpulse1;
  98383. var oldMotorImpulse2 = this.motorImpulse2;
  98384. var oldMotorImpulse3 = this.motorImpulse3;
  98385. var dMotorImpulse1 = 0;
  98386. var dMotorImpulse2 = 0;
  98387. var dMotorImpulse3 = 0;
  98388. if (this.enableMotor1) {
  98389. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  98390. this.motorImpulse1 += dMotorImpulse1;
  98391. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  98392. this.motorImpulse1 = this.maxMotorImpulse1;
  98393. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  98394. this.motorImpulse1 = -this.maxMotorImpulse1;
  98395. }
  98396. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  98397. }
  98398. if (this.enableMotor2) {
  98399. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  98400. this.motorImpulse2 += dMotorImpulse2;
  98401. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  98402. this.motorImpulse2 = this.maxMotorImpulse2;
  98403. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  98404. this.motorImpulse2 = -this.maxMotorImpulse2;
  98405. }
  98406. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  98407. }
  98408. if (this.enableMotor3) {
  98409. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  98410. this.motorImpulse3 += dMotorImpulse3;
  98411. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  98412. this.motorImpulse3 = this.maxMotorImpulse3;
  98413. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  98414. this.motorImpulse3 = -this.maxMotorImpulse3;
  98415. }
  98416. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  98417. }
  98418. // apply motor impulse to relative velocity
  98419. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  98420. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  98421. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  98422. // subtract target velocity and applied impulse
  98423. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  98424. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  98425. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  98426. var oldLimitImpulse1 = this.limitImpulse1;
  98427. var oldLimitImpulse2 = this.limitImpulse2;
  98428. var oldLimitImpulse3 = this.limitImpulse3;
  98429. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  98430. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  98431. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  98432. this.limitImpulse1 += dLimitImpulse1;
  98433. this.limitImpulse2 += dLimitImpulse2;
  98434. this.limitImpulse3 += dLimitImpulse3;
  98435. // clamp
  98436. var clampState = 0;
  98437. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  98438. dLimitImpulse1 = -oldLimitImpulse1;
  98439. rvn2 += dLimitImpulse1 * this.k10;
  98440. rvn3 += dLimitImpulse1 * this.k20;
  98441. clampState |= 1;
  98442. }
  98443. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  98444. dLimitImpulse2 = -oldLimitImpulse2;
  98445. rvn1 += dLimitImpulse2 * this.k01;
  98446. rvn3 += dLimitImpulse2 * this.k21;
  98447. clampState |= 2;
  98448. }
  98449. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  98450. dLimitImpulse3 = -oldLimitImpulse3;
  98451. rvn1 += dLimitImpulse3 * this.k02;
  98452. rvn2 += dLimitImpulse3 * this.k12;
  98453. clampState |= 4;
  98454. }
  98455. // update un-clamped impulse
  98456. // TODO: isolate division
  98457. var det;
  98458. switch (clampState) {
  98459. case 1:// update 2 3
  98460. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  98461. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  98462. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  98463. break;
  98464. case 2:// update 1 3
  98465. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  98466. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  98467. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  98468. break;
  98469. case 3:// update 3
  98470. dLimitImpulse3 = rvn3 / this.k22;
  98471. break;
  98472. case 4:// update 1 2
  98473. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  98474. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  98475. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  98476. break;
  98477. case 5:// update 2
  98478. dLimitImpulse2 = rvn2 / this.k11;
  98479. break;
  98480. case 6:// update 1
  98481. dLimitImpulse1 = rvn1 / this.k00;
  98482. break;
  98483. }
  98484. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  98485. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  98486. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  98487. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  98488. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  98489. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  98490. // apply impulse
  98491. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  98492. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  98493. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  98494. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  98495. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  98496. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  98497. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  98498. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  98499. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  98500. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  98501. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  98502. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  98503. }
  98504. }
  98505. /**
  98506. * A translational constraint for various joints.
  98507. * @author saharan
  98508. */
  98509. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  98510. this.cfm = NaN;
  98511. this.m1 = NaN;
  98512. this.m2 = NaN;
  98513. this.i1e00 = NaN;
  98514. this.i1e01 = NaN;
  98515. this.i1e02 = NaN;
  98516. this.i1e10 = NaN;
  98517. this.i1e11 = NaN;
  98518. this.i1e12 = NaN;
  98519. this.i1e20 = NaN;
  98520. this.i1e21 = NaN;
  98521. this.i1e22 = NaN;
  98522. this.i2e00 = NaN;
  98523. this.i2e01 = NaN;
  98524. this.i2e02 = NaN;
  98525. this.i2e10 = NaN;
  98526. this.i2e11 = NaN;
  98527. this.i2e12 = NaN;
  98528. this.i2e20 = NaN;
  98529. this.i2e21 = NaN;
  98530. this.i2e22 = NaN;
  98531. this.motorDenom = NaN;
  98532. this.invMotorDenom = NaN;
  98533. this.invDenom = NaN;
  98534. this.ax = NaN;
  98535. this.ay = NaN;
  98536. this.az = NaN;
  98537. this.r1x = NaN;
  98538. this.r1y = NaN;
  98539. this.r1z = NaN;
  98540. this.r2x = NaN;
  98541. this.r2y = NaN;
  98542. this.r2z = NaN;
  98543. this.t1x = NaN;
  98544. this.t1y = NaN;
  98545. this.t1z = NaN;
  98546. this.t2x = NaN;
  98547. this.t2y = NaN;
  98548. this.t2z = NaN;
  98549. this.l1x = NaN;
  98550. this.l1y = NaN;
  98551. this.l1z = NaN;
  98552. this.l2x = NaN;
  98553. this.l2y = NaN;
  98554. this.l2z = NaN;
  98555. this.a1x = NaN;
  98556. this.a1y = NaN;
  98557. this.a1z = NaN;
  98558. this.a2x = NaN;
  98559. this.a2y = NaN;
  98560. this.a2z = NaN;
  98561. this.lowerLimit = NaN;
  98562. this.upperLimit = NaN;
  98563. this.limitVelocity = NaN;
  98564. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  98565. this.enableMotor = false;
  98566. this.motorSpeed = NaN;
  98567. this.maxMotorForce = NaN;
  98568. this.maxMotorImpulse = NaN;
  98569. this.limitMotor = limitMotor;
  98570. this.b1 = joint.body1;
  98571. this.b2 = joint.body2;
  98572. this.p1 = joint.anchorPoint1;
  98573. this.p2 = joint.anchorPoint2;
  98574. this.r1 = joint.relativeAnchorPoint1;
  98575. this.r2 = joint.relativeAnchorPoint2;
  98576. this.l1 = this.b1.linearVelocity;
  98577. this.l2 = this.b2.linearVelocity;
  98578. this.a1 = this.b1.angularVelocity;
  98579. this.a2 = this.b2.angularVelocity;
  98580. this.i1 = this.b1.inverseInertia;
  98581. this.i2 = this.b2.inverseInertia;
  98582. this.limitImpulse = 0;
  98583. this.motorImpulse = 0;
  98584. }
  98585. OIMO.TranslationalConstraint.prototype = {
  98586. constructor: OIMO.TranslationalConstraint,
  98587. preSolve: function (timeStep, invTimeStep) {
  98588. this.ax = this.limitMotor.axis.x;
  98589. this.ay = this.limitMotor.axis.y;
  98590. this.az = this.limitMotor.axis.z;
  98591. this.lowerLimit = this.limitMotor.lowerLimit;
  98592. this.upperLimit = this.limitMotor.upperLimit;
  98593. this.motorSpeed = this.limitMotor.motorSpeed;
  98594. this.maxMotorForce = this.limitMotor.maxMotorForce;
  98595. this.enableMotor = this.maxMotorForce > 0;
  98596. this.m1 = this.b1.inverseMass;
  98597. this.m2 = this.b2.inverseMass;
  98598. var ti1 = this.i1.elements;
  98599. var ti2 = this.i2.elements;
  98600. this.i1e00 = ti1[0];
  98601. this.i1e01 = ti1[1];
  98602. this.i1e02 = ti1[2];
  98603. this.i1e10 = ti1[3];
  98604. this.i1e11 = ti1[4];
  98605. this.i1e12 = ti1[5];
  98606. this.i1e20 = ti1[6];
  98607. this.i1e21 = ti1[7];
  98608. this.i1e22 = ti1[8];
  98609. this.i2e00 = ti2[0];
  98610. this.i2e01 = ti2[1];
  98611. this.i2e02 = ti2[2];
  98612. this.i2e10 = ti2[3];
  98613. this.i2e11 = ti2[4];
  98614. this.i2e12 = ti2[5];
  98615. this.i2e20 = ti2[6];
  98616. this.i2e21 = ti2[7];
  98617. this.i2e22 = ti2[8];
  98618. var dx = this.p2.x - this.p1.x;
  98619. var dy = this.p2.y - this.p1.y;
  98620. var dz = this.p2.z - this.p1.z;
  98621. var d = dx * this.ax + dy * this.ay + dz * this.az;
  98622. var frequency = this.limitMotor.frequency;
  98623. var enableSpring = frequency > 0;
  98624. var enableLimit = this.lowerLimit <= this.upperLimit;
  98625. if (enableSpring && d > 20 || d < -20) {
  98626. enableSpring = false;
  98627. }
  98628. if (enableLimit) {
  98629. if (this.lowerLimit == this.upperLimit) {
  98630. if (this.limitState != 0) {
  98631. this.limitState = 0;
  98632. this.limitImpulse = 0;
  98633. }
  98634. this.limitVelocity = this.lowerLimit - d;
  98635. if (!enableSpring) d = this.lowerLimit;
  98636. } else if (d < this.lowerLimit) {
  98637. if (this.limitState != -1) {
  98638. this.limitState = -1;
  98639. this.limitImpulse = 0;
  98640. }
  98641. this.limitVelocity = this.lowerLimit - d;
  98642. if (!enableSpring) d = this.lowerLimit;
  98643. } else if (d > this.upperLimit) {
  98644. if (this.limitState != 1) {
  98645. this.limitState = 1;
  98646. this.limitImpulse = 0;
  98647. }
  98648. this.limitVelocity = this.upperLimit - d;
  98649. if (!enableSpring) d = this.upperLimit;
  98650. } else {
  98651. this.limitState = 2;
  98652. this.limitImpulse = 0;
  98653. this.limitVelocity = 0;
  98654. }
  98655. if (!enableSpring) {
  98656. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  98657. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  98658. else this.limitVelocity = 0;
  98659. }
  98660. } else {
  98661. this.limitState = 2;
  98662. this.limitImpulse = 0;
  98663. }
  98664. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  98665. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  98666. } else {
  98667. this.motorImpulse = 0;
  98668. this.maxMotorImpulse = 0;
  98669. }
  98670. var rdx = d * this.ax;
  98671. var rdy = d * this.ay;
  98672. var rdz = d * this.az;
  98673. var w1 = this.m1 / (this.m1 + this.m2);
  98674. var w2 = 1 - w1;
  98675. this.r1x = this.r1.x + rdx * w1;
  98676. this.r1y = this.r1.y + rdy * w1;
  98677. this.r1z = this.r1.z + rdz * w1;
  98678. this.r2x = this.r2.x - rdx * w2;
  98679. this.r2y = this.r2.y - rdy * w2;
  98680. this.r2z = this.r2.z - rdz * w2;
  98681. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  98682. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  98683. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  98684. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  98685. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  98686. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  98687. this.l1x = this.ax * this.m1;
  98688. this.l1y = this.ay * this.m1;
  98689. this.l1z = this.az * this.m1;
  98690. this.l2x = this.ax * this.m2;
  98691. this.l2y = this.ay * this.m2;
  98692. this.l2z = this.az * this.m2;
  98693. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  98694. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  98695. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  98696. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  98697. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  98698. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  98699. this.motorDenom =
  98700. this.m1 + this.m2 +
  98701. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  98702. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  98703. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  98704. this.invMotorDenom = 1 / this.motorDenom;
  98705. if (enableSpring && this.limitState != 2) {
  98706. var omega = 6.2831853 * frequency;
  98707. var k = omega * omega * timeStep;
  98708. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  98709. this.cfm = this.motorDenom * dmp;
  98710. this.limitVelocity *= k * dmp;
  98711. } else {
  98712. this.cfm = 0;
  98713. this.limitVelocity *= invTimeStep * 0.05;
  98714. }
  98715. this.invDenom = 1 / (this.motorDenom + this.cfm);
  98716. var totalImpulse = this.limitImpulse + this.motorImpulse;
  98717. this.l1.x += totalImpulse * this.l1x;
  98718. this.l1.y += totalImpulse * this.l1y;
  98719. this.l1.z += totalImpulse * this.l1z;
  98720. this.a1.x += totalImpulse * this.a1x;
  98721. this.a1.y += totalImpulse * this.a1y;
  98722. this.a1.z += totalImpulse * this.a1z;
  98723. this.l2.x -= totalImpulse * this.l2x;
  98724. this.l2.y -= totalImpulse * this.l2y;
  98725. this.l2.z -= totalImpulse * this.l2z;
  98726. this.a2.x -= totalImpulse * this.a2x;
  98727. this.a2.y -= totalImpulse * this.a2y;
  98728. this.a2.z -= totalImpulse * this.a2z;
  98729. },
  98730. solve: function () {
  98731. var rvn =
  98732. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  98733. 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;
  98734. // motor part
  98735. var newMotorImpulse;
  98736. if (this.enableMotor) {
  98737. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  98738. var oldMotorImpulse = this.motorImpulse;
  98739. this.motorImpulse += newMotorImpulse;
  98740. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  98741. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  98742. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  98743. rvn -= newMotorImpulse * this.motorDenom;
  98744. } else newMotorImpulse = 0;
  98745. // limit part
  98746. var newLimitImpulse;
  98747. if (this.limitState != 2) {
  98748. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  98749. var oldLimitImpulse = this.limitImpulse;
  98750. this.limitImpulse += newLimitImpulse;
  98751. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  98752. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  98753. } else newLimitImpulse = 0;
  98754. var totalImpulse = newLimitImpulse + newMotorImpulse;
  98755. this.l1.x += totalImpulse * this.l1x;
  98756. this.l1.y += totalImpulse * this.l1y;
  98757. this.l1.z += totalImpulse * this.l1z;
  98758. this.a1.x += totalImpulse * this.a1x;
  98759. this.a1.y += totalImpulse * this.a1y;
  98760. this.a1.z += totalImpulse * this.a1z;
  98761. this.l2.x -= totalImpulse * this.l2x;
  98762. this.l2.y -= totalImpulse * this.l2y;
  98763. this.l2.z -= totalImpulse * this.l2z;
  98764. this.a2.x -= totalImpulse * this.a2x;
  98765. this.a2.y -= totalImpulse * this.a2y;
  98766. this.a2.z -= totalImpulse * this.a2z;
  98767. }
  98768. }
  98769. /**
  98770. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  98771. * @author saharan
  98772. */
  98773. OIMO.Contact = function () {
  98774. // The first shape.
  98775. this.shape1 = null;
  98776. // The second shape.
  98777. this.shape2 = null;
  98778. // The first rigid body.
  98779. this.body1 = null;
  98780. // The second rigid body.
  98781. this.body2 = null;
  98782. // The previous contact in the world.
  98783. this.prev = null;
  98784. // The next contact in the world.
  98785. this.next = null;
  98786. // Internal
  98787. this.persisting = false;
  98788. // Whether both the rigid bodies are sleeping or not.
  98789. this.sleeping = false;
  98790. // The collision detector between two shapes.
  98791. this.detector = null;
  98792. // The contact constraint of the contact.
  98793. this.constraint = null;
  98794. // Whether the shapes are touching or not.
  98795. this.touching = false;
  98796. this.b1Link = new OIMO.ContactLink(this);
  98797. this.b2Link = new OIMO.ContactLink(this);
  98798. this.s1Link = new OIMO.ContactLink(this);
  98799. this.s2Link = new OIMO.ContactLink(this);
  98800. // The contact manifold of the contact.
  98801. this.manifold = new OIMO.ContactManifold();
  98802. this.buffer = [];// vector 4
  98803. this.buffer.length = 4;
  98804. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  98805. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  98806. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  98807. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  98808. this.points = this.manifold.points;
  98809. this.constraint = new OIMO.ContactConstraint(this.manifold);
  98810. }
  98811. OIMO.Contact.prototype = {
  98812. constructor: OIMO.Contact,
  98813. mixRestitution: function (restitution1, restitution2) {
  98814. return OIMO.sqrt(restitution1 * restitution2);
  98815. },
  98816. mixFriction: function (friction1, friction2) {
  98817. return OIMO.sqrt(friction1 * friction2);
  98818. },
  98819. /**
  98820. * Update the contact manifold.
  98821. */
  98822. updateManifold: function () {
  98823. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  98824. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  98825. var numBuffers = this.manifold.numPoints;
  98826. var i = numBuffers;
  98827. while (i--) {
  98828. //for(var i=0;i<numBuffers;i++){
  98829. var b = this.buffer[i];
  98830. var p = this.points[i];
  98831. b.lp1X = p.localPoint1.x;
  98832. b.lp1Y = p.localPoint1.y;
  98833. b.lp1Z = p.localPoint1.z;
  98834. b.lp2X = p.localPoint2.x;
  98835. b.lp2Y = p.localPoint2.y;
  98836. b.lp2Z = p.localPoint2.z;
  98837. b.impulse = p.normalImpulse;
  98838. }
  98839. this.manifold.numPoints = 0;
  98840. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  98841. var num = this.manifold.numPoints;
  98842. if (num == 0) {
  98843. this.touching = false;
  98844. return;
  98845. }
  98846. this.touching = true;
  98847. i = num;
  98848. while (i--) {
  98849. //for(i=0; i<num; i++){
  98850. p = this.points[i];
  98851. var lp1x = p.localPoint1.x;
  98852. var lp1y = p.localPoint1.y;
  98853. var lp1z = p.localPoint1.z;
  98854. var lp2x = p.localPoint2.x;
  98855. var lp2y = p.localPoint2.y;
  98856. var lp2z = p.localPoint2.z;
  98857. var index = -1;
  98858. var minDistance = 0.0004;
  98859. var j = numBuffers;
  98860. while (j--) {
  98861. //for(var j=0;j<numBuffers;j++){
  98862. b = this.buffer[j];
  98863. var dx = b.lp1X - lp1x;
  98864. var dy = b.lp1Y - lp1y;
  98865. var dz = b.lp1Z - lp1z;
  98866. var distance1 = dx * dx + dy * dy + dz * dz;
  98867. dx = b.lp2X - lp2x;
  98868. dy = b.lp2Y - lp2y;
  98869. dz = b.lp2Z - lp2z;
  98870. var distance2 = dx * dx + dy * dy + dz * dz;
  98871. if (distance1 < distance2) {
  98872. if (distance1 < minDistance) {
  98873. minDistance = distance1;
  98874. index = j;
  98875. }
  98876. } else {
  98877. if (distance2 < minDistance) {
  98878. minDistance = distance2;
  98879. index = j;
  98880. }
  98881. }
  98882. }
  98883. if (index != -1) {
  98884. var tmp = this.buffer[index];
  98885. this.buffer[index] = this.buffer[--numBuffers];
  98886. this.buffer[numBuffers] = tmp;
  98887. p.normalImpulse = tmp.impulse;
  98888. p.warmStarted = true;
  98889. } else {
  98890. p.normalImpulse = 0;
  98891. p.warmStarted = false;
  98892. }
  98893. }
  98894. },
  98895. /**
  98896. * Attach the contact to the shapes.
  98897. * @param shape1
  98898. * @param shape2
  98899. */
  98900. attach: function (shape1, shape2) {
  98901. this.shape1 = shape1;
  98902. this.shape2 = shape2;
  98903. this.body1 = shape1.parent;
  98904. this.body2 = shape2.parent;
  98905. this.manifold.body1 = this.body1;
  98906. this.manifold.body2 = this.body2;
  98907. this.constraint.body1 = this.body1;
  98908. this.constraint.body2 = this.body2;
  98909. this.constraint.attach();
  98910. this.s1Link.shape = shape2;
  98911. this.s1Link.body = this.body2;
  98912. this.s2Link.shape = shape1;
  98913. this.s2Link.body = this.body1;
  98914. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  98915. else this.s1Link.next = null;
  98916. shape1.contactLink = this.s1Link;
  98917. shape1.numContacts++;
  98918. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  98919. else this.s2Link.next = null;
  98920. shape2.contactLink = this.s2Link;
  98921. shape2.numContacts++;
  98922. this.b1Link.shape = shape2;
  98923. this.b1Link.body = this.body2;
  98924. this.b2Link.shape = shape1;
  98925. this.b2Link.body = this.body1;
  98926. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  98927. else this.b1Link.next = null;
  98928. this.body1.contactLink = this.b1Link;
  98929. this.body1.numContacts++;
  98930. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  98931. else this.b2Link.next = null;
  98932. this.body2.contactLink = this.b2Link;
  98933. this.body2.numContacts++;
  98934. this.prev = null;
  98935. this.next = null;
  98936. this.persisting = true;
  98937. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  98938. this.manifold.numPoints = 0;
  98939. },
  98940. /**
  98941. * Detach the contact from the shapes.
  98942. */
  98943. detach: function () {
  98944. var prev = this.s1Link.prev;
  98945. var next = this.s1Link.next;
  98946. if (prev !== null) prev.next = next;
  98947. if (next !== null) next.prev = prev;
  98948. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  98949. this.s1Link.prev = null;
  98950. this.s1Link.next = null;
  98951. this.s1Link.shape = null;
  98952. this.s1Link.body = null;
  98953. this.shape1.numContacts--;
  98954. prev = this.s2Link.prev;
  98955. next = this.s2Link.next;
  98956. if (prev !== null) prev.next = next;
  98957. if (next !== null) next.prev = prev;
  98958. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  98959. this.s2Link.prev = null;
  98960. this.s2Link.next = null;
  98961. this.s2Link.shape = null;
  98962. this.s2Link.body = null;
  98963. this.shape2.numContacts--;
  98964. prev = this.b1Link.prev;
  98965. next = this.b1Link.next;
  98966. if (prev !== null) prev.next = next;
  98967. if (next !== null) next.prev = prev;
  98968. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  98969. this.b1Link.prev = null;
  98970. this.b1Link.next = null;
  98971. this.b1Link.shape = null;
  98972. this.b1Link.body = null;
  98973. this.body1.numContacts--;
  98974. prev = this.b2Link.prev;
  98975. next = this.b2Link.next;
  98976. if (prev !== null) prev.next = next;
  98977. if (next !== null) next.prev = prev;
  98978. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  98979. this.b2Link.prev = null;
  98980. this.b2Link.next = null;
  98981. this.b2Link.shape = null;
  98982. this.b2Link.body = null;
  98983. this.body2.numContacts--;
  98984. this.manifold.body1 = null;
  98985. this.manifold.body2 = null;
  98986. this.constraint.body1 = null;
  98987. this.constraint.body2 = null;
  98988. this.constraint.detach();
  98989. this.shape1 = null;
  98990. this.shape2 = null;
  98991. this.body1 = null;
  98992. this.body2 = null;
  98993. }
  98994. }
  98995. /**
  98996. * ...
  98997. * @author saharan
  98998. */
  98999. OIMO.ContactConstraint = function (manifold) {
  99000. OIMO.Constraint.call(this);
  99001. // The contact manifold of the constraint.
  99002. this.manifold = manifold;
  99003. // The coefficient of restitution of the constraint.
  99004. this.restitution = NaN;
  99005. // The coefficient of friction of the constraint.
  99006. this.friction = NaN;
  99007. this.p1 = null;
  99008. this.p2 = null;
  99009. this.lv1 = null;
  99010. this.lv2 = null;
  99011. this.av1 = null;
  99012. this.av2 = null;
  99013. this.i1 = null;
  99014. this.i2 = null;
  99015. this.ii1 = null;
  99016. this.ii2 = null;
  99017. this.m1 = NaN;
  99018. this.m2 = NaN;
  99019. this.num = 0;
  99020. this.ps = manifold.points;
  99021. this.cs = new OIMO.ContactPointDataBuffer();
  99022. this.cs.next = new OIMO.ContactPointDataBuffer();
  99023. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  99024. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  99025. }
  99026. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  99027. /**
  99028. * Attach the constraint to the bodies.
  99029. */
  99030. OIMO.ContactConstraint.prototype.attach = function () {
  99031. this.p1 = this.body1.position;
  99032. this.p2 = this.body2.position;
  99033. this.lv1 = this.body1.linearVelocity;
  99034. this.av1 = this.body1.angularVelocity;
  99035. this.lv2 = this.body2.linearVelocity;
  99036. this.av2 = this.body2.angularVelocity;
  99037. this.i1 = this.body1.inverseInertia;
  99038. this.i2 = this.body2.inverseInertia;
  99039. }
  99040. /**
  99041. * Detach the constraint from the bodies.
  99042. */
  99043. OIMO.ContactConstraint.prototype.detach = function () {
  99044. this.p1 = null;
  99045. this.p2 = null;
  99046. this.lv1 = null;
  99047. this.lv2 = null;
  99048. this.av1 = null;
  99049. this.av2 = null;
  99050. this.i1 = null;
  99051. this.i2 = null;
  99052. }
  99053. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  99054. this.m1 = this.body1.inverseMass;
  99055. this.m2 = this.body2.inverseMass;
  99056. this.ii1 = this.i1.clone();
  99057. this.ii2 = this.i2.clone();
  99058. var ii1 = this.ii1.elements;
  99059. var ii2 = this.ii2.elements;
  99060. var p1x = this.p1.x;
  99061. var p1y = this.p1.y;
  99062. var p1z = this.p1.z;
  99063. var p2x = this.p2.x;
  99064. var p2y = this.p2.y;
  99065. var p2z = this.p2.z;
  99066. var m1m2 = this.m1 + this.m2;
  99067. this.num = this.manifold.numPoints;
  99068. var c = this.cs;
  99069. for (var i = 0; i < this.num; i++) {
  99070. var p = this.ps[i];
  99071. var tmp1X;
  99072. var tmp1Y;
  99073. var tmp1Z;
  99074. var tmp2X;
  99075. var tmp2Y;
  99076. var tmp2Z;
  99077. tmp1X = p.position.x;
  99078. tmp1Y = p.position.y;
  99079. tmp1Z = p.position.z;
  99080. var rp1X = tmp1X - p1x;
  99081. var rp1Y = tmp1Y - p1y;
  99082. var rp1Z = tmp1Z - p1z;
  99083. var rp2X = tmp1X - p2x;
  99084. var rp2Y = tmp1Y - p2y;
  99085. var rp2Z = tmp1Z - p2z;
  99086. c.rp1X = rp1X;
  99087. c.rp1Y = rp1Y;
  99088. c.rp1Z = rp1Z;
  99089. c.rp2X = rp2X;
  99090. c.rp2Y = rp2Y;
  99091. c.rp2Z = rp2Z;
  99092. c.norImp = p.normalImpulse;
  99093. c.tanImp = p.tangentImpulse;
  99094. c.binImp = p.binormalImpulse;
  99095. var norX = p.normal.x;
  99096. var norY = p.normal.y;
  99097. var norZ = p.normal.z;
  99098. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  99099. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  99100. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  99101. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  99102. var tanX = rvX - rvn * norX;
  99103. var tanY = rvY - rvn * norY;
  99104. var tanZ = rvZ - rvn * norZ;
  99105. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  99106. if (len > 0.04) {
  99107. len = 1 / OIMO.sqrt(len);
  99108. } else {
  99109. tanX = norY * norX - norZ * norZ;
  99110. tanY = -norZ * norY - norX * norX;
  99111. tanZ = norX * norZ + norY * norY;
  99112. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  99113. }
  99114. tanX *= len;
  99115. tanY *= len;
  99116. tanZ *= len;
  99117. var binX = norY * tanZ - norZ * tanY;
  99118. var binY = norZ * tanX - norX * tanZ;
  99119. var binZ = norX * tanY - norY * tanX;
  99120. c.norX = norX;
  99121. c.norY = norY;
  99122. c.norZ = norZ;
  99123. c.tanX = tanX;
  99124. c.tanY = tanY;
  99125. c.tanZ = tanZ;
  99126. c.binX = binX;
  99127. c.binY = binY;
  99128. c.binZ = binZ;
  99129. c.norU1X = norX * this.m1;
  99130. c.norU1Y = norY * this.m1;
  99131. c.norU1Z = norZ * this.m1;
  99132. c.norU2X = norX * this.m2;
  99133. c.norU2Y = norY * this.m2;
  99134. c.norU2Z = norZ * this.m2;
  99135. c.tanU1X = tanX * this.m1;
  99136. c.tanU1Y = tanY * this.m1;
  99137. c.tanU1Z = tanZ * this.m1;
  99138. c.tanU2X = tanX * this.m2;
  99139. c.tanU2Y = tanY * this.m2;
  99140. c.tanU2Z = tanZ * this.m2;
  99141. c.binU1X = binX * this.m1;
  99142. c.binU1Y = binY * this.m1;
  99143. c.binU1Z = binZ * this.m1;
  99144. c.binU2X = binX * this.m2;
  99145. c.binU2Y = binY * this.m2;
  99146. c.binU2Z = binZ * this.m2;
  99147. var norT1X = rp1Y * norZ - rp1Z * norY;
  99148. var norT1Y = rp1Z * norX - rp1X * norZ;
  99149. var norT1Z = rp1X * norY - rp1Y * norX;
  99150. var norT2X = rp2Y * norZ - rp2Z * norY;
  99151. var norT2Y = rp2Z * norX - rp2X * norZ;
  99152. var norT2Z = rp2X * norY - rp2Y * norX;
  99153. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  99154. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  99155. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  99156. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  99157. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  99158. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  99159. var binT1X = rp1Y * binZ - rp1Z * binY;
  99160. var binT1Y = rp1Z * binX - rp1X * binZ;
  99161. var binT1Z = rp1X * binY - rp1Y * binX;
  99162. var binT2X = rp2Y * binZ - rp2Z * binY;
  99163. var binT2Y = rp2Z * binX - rp2X * binZ;
  99164. var binT2Z = rp2X * binY - rp2Y * binX;
  99165. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  99166. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  99167. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  99168. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  99169. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  99170. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  99171. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  99172. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  99173. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  99174. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  99175. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  99176. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  99177. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  99178. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  99179. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  99180. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  99181. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  99182. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  99183. c.norT1X = norT1X;
  99184. c.norT1Y = norT1Y;
  99185. c.norT1Z = norT1Z;
  99186. c.tanT1X = tanT1X;
  99187. c.tanT1Y = tanT1Y;
  99188. c.tanT1Z = tanT1Z;
  99189. c.binT1X = binT1X;
  99190. c.binT1Y = binT1Y;
  99191. c.binT1Z = binT1Z;
  99192. c.norT2X = norT2X;
  99193. c.norT2Y = norT2Y;
  99194. c.norT2Z = norT2Z;
  99195. c.tanT2X = tanT2X;
  99196. c.tanT2Y = tanT2Y;
  99197. c.tanT2Z = tanT2Z;
  99198. c.binT2X = binT2X;
  99199. c.binT2Y = binT2Y;
  99200. c.binT2Z = binT2Z;
  99201. c.norTU1X = norTU1X;
  99202. c.norTU1Y = norTU1Y;
  99203. c.norTU1Z = norTU1Z;
  99204. c.tanTU1X = tanTU1X;
  99205. c.tanTU1Y = tanTU1Y;
  99206. c.tanTU1Z = tanTU1Z;
  99207. c.binTU1X = binTU1X;
  99208. c.binTU1Y = binTU1Y;
  99209. c.binTU1Z = binTU1Z;
  99210. c.norTU2X = norTU2X;
  99211. c.norTU2Y = norTU2Y;
  99212. c.norTU2Z = norTU2Z;
  99213. c.tanTU2X = tanTU2X;
  99214. c.tanTU2Y = tanTU2Y;
  99215. c.tanTU2Z = tanTU2Z;
  99216. c.binTU2X = binTU2X;
  99217. c.binTU2Y = binTU2Y;
  99218. c.binTU2Z = binTU2Z;
  99219. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  99220. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  99221. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  99222. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  99223. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  99224. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  99225. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  99226. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  99227. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  99228. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  99229. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  99230. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  99231. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  99232. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  99233. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  99234. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  99235. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  99236. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  99237. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  99238. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  99239. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  99240. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  99241. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  99242. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  99243. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  99244. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  99245. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  99246. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  99247. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  99248. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  99249. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  99250. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  99251. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  99252. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  99253. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  99254. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  99255. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  99256. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  99257. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  99258. c.norDen = norDen;
  99259. c.tanDen = tanDen;
  99260. c.binDen = binDen;
  99261. if (p.warmStarted) {
  99262. var norImp = p.normalImpulse;
  99263. this.lv1.x += c.norU1X * norImp;
  99264. this.lv1.y += c.norU1Y * norImp;
  99265. this.lv1.z += c.norU1Z * norImp;
  99266. this.av1.x += norTU1X * norImp;
  99267. this.av1.y += norTU1Y * norImp;
  99268. this.av1.z += norTU1Z * norImp;
  99269. this.lv2.x -= c.norU2X * norImp;
  99270. this.lv2.y -= c.norU2Y * norImp;
  99271. this.lv2.z -= c.norU2Z * norImp;
  99272. this.av2.x -= norTU2X * norImp;
  99273. this.av2.y -= norTU2Y * norImp;
  99274. this.av2.z -= norTU2Z * norImp;
  99275. c.norImp = norImp;
  99276. c.tanImp = 0;
  99277. c.binImp = 0;
  99278. rvn = 0; // disable bouncing
  99279. } else {
  99280. c.norImp = 0;
  99281. c.tanImp = 0;
  99282. c.binImp = 0;
  99283. }
  99284. if (rvn > -1) {
  99285. rvn = 0; // disable bouncing
  99286. }
  99287. var norTar = this.restitution * -rvn;
  99288. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  99289. if (norTar < sepV) norTar = sepV;
  99290. c.norTar = norTar;
  99291. c.last = i == this.num - 1;
  99292. c = c.next;
  99293. }
  99294. }
  99295. OIMO.ContactConstraint.prototype.solve = function () {
  99296. var lv1x = this.lv1.x;
  99297. var lv1y = this.lv1.y;
  99298. var lv1z = this.lv1.z;
  99299. var lv2x = this.lv2.x;
  99300. var lv2y = this.lv2.y;
  99301. var lv2z = this.lv2.z;
  99302. var av1x = this.av1.x;
  99303. var av1y = this.av1.y;
  99304. var av1z = this.av1.z;
  99305. var av2x = this.av2.x;
  99306. var av2y = this.av2.y;
  99307. var av2z = this.av2.z;
  99308. var c = this.cs;
  99309. while (true) {
  99310. var oldImp1;
  99311. var newImp1;
  99312. var oldImp2;
  99313. var newImp2;
  99314. var rvn;
  99315. var norImp = c.norImp;
  99316. var tanImp = c.tanImp;
  99317. var binImp = c.binImp;
  99318. var max = -norImp * this.friction;
  99319. var rvX = lv2x - lv1x;
  99320. var rvY = lv2y - lv1y;
  99321. var rvZ = lv2z - lv1z;
  99322. rvn =
  99323. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  99324. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  99325. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  99326. ;
  99327. oldImp1 = tanImp;
  99328. newImp1 = rvn * c.tanDen;
  99329. tanImp += newImp1;
  99330. rvn =
  99331. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  99332. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  99333. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  99334. ;
  99335. oldImp2 = binImp;
  99336. newImp2 = rvn * c.binDen;
  99337. binImp += newImp2;
  99338. // cone friction clamp
  99339. var len = tanImp * tanImp + binImp * binImp;
  99340. if (len > max * max) {
  99341. len = max / OIMO.sqrt(len);
  99342. tanImp *= len;
  99343. binImp *= len;
  99344. }
  99345. newImp1 = tanImp - oldImp1;
  99346. newImp2 = binImp - oldImp2;
  99347. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  99348. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  99349. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  99350. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  99351. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  99352. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  99353. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  99354. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  99355. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  99356. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  99357. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  99358. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  99359. // restitution part
  99360. rvn =
  99361. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  99362. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  99363. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  99364. oldImp1 = norImp;
  99365. newImp1 = (rvn - c.norTar) * c.norDen;
  99366. norImp += newImp1;
  99367. if (norImp > 0) norImp = 0;
  99368. newImp1 = norImp - oldImp1;
  99369. lv1x += c.norU1X * newImp1;
  99370. lv1y += c.norU1Y * newImp1;
  99371. lv1z += c.norU1Z * newImp1;
  99372. av1x += c.norTU1X * newImp1;
  99373. av1y += c.norTU1Y * newImp1;
  99374. av1z += c.norTU1Z * newImp1;
  99375. lv2x -= c.norU2X * newImp1;
  99376. lv2y -= c.norU2Y * newImp1;
  99377. lv2z -= c.norU2Z * newImp1;
  99378. av2x -= c.norTU2X * newImp1;
  99379. av2y -= c.norTU2Y * newImp1;
  99380. av2z -= c.norTU2Z * newImp1;
  99381. c.norImp = norImp;
  99382. c.tanImp = tanImp;
  99383. c.binImp = binImp;
  99384. if (c.last) break;
  99385. c = c.next;
  99386. }
  99387. this.lv1.x = lv1x;
  99388. this.lv1.y = lv1y;
  99389. this.lv1.z = lv1z;
  99390. this.lv2.x = lv2x;
  99391. this.lv2.y = lv2y;
  99392. this.lv2.z = lv2z;
  99393. this.av1.x = av1x;
  99394. this.av1.y = av1y;
  99395. this.av1.z = av1z;
  99396. this.av2.x = av2x;
  99397. this.av2.y = av2y;
  99398. this.av2.z = av2z;
  99399. }
  99400. OIMO.ContactConstraint.prototype.postSolve = function () {
  99401. var c = this.cs;
  99402. var i = this.num;
  99403. while (i--) {
  99404. //for(var i=0;i<this.num;i++){
  99405. var p = this.ps[i];
  99406. p.normal.x = c.norX;
  99407. p.normal.y = c.norY;
  99408. p.normal.z = c.norZ;
  99409. p.tangent.x = c.tanX;
  99410. p.tangent.y = c.tanY;
  99411. p.tangent.z = c.tanZ;
  99412. p.binormal.x = c.binX;
  99413. p.binormal.y = c.binY;
  99414. p.binormal.z = c.binZ;
  99415. p.normalImpulse = c.norImp;
  99416. p.tangentImpulse = c.tanImp;
  99417. p.binormalImpulse = c.binImp;
  99418. p.normalDenominator = c.norDen;
  99419. p.tangentDenominator = c.tanDen;
  99420. p.binormalDenominator = c.binDen;
  99421. c = c.next;
  99422. }
  99423. }
  99424. /**
  99425. * A link list of contacts.
  99426. * @author saharan
  99427. */
  99428. OIMO.ContactLink = function (contact) {
  99429. // The previous contact link.
  99430. this.prev = null;
  99431. // The next contact link.
  99432. this.next = null;
  99433. // The shape of the contact.
  99434. this.shape = null;
  99435. // The other rigid body.
  99436. this.body = null;
  99437. // The contact of the link.
  99438. this.contact = contact;
  99439. }
  99440. /**
  99441. * A contact manifold between two shapes.
  99442. * @author saharan
  99443. */
  99444. OIMO.ContactManifold = function () {
  99445. // The first rigid body.
  99446. this.body1 = null;
  99447. // The second rigid body.
  99448. this.body2 = null;
  99449. // The number of manifold points.
  99450. this.numPoints = 0;
  99451. // The manifold points.
  99452. this.points = [];
  99453. this.points.length = 4;
  99454. this.points[0] = new OIMO.ManifoldPoint();
  99455. this.points[1] = new OIMO.ManifoldPoint();
  99456. this.points[2] = new OIMO.ManifoldPoint();
  99457. this.points[3] = new OIMO.ManifoldPoint();
  99458. }
  99459. OIMO.ContactManifold.prototype = {
  99460. constructor: OIMO.ContactManifold,
  99461. /**
  99462. * Reset the manifold.
  99463. * @param shape1
  99464. * @param shape2
  99465. */
  99466. reset: function (shape1, shape2) {
  99467. this.body1 = shape1.parent;
  99468. this.body2 = shape2.parent;
  99469. this.numPoints = 0;
  99470. },
  99471. /**
  99472. * Add a point into this manifold.
  99473. * @param x
  99474. * @param y
  99475. * @param z
  99476. * @param normalX
  99477. * @param normalY
  99478. * @param normalZ
  99479. * @param penetration
  99480. * @param flip
  99481. */
  99482. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  99483. var p = this.points[this.numPoints++];
  99484. p.position.x = x;
  99485. p.position.y = y;
  99486. p.position.z = z;
  99487. var r = this.body1.rotation;
  99488. var rx = x - this.body1.position.x;
  99489. var ry = y - this.body1.position.y;
  99490. var rz = z - this.body1.position.z;
  99491. var tr = r.elements;
  99492. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  99493. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  99494. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  99495. r = this.body2.rotation;
  99496. rx = x - this.body2.position.x;
  99497. ry = y - this.body2.position.y;
  99498. rz = z - this.body2.position.z;
  99499. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  99500. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  99501. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  99502. p.normalImpulse = 0;
  99503. if (flip) {
  99504. p.normal.x = -normalX;
  99505. p.normal.y = -normalY;
  99506. p.normal.z = -normalZ;
  99507. } else {
  99508. p.normal.x = normalX;
  99509. p.normal.y = normalY;
  99510. p.normal.z = normalZ;
  99511. }
  99512. p.penetration = penetration;
  99513. p.warmStarted = false;
  99514. }
  99515. }
  99516. OIMO.ContactPointDataBuffer = function () {
  99517. this.norX = NaN;
  99518. this.norY = NaN;
  99519. this.norZ = NaN;
  99520. this.tanX = NaN;
  99521. this.tanY = NaN;
  99522. this.tanZ = NaN;
  99523. this.binX = NaN;
  99524. this.binY = NaN;
  99525. this.binZ = NaN;
  99526. this.rp1X = NaN;
  99527. this.rp1Y = NaN;
  99528. this.rp1Z = NaN;
  99529. this.rp2X = NaN;
  99530. this.rp2Y = NaN;
  99531. this.rp2Z = NaN;
  99532. this.norU1X = NaN;
  99533. this.norU1Y = NaN;
  99534. this.norU1Z = NaN;
  99535. this.norU2X = NaN;
  99536. this.norU2Y = NaN;
  99537. this.norU2Z = NaN;
  99538. this.tanU1X = NaN;
  99539. this.tanU1Y = NaN;
  99540. this.tanU1Z = NaN;
  99541. this.tanU2X = NaN;
  99542. this.tanU2Y = NaN;
  99543. this.tanU2Z = NaN;
  99544. this.binU1X = NaN;
  99545. this.binU1Y = NaN;
  99546. this.binU1Z = NaN;
  99547. this.binU2X = NaN;
  99548. this.binU2Y = NaN;
  99549. this.binU2Z = NaN;
  99550. this.norT1X = NaN;
  99551. this.norT1Y = NaN;
  99552. this.norT1Z = NaN;
  99553. this.norT2X = NaN;
  99554. this.norT2Y = NaN;
  99555. this.norT2Z = NaN;
  99556. this.tanT1X = NaN;
  99557. this.tanT1Y = NaN;
  99558. this.tanT1Z = NaN;
  99559. this.tanT2X = NaN;
  99560. this.tanT2Y = NaN;
  99561. this.tanT2Z = NaN;
  99562. this.binT1X = NaN;
  99563. this.binT1Y = NaN;
  99564. this.binT1Z = NaN;
  99565. this.binT2X = NaN;
  99566. this.binT2Y = NaN;
  99567. this.binT2Z = NaN;
  99568. this.norTU1X = NaN;
  99569. this.norTU1Y = NaN;
  99570. this.norTU1Z = NaN;
  99571. this.norTU2X = NaN;
  99572. this.norTU2Y = NaN;
  99573. this.norTU2Z = NaN;
  99574. this.tanTU1X = NaN;
  99575. this.tanTU1Y = NaN;
  99576. this.tanTU1Z = NaN;
  99577. this.tanTU2X = NaN;
  99578. this.tanTU2Y = NaN;
  99579. this.tanTU2Z = NaN;
  99580. this.binTU1X = NaN;
  99581. this.binTU1Y = NaN;
  99582. this.binTU1Z = NaN;
  99583. this.binTU2X = NaN;
  99584. this.binTU2Y = NaN;
  99585. this.binTU2Z = NaN;
  99586. this.norImp = NaN;
  99587. this.tanImp = NaN;
  99588. this.binImp = NaN;
  99589. this.norDen = NaN;
  99590. this.tanDen = NaN;
  99591. this.binDen = NaN;
  99592. this.norTar = NaN;
  99593. this.next = null;
  99594. this.last = false;
  99595. }
  99596. OIMO.ImpulseDataBuffer = function () {
  99597. this.lp1X = NaN;
  99598. this.lp1Y = NaN;
  99599. this.lp1Z = NaN;
  99600. this.lp2X = NaN;
  99601. this.lp2Y = NaN;
  99602. this.lp2Z = NaN;
  99603. this.impulse = NaN;
  99604. }
  99605. /**
  99606. * The class holds details of the contact point.
  99607. * @author saharan
  99608. */
  99609. OIMO.ManifoldPoint = function () {
  99610. // Whether this manifold point is persisting or not.
  99611. this.warmStarted = false;
  99612. // The position of this manifold point.
  99613. this.position = new OIMO.Vec3();
  99614. // The position in the first shape's coordinate.
  99615. this.localPoint1 = new OIMO.Vec3();
  99616. // The position in the second shape's coordinate.
  99617. this.localPoint2 = new OIMO.Vec3();
  99618. // The normal vector of this manifold point.
  99619. this.normal = new OIMO.Vec3();
  99620. // The tangent vector of this manifold point.
  99621. this.tangent = new OIMO.Vec3();
  99622. // The binormal vector of this manifold point.
  99623. this.binormal = new OIMO.Vec3();
  99624. // The impulse in normal direction.
  99625. this.normalImpulse = 0;
  99626. // The impulse in tangent direction.
  99627. this.tangentImpulse = 0;
  99628. // The impulse in binormal direction.
  99629. this.binormalImpulse = 0;
  99630. // The denominator in normal direction.
  99631. this.normalDenominator = 0;
  99632. // The denominator in tangent direction.
  99633. this.tangentDenominator = 0;
  99634. // The denominator in binormal direction.
  99635. this.binormalDenominator = 0;
  99636. // The depth of penetration.
  99637. this.penetration = 0;
  99638. }
  99639. /**
  99640. * This class holds mass information of a shape.
  99641. * @author saharan
  99642. */
  99643. OIMO.MassInfo = function () {
  99644. // Mass of the shape.
  99645. this.mass = 0;
  99646. // The moment inertia of the shape.
  99647. this.inertia = new OIMO.Mat33();
  99648. };
  99649. /**
  99650. * A shape is used to detect collisions of rigid bodies.
  99651. * @author saharan
  99652. * @author lo-th
  99653. */
  99654. OIMO.Shape = function (config) {
  99655. this.type = OIMO.SHAPE_NULL;
  99656. // The global identification of the shape should be unique to the shape.
  99657. this.id = OIMO.nextID++;
  99658. // The previous shape in parent rigid body.
  99659. this.prev = null;
  99660. // The next shape in parent rigid body.
  99661. this.next = null;
  99662. // The proxy of the shape used for broad-phase collision detection.
  99663. this.proxy = null;
  99664. // The parent rigid body of the shape.
  99665. this.parent = null;
  99666. // The linked list of the contacts with the shape.
  99667. this.contactLink = null;
  99668. // The number of the contacts with the shape.
  99669. this.numContacts = 0;
  99670. // The center of gravity of the shape in world coordinate system.
  99671. this.position = new OIMO.Vec3();
  99672. // The rotation matrix of the shape in world coordinate system
  99673. this.rotation = new OIMO.Mat33();
  99674. // The position of the shape in parent's coordinate system.
  99675. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  99676. // The rotation matrix of the shape in parent's coordinate system.
  99677. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  99678. // The axis-aligned bounding box of the shape.
  99679. this.aabb = new OIMO.AABB();
  99680. // The density of the shape.
  99681. this.density = config.density;
  99682. // The coefficient of friction of the shape.
  99683. this.friction = config.friction;
  99684. // The coefficient of restitution of the shape.
  99685. this.restitution = config.restitution;
  99686. // The bits of the collision groups to which the shape belongs.
  99687. this.belongsTo = config.belongsTo;
  99688. // The bits of the collision groups with which the shape collides.
  99689. this.collidesWith = config.collidesWith;
  99690. };
  99691. OIMO.Shape.prototype = {
  99692. constructor: OIMO.Shape,
  99693. // Calculate the mass information of the shape.
  99694. calculateMassInfo: function (out) {
  99695. OIMO.Error("Shape", "Inheritance error.");
  99696. },
  99697. // Update the proxy of the shape.
  99698. updateProxy: function () {
  99699. OIMO.Error("Shape", "Inheritance error.");
  99700. }
  99701. };
  99702. /**
  99703. * A shape configuration holds common configuration data for constructing a shape.
  99704. * Shape configurations can be reused safely.
  99705. * @author saharan
  99706. */
  99707. OIMO.ShapeConfig = function () {
  99708. // The position of the shape in parent's coordinate system.
  99709. this.relativePosition = new OIMO.Vec3();
  99710. // The rotation matrix of the shape in parent's coordinate system.
  99711. this.relativeRotation = new OIMO.Mat33();
  99712. // The coefficient of friction of the shape.
  99713. this.friction = 0.4;
  99714. // The coefficient of restitution of the shape.
  99715. this.restitution = 0.2;
  99716. // The density of the shape.
  99717. this.density = 1;
  99718. // The bits of the collision groups to which the shape belongs.
  99719. this.belongsTo = 1;
  99720. // The bits of the collision groups with which the shape collides.
  99721. this.collidesWith = 0xffffffff;
  99722. };
  99723. /**
  99724. * A box shape.
  99725. * @author saharan
  99726. * @author lo-th
  99727. */
  99728. OIMO.BoxShape = function (config, Width, Height, Depth) {
  99729. OIMO.Shape.call(this, config);
  99730. this.type = OIMO.SHAPE_BOX;
  99731. // The width of the box.
  99732. this.width = Width;
  99733. // The height of the box.
  99734. this.height = Height;
  99735. // The depth of the box.
  99736. this.depth = Depth;
  99737. // The half-width of the box.
  99738. this.halfWidth = Width * 0.5;
  99739. // The half-height of the box.
  99740. this.halfHeight = Height * 0.5;
  99741. // The half-depth of the box.
  99742. this.halfDepth = Depth * 0.5;
  99743. this.dimentions = new OIMO_ARRAY_TYPE(18);
  99744. this.elements = new OIMO_ARRAY_TYPE(24);
  99745. };
  99746. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  99747. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  99748. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  99749. var mass = this.width * this.height * this.depth * this.density;
  99750. var divid = 1 / 12;
  99751. out.mass = mass;
  99752. out.inertia.set(
  99753. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  99754. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  99755. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  99756. );
  99757. };
  99758. OIMO.BoxShape.prototype.updateProxy = function () {
  99759. var te = this.rotation.elements;
  99760. var di = this.dimentions;
  99761. // Width
  99762. di[0] = te[0];
  99763. di[1] = te[3];
  99764. di[2] = te[6];
  99765. // Height
  99766. di[3] = te[1];
  99767. di[4] = te[4];
  99768. di[5] = te[7];
  99769. // Depth
  99770. di[6] = te[2];
  99771. di[7] = te[5];
  99772. di[8] = te[8];
  99773. // halp Width
  99774. di[9] = te[0] * this.halfWidth;
  99775. di[10] = te[3] * this.halfWidth;
  99776. di[11] = te[6] * this.halfWidth;
  99777. // halp Height
  99778. di[12] = te[1] * this.halfHeight;
  99779. di[13] = te[4] * this.halfHeight;
  99780. di[14] = te[7] * this.halfHeight;
  99781. // halp Depth
  99782. di[15] = te[2] * this.halfDepth;
  99783. di[16] = te[5] * this.halfDepth;
  99784. di[17] = te[8] * this.halfDepth;
  99785. var wx = di[9];
  99786. var wy = di[10];
  99787. var wz = di[11];
  99788. var hx = di[12];
  99789. var hy = di[13];
  99790. var hz = di[14];
  99791. var dx = di[15];
  99792. var dy = di[16];
  99793. var dz = di[17];
  99794. var x = this.position.x;
  99795. var y = this.position.y;
  99796. var z = this.position.z;
  99797. var v = this.elements;
  99798. //v1
  99799. v[0] = x + wx + hx + dx;
  99800. v[1] = y + wy + hy + dy;
  99801. v[2] = z + wz + hz + dz;
  99802. //v2
  99803. v[3] = x + wx + hx - dx;
  99804. v[4] = y + wy + hy - dy;
  99805. v[5] = z + wz + hz - dz;
  99806. //v3
  99807. v[6] = x + wx - hx + dx;
  99808. v[7] = y + wy - hy + dy;
  99809. v[8] = z + wz - hz + dz;
  99810. //v4
  99811. v[9] = x + wx - hx - dx;
  99812. v[10] = y + wy - hy - dy;
  99813. v[11] = z + wz - hz - dz;
  99814. //v5
  99815. v[12] = x - wx + hx + dx;
  99816. v[13] = y - wy + hy + dy;
  99817. v[14] = z - wz + hz + dz;
  99818. //v6
  99819. v[15] = x - wx + hx - dx;
  99820. v[16] = y - wy + hy - dy;
  99821. v[17] = z - wz + hz - dz;
  99822. //v7
  99823. v[18] = x - wx - hx + dx;
  99824. v[19] = y - wy - hy + dy;
  99825. v[20] = z - wz - hz + dz;
  99826. //v8
  99827. v[21] = x - wx - hx - dx;
  99828. v[22] = y - wy - hy - dy;
  99829. v[23] = z - wz - hz - dz;
  99830. var w = di[9] < 0 ? -di[9] : di[9];
  99831. var h = di[10] < 0 ? -di[10] : di[10];
  99832. var d = di[11] < 0 ? -di[11] : di[11];
  99833. w = di[12] < 0 ? w - di[12] : w + di[12];
  99834. h = di[13] < 0 ? h - di[13] : h + di[13];
  99835. d = di[14] < 0 ? d - di[14] : d + di[14];
  99836. w = di[15] < 0 ? w - di[15] : w + di[15];
  99837. h = di[16] < 0 ? h - di[16] : h + di[16];
  99838. d = di[17] < 0 ? d - di[17] : d + di[17];
  99839. var p = OIMO.AABB_PROX;
  99840. this.aabb.set(
  99841. this.position.x - w - p, this.position.x + w + p,
  99842. this.position.y - h - p, this.position.y + h + p,
  99843. this.position.z - d - p, this.position.z + d + p
  99844. );
  99845. if (this.proxy != null) this.proxy.update();
  99846. };
  99847. /**
  99848. * A sphere shape.
  99849. * @author saharan
  99850. * @author lo-th
  99851. */
  99852. OIMO.SphereShape = function (config, radius) {
  99853. OIMO.Shape.call(this, config);
  99854. this.type = OIMO.SHAPE_SPHERE;
  99855. // The radius of the shape.
  99856. this.radius = radius;
  99857. };
  99858. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  99859. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  99860. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  99861. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  99862. out.mass = mass;
  99863. var inertia = mass * this.radius * this.radius * 0.4;
  99864. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  99865. };
  99866. OIMO.SphereShape.prototype.updateProxy = function () {
  99867. var p = OIMO.AABB_PROX;
  99868. this.aabb.set(
  99869. this.position.x - this.radius - p, this.position.x + this.radius + p,
  99870. this.position.y - this.radius - p, this.position.y + this.radius + p,
  99871. this.position.z - this.radius - p, this.position.z + this.radius + p
  99872. );
  99873. if (this.proxy != null) this.proxy.update();
  99874. };
  99875. /**
  99876. * A cylinder shap.
  99877. * @author saharan
  99878. * @author lo-th
  99879. */
  99880. OIMO.CylinderShape = function (config, radius, height) {
  99881. OIMO.Shape.call(this, config);
  99882. this.type = OIMO.SHAPE_CYLINDER;
  99883. this.radius = radius;
  99884. this.height = height;
  99885. this.halfHeight = height * 0.5;
  99886. this.normalDirection = new OIMO.Vec3();
  99887. this.halfDirection = new OIMO.Vec3();
  99888. };
  99889. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  99890. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  99891. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  99892. var rsq = this.radius * this.radius;
  99893. var mass = OIMO.PI * rsq * this.height * this.density;
  99894. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  99895. var inertiaY = 0.5 * rsq;
  99896. out.mass = mass;
  99897. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  99898. };
  99899. OIMO.CylinderShape.prototype.updateProxy = function () {
  99900. var te = this.rotation.elements;
  99901. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  99902. xx = te[1] * te[1];
  99903. yy = te[4] * te[4];
  99904. zz = te[7] * te[7];
  99905. this.normalDirection.set(te[1], te[4], te[7]);
  99906. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  99907. wx = 1 - xx;
  99908. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  99909. if (len > 0) len = this.radius / len;
  99910. wx *= len;
  99911. hy = 1 - yy;
  99912. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  99913. if (len > 0) len = this.radius / len;
  99914. hy *= len;
  99915. dz = 1 - zz;
  99916. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  99917. if (len > 0) len = this.radius / len;
  99918. dz *= len;
  99919. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  99920. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  99921. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  99922. w = wx < 0 ? w - wx : w + wx;
  99923. h = hy < 0 ? h - hy : h + hy;
  99924. d = dz < 0 ? d - dz : d + dz;
  99925. p = OIMO.AABB_PROX;
  99926. this.aabb.set(
  99927. this.position.x - w - p, this.position.x + w + p,
  99928. this.position.y - h - p, this.position.y + h + p,
  99929. this.position.z - d - p, this.position.z + d + p
  99930. );
  99931. if (this.proxy != null) this.proxy.update();
  99932. };
  99933. /**
  99934. * A tetra shape.
  99935. * @author xprogram
  99936. */
  99937. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  99938. OIMO.Shape.call(this, config);
  99939. this.type = OIMO.SHAPE_TETRA;
  99940. // Vertices and faces of tetra
  99941. this.verts = [p1, p2, p3, p4];
  99942. this.faces = [
  99943. mtri(0, 1, 2),
  99944. mtri(1, 2, 3),
  99945. mtri(2, 3, 4),
  99946. mtri(4, 0, 1),
  99947. ];
  99948. };
  99949. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  99950. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  99951. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  99952. // I guess you could calculate box mass and split it
  99953. // in half for the tetra...
  99954. };
  99955. OIMO.TetraShape.prototype.updateProxy = function () {
  99956. this.aabb.setFromPoints(this.verts);
  99957. if (this.proxy !== null)
  99958. this.proxy.update();
  99959. };
  99960. function mtri(a, b, c) {
  99961. return { a: a, b: b, c: c };
  99962. }
  99963. OIMO.CollisionDetector = function () {
  99964. this.flip = false;
  99965. };
  99966. OIMO.CollisionDetector.prototype = {
  99967. constructor: OIMO.CollisionDetector,
  99968. detectCollision: function (shape1, shape2, manifold) {
  99969. OIMO.Error("CollisionDetector", "Inheritance error.");
  99970. }
  99971. };
  99972. /**
  99973. * A collision detector which detects collisions between two boxes.
  99974. * @author saharan
  99975. */
  99976. OIMO.BoxBoxCollisionDetector = function () {
  99977. OIMO.CollisionDetector.call(this);
  99978. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  99979. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  99980. this.used = new OIMO_ARRAY_TYPE(8);
  99981. this.INF = 1 / 0;
  99982. };
  99983. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99984. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  99985. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99986. // What you are doing
  99987. // · I to prepare a separate axis of the fifteen
  99988. //-Six in each of three normal vectors of the xyz direction of the box both
  99989. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  99990. // · Calculate the depth to the separation axis
  99991. // Calculates the distance using the inner product and put the amount of embedment
  99992. // · However a vertical separation axis and side to weight a little to avoid vibration
  99993. // And end when there is a separate axis that is remote even one
  99994. // · I look for separation axis with little to dent most
  99995. // Men and if separation axis of the first six - end collision
  99996. // Heng If it separate axis of nine other - side collision
  99997. // Heng - case of a side collision
  99998. // · Find points of two sides on which you made ​​the separation axis
  99999. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  100000. //-Surface - the case of the plane crash
  100001. //-Box A, box B and the other a box of better made ​​a separate axis
  100002. // • 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
  100003. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  100004. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  100005. // • If more than one candidate 5 exists, scraping up to four
  100006. // For potential collision points of all, to examine the distance between the surface A
  100007. // • If you were on the inside surface of A, and the collision point
  100008. var b1;
  100009. var b2;
  100010. if (shape1.id < shape2.id) {
  100011. b1 = (shape1);
  100012. b2 = (shape2);
  100013. } else {
  100014. b1 = (shape2);
  100015. b2 = (shape1);
  100016. }
  100017. var V1 = b1.elements;
  100018. var V2 = b2.elements;
  100019. var D1 = b1.dimentions;
  100020. var D2 = b2.dimentions;
  100021. var p1 = b1.position;
  100022. var p2 = b2.position;
  100023. var p1x = p1.x;
  100024. var p1y = p1.y;
  100025. var p1z = p1.z;
  100026. var p2x = p2.x;
  100027. var p2y = p2.y;
  100028. var p2z = p2.z;
  100029. // diff
  100030. var dx = p2x - p1x;
  100031. var dy = p2y - p1y;
  100032. var dz = p2z - p1z;
  100033. // distance
  100034. var w1 = b1.halfWidth;
  100035. var h1 = b1.halfHeight;
  100036. var d1 = b1.halfDepth;
  100037. var w2 = b2.halfWidth;
  100038. var h2 = b2.halfHeight;
  100039. var d2 = b2.halfDepth;
  100040. // direction
  100041. // ----------------------------
  100042. // 15 separating axes
  100043. // 1~6: face
  100044. // 7~f: edge
  100045. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  100046. // ----------------------------
  100047. var a1x = D1[0];
  100048. var a1y = D1[1];
  100049. var a1z = D1[2];
  100050. var a2x = D1[3];
  100051. var a2y = D1[4];
  100052. var a2z = D1[5];
  100053. var a3x = D1[6];
  100054. var a3y = D1[7];
  100055. var a3z = D1[8];
  100056. var d1x = D1[9];
  100057. var d1y = D1[10];
  100058. var d1z = D1[11];
  100059. var d2x = D1[12];
  100060. var d2y = D1[13];
  100061. var d2z = D1[14];
  100062. var d3x = D1[15];
  100063. var d3y = D1[16];
  100064. var d3z = D1[17];
  100065. var a4x = D2[0];
  100066. var a4y = D2[1];
  100067. var a4z = D2[2];
  100068. var a5x = D2[3];
  100069. var a5y = D2[4];
  100070. var a5z = D2[5];
  100071. var a6x = D2[6];
  100072. var a6y = D2[7];
  100073. var a6z = D2[8];
  100074. var d4x = D2[9];
  100075. var d4y = D2[10];
  100076. var d4z = D2[11];
  100077. var d5x = D2[12];
  100078. var d5y = D2[13];
  100079. var d5z = D2[14];
  100080. var d6x = D2[15];
  100081. var d6y = D2[16];
  100082. var d6z = D2[17];
  100083. var a7x = a1y * a4z - a1z * a4y;
  100084. var a7y = a1z * a4x - a1x * a4z;
  100085. var a7z = a1x * a4y - a1y * a4x;
  100086. var a8x = a1y * a5z - a1z * a5y;
  100087. var a8y = a1z * a5x - a1x * a5z;
  100088. var a8z = a1x * a5y - a1y * a5x;
  100089. var a9x = a1y * a6z - a1z * a6y;
  100090. var a9y = a1z * a6x - a1x * a6z;
  100091. var a9z = a1x * a6y - a1y * a6x;
  100092. var aax = a2y * a4z - a2z * a4y;
  100093. var aay = a2z * a4x - a2x * a4z;
  100094. var aaz = a2x * a4y - a2y * a4x;
  100095. var abx = a2y * a5z - a2z * a5y;
  100096. var aby = a2z * a5x - a2x * a5z;
  100097. var abz = a2x * a5y - a2y * a5x;
  100098. var acx = a2y * a6z - a2z * a6y;
  100099. var acy = a2z * a6x - a2x * a6z;
  100100. var acz = a2x * a6y - a2y * a6x;
  100101. var adx = a3y * a4z - a3z * a4y;
  100102. var ady = a3z * a4x - a3x * a4z;
  100103. var adz = a3x * a4y - a3y * a4x;
  100104. var aex = a3y * a5z - a3z * a5y;
  100105. var aey = a3z * a5x - a3x * a5z;
  100106. var aez = a3x * a5y - a3y * a5x;
  100107. var afx = a3y * a6z - a3z * a6y;
  100108. var afy = a3z * a6x - a3x * a6z;
  100109. var afz = a3x * a6y - a3y * a6x;
  100110. // right or left flags
  100111. var right1;
  100112. var right2;
  100113. var right3;
  100114. var right4;
  100115. var right5;
  100116. var right6;
  100117. var right7;
  100118. var right8;
  100119. var right9;
  100120. var righta;
  100121. var rightb;
  100122. var rightc;
  100123. var rightd;
  100124. var righte;
  100125. var rightf;
  100126. // overlapping distances
  100127. var overlap1;
  100128. var overlap2;
  100129. var overlap3;
  100130. var overlap4;
  100131. var overlap5;
  100132. var overlap6;
  100133. var overlap7;
  100134. var overlap8;
  100135. var overlap9;
  100136. var overlapa;
  100137. var overlapb;
  100138. var overlapc;
  100139. var overlapd;
  100140. var overlape;
  100141. var overlapf;
  100142. // invalid flags
  100143. var invalid7 = false;
  100144. var invalid8 = false;
  100145. var invalid9 = false;
  100146. var invalida = false;
  100147. var invalidb = false;
  100148. var invalidc = false;
  100149. var invalidd = false;
  100150. var invalide = false;
  100151. var invalidf = false;
  100152. // temporary variables
  100153. var len;
  100154. var len1;
  100155. var len2;
  100156. var dot1;
  100157. var dot2;
  100158. var dot3;
  100159. // try axis 1
  100160. len = a1x * dx + a1y * dy + a1z * dz;
  100161. right1 = len > 0;
  100162. if (!right1) len = -len;
  100163. len1 = w1;
  100164. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  100165. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  100166. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  100167. if (dot1 < 0) dot1 = -dot1;
  100168. if (dot2 < 0) dot2 = -dot2;
  100169. if (dot3 < 0) dot3 = -dot3;
  100170. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  100171. overlap1 = len - len1 - len2;
  100172. if (overlap1 > 0) return;
  100173. // try axis 2
  100174. len = a2x * dx + a2y * dy + a2z * dz;
  100175. right2 = len > 0;
  100176. if (!right2) len = -len;
  100177. len1 = h1;
  100178. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  100179. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  100180. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  100181. if (dot1 < 0) dot1 = -dot1;
  100182. if (dot2 < 0) dot2 = -dot2;
  100183. if (dot3 < 0) dot3 = -dot3;
  100184. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  100185. overlap2 = len - len1 - len2;
  100186. if (overlap2 > 0) return;
  100187. // try axis 3
  100188. len = a3x * dx + a3y * dy + a3z * dz;
  100189. right3 = len > 0;
  100190. if (!right3) len = -len;
  100191. len1 = d1;
  100192. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  100193. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  100194. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  100195. if (dot1 < 0) dot1 = -dot1;
  100196. if (dot2 < 0) dot2 = -dot2;
  100197. if (dot3 < 0) dot3 = -dot3;
  100198. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  100199. overlap3 = len - len1 - len2;
  100200. if (overlap3 > 0) return;
  100201. // try axis 4
  100202. len = a4x * dx + a4y * dy + a4z * dz;
  100203. right4 = len > 0;
  100204. if (!right4) len = -len;
  100205. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  100206. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  100207. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  100208. if (dot1 < 0) dot1 = -dot1;
  100209. if (dot2 < 0) dot2 = -dot2;
  100210. if (dot3 < 0) dot3 = -dot3;
  100211. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  100212. len2 = w2;
  100213. overlap4 = (len - len1 - len2) * 1.0;
  100214. if (overlap4 > 0) return;
  100215. // try axis 5
  100216. len = a5x * dx + a5y * dy + a5z * dz;
  100217. right5 = len > 0;
  100218. if (!right5) len = -len;
  100219. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  100220. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  100221. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  100222. if (dot1 < 0) dot1 = -dot1;
  100223. if (dot2 < 0) dot2 = -dot2;
  100224. if (dot3 < 0) dot3 = -dot3;
  100225. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  100226. len2 = h2;
  100227. overlap5 = (len - len1 - len2) * 1.0;
  100228. if (overlap5 > 0) return;
  100229. // try axis 6
  100230. len = a6x * dx + a6y * dy + a6z * dz;
  100231. right6 = len > 0;
  100232. if (!right6) len = -len;
  100233. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  100234. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  100235. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  100236. if (dot1 < 0) dot1 = -dot1;
  100237. if (dot2 < 0) dot2 = -dot2;
  100238. if (dot3 < 0) dot3 = -dot3;
  100239. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  100240. len2 = d2;
  100241. overlap6 = (len - len1 - len2) * 1.0;
  100242. if (overlap6 > 0) return;
  100243. // try axis 7
  100244. len = a7x * a7x + a7y * a7y + a7z * a7z;
  100245. if (len > 1e-5) {
  100246. len = 1 / OIMO.sqrt(len);
  100247. a7x *= len;
  100248. a7y *= len;
  100249. a7z *= len;
  100250. len = a7x * dx + a7y * dy + a7z * dz;
  100251. right7 = len > 0;
  100252. if (!right7) len = -len;
  100253. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  100254. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  100255. if (dot1 < 0) dot1 = -dot1;
  100256. if (dot2 < 0) dot2 = -dot2;
  100257. len1 = dot1 * h1 + dot2 * d1;
  100258. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  100259. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  100260. if (dot1 < 0) dot1 = -dot1;
  100261. if (dot2 < 0) dot2 = -dot2;
  100262. len2 = dot1 * h2 + dot2 * d2;
  100263. overlap7 = len - len1 - len2;
  100264. if (overlap7 > 0) return;
  100265. } else {
  100266. right7 = false;
  100267. overlap7 = 0;
  100268. invalid7 = true;
  100269. }
  100270. // try axis 8
  100271. len = a8x * a8x + a8y * a8y + a8z * a8z;
  100272. if (len > 1e-5) {
  100273. len = 1 / OIMO.sqrt(len);
  100274. a8x *= len;
  100275. a8y *= len;
  100276. a8z *= len;
  100277. len = a8x * dx + a8y * dy + a8z * dz;
  100278. right8 = len > 0;
  100279. if (!right8) len = -len;
  100280. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  100281. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  100282. if (dot1 < 0) dot1 = -dot1;
  100283. if (dot2 < 0) dot2 = -dot2;
  100284. len1 = dot1 * h1 + dot2 * d1;
  100285. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  100286. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  100287. if (dot1 < 0) dot1 = -dot1;
  100288. if (dot2 < 0) dot2 = -dot2;
  100289. len2 = dot1 * w2 + dot2 * d2;
  100290. overlap8 = len - len1 - len2;
  100291. if (overlap8 > 0) return;
  100292. } else {
  100293. right8 = false;
  100294. overlap8 = 0;
  100295. invalid8 = true;
  100296. }
  100297. // try axis 9
  100298. len = a9x * a9x + a9y * a9y + a9z * a9z;
  100299. if (len > 1e-5) {
  100300. len = 1 / OIMO.sqrt(len);
  100301. a9x *= len;
  100302. a9y *= len;
  100303. a9z *= len;
  100304. len = a9x * dx + a9y * dy + a9z * dz;
  100305. right9 = len > 0;
  100306. if (!right9) len = -len;
  100307. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  100308. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  100309. if (dot1 < 0) dot1 = -dot1;
  100310. if (dot2 < 0) dot2 = -dot2;
  100311. len1 = dot1 * h1 + dot2 * d1;
  100312. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  100313. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  100314. if (dot1 < 0) dot1 = -dot1;
  100315. if (dot2 < 0) dot2 = -dot2;
  100316. len2 = dot1 * w2 + dot2 * h2;
  100317. overlap9 = len - len1 - len2;
  100318. if (overlap9 > 0) return;
  100319. } else {
  100320. right9 = false;
  100321. overlap9 = 0;
  100322. invalid9 = true;
  100323. }
  100324. // try axis 10
  100325. len = aax * aax + aay * aay + aaz * aaz;
  100326. if (len > 1e-5) {
  100327. len = 1 / OIMO.sqrt(len);
  100328. aax *= len;
  100329. aay *= len;
  100330. aaz *= len;
  100331. len = aax * dx + aay * dy + aaz * dz;
  100332. righta = len > 0;
  100333. if (!righta) len = -len;
  100334. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  100335. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  100336. if (dot1 < 0) dot1 = -dot1;
  100337. if (dot2 < 0) dot2 = -dot2;
  100338. len1 = dot1 * w1 + dot2 * d1;
  100339. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  100340. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  100341. if (dot1 < 0) dot1 = -dot1;
  100342. if (dot2 < 0) dot2 = -dot2;
  100343. len2 = dot1 * h2 + dot2 * d2;
  100344. overlapa = len - len1 - len2;
  100345. if (overlapa > 0) return;
  100346. } else {
  100347. righta = false;
  100348. overlapa = 0;
  100349. invalida = true;
  100350. }
  100351. // try axis 11
  100352. len = abx * abx + aby * aby + abz * abz;
  100353. if (len > 1e-5) {
  100354. len = 1 / OIMO.sqrt(len);
  100355. abx *= len;
  100356. aby *= len;
  100357. abz *= len;
  100358. len = abx * dx + aby * dy + abz * dz;
  100359. rightb = len > 0;
  100360. if (!rightb) len = -len;
  100361. dot1 = abx * a1x + aby * a1y + abz * a1z;
  100362. dot2 = abx * a3x + aby * a3y + abz * a3z;
  100363. if (dot1 < 0) dot1 = -dot1;
  100364. if (dot2 < 0) dot2 = -dot2;
  100365. len1 = dot1 * w1 + dot2 * d1;
  100366. dot1 = abx * a4x + aby * a4y + abz * a4z;
  100367. dot2 = abx * a6x + aby * a6y + abz * a6z;
  100368. if (dot1 < 0) dot1 = -dot1;
  100369. if (dot2 < 0) dot2 = -dot2;
  100370. len2 = dot1 * w2 + dot2 * d2;
  100371. overlapb = len - len1 - len2;
  100372. if (overlapb > 0) return;
  100373. } else {
  100374. rightb = false;
  100375. overlapb = 0;
  100376. invalidb = true;
  100377. }
  100378. // try axis 12
  100379. len = acx * acx + acy * acy + acz * acz;
  100380. if (len > 1e-5) {
  100381. len = 1 / OIMO.sqrt(len);
  100382. acx *= len;
  100383. acy *= len;
  100384. acz *= len;
  100385. len = acx * dx + acy * dy + acz * dz;
  100386. rightc = len > 0;
  100387. if (!rightc) len = -len;
  100388. dot1 = acx * a1x + acy * a1y + acz * a1z;
  100389. dot2 = acx * a3x + acy * a3y + acz * a3z;
  100390. if (dot1 < 0) dot1 = -dot1;
  100391. if (dot2 < 0) dot2 = -dot2;
  100392. len1 = dot1 * w1 + dot2 * d1;
  100393. dot1 = acx * a4x + acy * a4y + acz * a4z;
  100394. dot2 = acx * a5x + acy * a5y + acz * a5z;
  100395. if (dot1 < 0) dot1 = -dot1;
  100396. if (dot2 < 0) dot2 = -dot2;
  100397. len2 = dot1 * w2 + dot2 * h2;
  100398. overlapc = len - len1 - len2;
  100399. if (overlapc > 0) return;
  100400. } else {
  100401. rightc = false;
  100402. overlapc = 0;
  100403. invalidc = true;
  100404. }
  100405. // try axis 13
  100406. len = adx * adx + ady * ady + adz * adz;
  100407. if (len > 1e-5) {
  100408. len = 1 / OIMO.sqrt(len);
  100409. adx *= len;
  100410. ady *= len;
  100411. adz *= len;
  100412. len = adx * dx + ady * dy + adz * dz;
  100413. rightd = len > 0;
  100414. if (!rightd) len = -len;
  100415. dot1 = adx * a1x + ady * a1y + adz * a1z;
  100416. dot2 = adx * a2x + ady * a2y + adz * a2z;
  100417. if (dot1 < 0) dot1 = -dot1;
  100418. if (dot2 < 0) dot2 = -dot2;
  100419. len1 = dot1 * w1 + dot2 * h1;
  100420. dot1 = adx * a5x + ady * a5y + adz * a5z;
  100421. dot2 = adx * a6x + ady * a6y + adz * a6z;
  100422. if (dot1 < 0) dot1 = -dot1;
  100423. if (dot2 < 0) dot2 = -dot2;
  100424. len2 = dot1 * h2 + dot2 * d2;
  100425. overlapd = len - len1 - len2;
  100426. if (overlapd > 0) return;
  100427. } else {
  100428. rightd = false;
  100429. overlapd = 0;
  100430. invalidd = true;
  100431. }
  100432. // try axis 14
  100433. len = aex * aex + aey * aey + aez * aez;
  100434. if (len > 1e-5) {
  100435. len = 1 / OIMO.sqrt(len);
  100436. aex *= len;
  100437. aey *= len;
  100438. aez *= len;
  100439. len = aex * dx + aey * dy + aez * dz;
  100440. righte = len > 0;
  100441. if (!righte) len = -len;
  100442. dot1 = aex * a1x + aey * a1y + aez * a1z;
  100443. dot2 = aex * a2x + aey * a2y + aez * a2z;
  100444. if (dot1 < 0) dot1 = -dot1;
  100445. if (dot2 < 0) dot2 = -dot2;
  100446. len1 = dot1 * w1 + dot2 * h1;
  100447. dot1 = aex * a4x + aey * a4y + aez * a4z;
  100448. dot2 = aex * a6x + aey * a6y + aez * a6z;
  100449. if (dot1 < 0) dot1 = -dot1;
  100450. if (dot2 < 0) dot2 = -dot2;
  100451. len2 = dot1 * w2 + dot2 * d2;
  100452. overlape = len - len1 - len2;
  100453. if (overlape > 0) return;
  100454. } else {
  100455. righte = false;
  100456. overlape = 0;
  100457. invalide = true;
  100458. }
  100459. // try axis 15
  100460. len = afx * afx + afy * afy + afz * afz;
  100461. if (len > 1e-5) {
  100462. len = 1 / OIMO.sqrt(len);
  100463. afx *= len;
  100464. afy *= len;
  100465. afz *= len;
  100466. len = afx * dx + afy * dy + afz * dz;
  100467. rightf = len > 0;
  100468. if (!rightf) len = -len;
  100469. dot1 = afx * a1x + afy * a1y + afz * a1z;
  100470. dot2 = afx * a2x + afy * a2y + afz * a2z;
  100471. if (dot1 < 0) dot1 = -dot1;
  100472. if (dot2 < 0) dot2 = -dot2;
  100473. len1 = dot1 * w1 + dot2 * h1;
  100474. dot1 = afx * a4x + afy * a4y + afz * a4z;
  100475. dot2 = afx * a5x + afy * a5y + afz * a5z;
  100476. if (dot1 < 0) dot1 = -dot1;
  100477. if (dot2 < 0) dot2 = -dot2;
  100478. len2 = dot1 * w2 + dot2 * h2;
  100479. overlapf = len - len1 - len2;
  100480. if (overlapf > 0) return;
  100481. } else {
  100482. rightf = false;
  100483. overlapf = 0;
  100484. invalidf = true;
  100485. }
  100486. // boxes are overlapping
  100487. var depth = overlap1;
  100488. var depth2 = overlap1;
  100489. var minIndex = 0;
  100490. var right = right1;
  100491. if (overlap2 > depth2) {
  100492. depth = overlap2;
  100493. depth2 = overlap2;
  100494. minIndex = 1;
  100495. right = right2;
  100496. }
  100497. if (overlap3 > depth2) {
  100498. depth = overlap3;
  100499. depth2 = overlap3;
  100500. minIndex = 2;
  100501. right = right3;
  100502. }
  100503. if (overlap4 > depth2) {
  100504. depth = overlap4;
  100505. depth2 = overlap4;
  100506. minIndex = 3;
  100507. right = right4;
  100508. }
  100509. if (overlap5 > depth2) {
  100510. depth = overlap5;
  100511. depth2 = overlap5;
  100512. minIndex = 4;
  100513. right = right5;
  100514. }
  100515. if (overlap6 > depth2) {
  100516. depth = overlap6;
  100517. depth2 = overlap6;
  100518. minIndex = 5;
  100519. right = right6;
  100520. }
  100521. if (overlap7 - 0.01 > depth2 && !invalid7) {
  100522. depth = overlap7;
  100523. depth2 = overlap7 - 0.01;
  100524. minIndex = 6;
  100525. right = right7;
  100526. }
  100527. if (overlap8 - 0.01 > depth2 && !invalid8) {
  100528. depth = overlap8;
  100529. depth2 = overlap8 - 0.01;
  100530. minIndex = 7;
  100531. right = right8;
  100532. }
  100533. if (overlap9 - 0.01 > depth2 && !invalid9) {
  100534. depth = overlap9;
  100535. depth2 = overlap9 - 0.01;
  100536. minIndex = 8;
  100537. right = right9;
  100538. }
  100539. if (overlapa - 0.01 > depth2 && !invalida) {
  100540. depth = overlapa;
  100541. depth2 = overlapa - 0.01;
  100542. minIndex = 9;
  100543. right = righta;
  100544. }
  100545. if (overlapb - 0.01 > depth2 && !invalidb) {
  100546. depth = overlapb;
  100547. depth2 = overlapb - 0.01;
  100548. minIndex = 10;
  100549. right = rightb;
  100550. }
  100551. if (overlapc - 0.01 > depth2 && !invalidc) {
  100552. depth = overlapc;
  100553. depth2 = overlapc - 0.01;
  100554. minIndex = 11;
  100555. right = rightc;
  100556. }
  100557. if (overlapd - 0.01 > depth2 && !invalidd) {
  100558. depth = overlapd;
  100559. depth2 = overlapd - 0.01;
  100560. minIndex = 12;
  100561. right = rightd;
  100562. }
  100563. if (overlape - 0.01 > depth2 && !invalide) {
  100564. depth = overlape;
  100565. depth2 = overlape - 0.01;
  100566. minIndex = 13;
  100567. right = righte;
  100568. }
  100569. if (overlapf - 0.01 > depth2 && !invalidf) {
  100570. depth = overlapf;
  100571. minIndex = 14;
  100572. right = rightf;
  100573. }
  100574. // normal
  100575. var nx = 0;
  100576. var ny = 0;
  100577. var nz = 0;
  100578. // edge line or face side normal
  100579. var n1x = 0;
  100580. var n1y = 0;
  100581. var n1z = 0;
  100582. var n2x = 0;
  100583. var n2y = 0;
  100584. var n2z = 0;
  100585. // center of current face
  100586. var cx = 0;
  100587. var cy = 0;
  100588. var cz = 0;
  100589. // face side
  100590. var s1x = 0;
  100591. var s1y = 0;
  100592. var s1z = 0;
  100593. var s2x = 0;
  100594. var s2y = 0;
  100595. var s2z = 0;
  100596. // swap b1 b2
  100597. var swap = false;
  100598. //_______________________________________
  100599. if (minIndex == 0) {// b1.x * b2
  100600. if (right) {
  100601. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  100602. nx = a1x; ny = a1y; nz = a1z;
  100603. } else {
  100604. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  100605. nx = -a1x; ny = -a1y; nz = -a1z;
  100606. }
  100607. s1x = d2x; s1y = d2y; s1z = d2z;
  100608. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  100609. s2x = d3x; s2y = d3y; s2z = d3z;
  100610. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  100611. }
  100612. else if (minIndex == 1) {// b1.y * b2
  100613. if (right) {
  100614. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  100615. nx = a2x; ny = a2y; nz = a2z;
  100616. } else {
  100617. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  100618. nx = -a2x; ny = -a2y; nz = -a2z;
  100619. }
  100620. s1x = d1x; s1y = d1y; s1z = d1z;
  100621. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  100622. s2x = d3x; s2y = d3y; s2z = d3z;
  100623. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  100624. }
  100625. else if (minIndex == 2) {// b1.z * b2
  100626. if (right) {
  100627. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  100628. nx = a3x; ny = a3y; nz = a3z;
  100629. } else {
  100630. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  100631. nx = -a3x; ny = -a3y; nz = -a3z;
  100632. }
  100633. s1x = d1x; s1y = d1y; s1z = d1z;
  100634. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  100635. s2x = d2x; s2y = d2y; s2z = d2z;
  100636. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  100637. }
  100638. else if (minIndex == 3) {// b2.x * b1
  100639. swap = true;
  100640. if (!right) {
  100641. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  100642. nx = a4x; ny = a4y; nz = a4z;
  100643. } else {
  100644. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  100645. nx = -a4x; ny = -a4y; nz = -a4z;
  100646. }
  100647. s1x = d5x; s1y = d5y; s1z = d5z;
  100648. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  100649. s2x = d6x; s2y = d6y; s2z = d6z;
  100650. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  100651. }
  100652. else if (minIndex == 4) {// b2.y * b1
  100653. swap = true;
  100654. if (!right) {
  100655. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  100656. nx = a5x; ny = a5y; nz = a5z;
  100657. } else {
  100658. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  100659. nx = -a5x; ny = -a5y; nz = -a5z;
  100660. }
  100661. s1x = d4x; s1y = d4y; s1z = d4z;
  100662. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  100663. s2x = d6x; s2y = d6y; s2z = d6z;
  100664. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  100665. }
  100666. else if (minIndex == 5) {// b2.z * b1
  100667. swap = true;
  100668. if (!right) {
  100669. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  100670. nx = a6x; ny = a6y; nz = a6z;
  100671. } else {
  100672. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  100673. nx = -a6x; ny = -a6y; nz = -a6z;
  100674. }
  100675. s1x = d4x; s1y = d4y; s1z = d4z;
  100676. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  100677. s2x = d5x; s2y = d5y; s2z = d5z;
  100678. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  100679. }
  100680. else if (minIndex == 6) {// b1.x * b2.x
  100681. nx = a7x; ny = a7y; nz = a7z;
  100682. n1x = a1x; n1y = a1y; n1z = a1z;
  100683. n2x = a4x; n2y = a4y; n2z = a4z;
  100684. }
  100685. else if (minIndex == 7) {// b1.x * b2.y
  100686. nx = a8x; ny = a8y; nz = a8z;
  100687. n1x = a1x; n1y = a1y; n1z = a1z;
  100688. n2x = a5x; n2y = a5y; n2z = a5z;
  100689. }
  100690. else if (minIndex == 8) {// b1.x * b2.z
  100691. nx = a9x; ny = a9y; nz = a9z;
  100692. n1x = a1x; n1y = a1y; n1z = a1z;
  100693. n2x = a6x; n2y = a6y; n2z = a6z;
  100694. }
  100695. else if (minIndex == 9) {// b1.y * b2.x
  100696. nx = aax; ny = aay; nz = aaz;
  100697. n1x = a2x; n1y = a2y; n1z = a2z;
  100698. n2x = a4x; n2y = a4y; n2z = a4z
  100699. }
  100700. else if (minIndex == 10) {// b1.y * b2.y
  100701. nx = abx; ny = aby; nz = abz;
  100702. n1x = a2x; n1y = a2y; n1z = a2z;
  100703. n2x = a5x; n2y = a5y; n2z = a5z;
  100704. }
  100705. else if (minIndex == 11) {// b1.y * b2.z
  100706. nx = acx; ny = acy; nz = acz;
  100707. n1x = a2x; n1y = a2y; n1z = a2z;
  100708. n2x = a6x; n2y = a6y; n2z = a6z;
  100709. }
  100710. else if (minIndex == 12) {// b1.z * b2.x
  100711. nx = adx; ny = ady; nz = adz;
  100712. n1x = a3x; n1y = a3y; n1z = a3z;
  100713. n2x = a4x; n2y = a4y; n2z = a4z;
  100714. }
  100715. else if (minIndex == 13) {// b1.z * b2.y
  100716. nx = aex; ny = aey; nz = aez;
  100717. n1x = a3x; n1y = a3y; n1z = a3z;
  100718. n2x = a5x; n2y = a5y; n2z = a5z;
  100719. }
  100720. else if (minIndex == 14) {// b1.z * b2.z
  100721. nx = afx; ny = afy; nz = afz;
  100722. n1x = a3x; n1y = a3y; n1z = a3z;
  100723. n2x = a6x; n2y = a6y; n2z = a6z;
  100724. }
  100725. //__________________________________________
  100726. var v;
  100727. if (minIndex > 5) {
  100728. if (!right) {
  100729. nx = -nx; ny = -ny; nz = -nz;
  100730. }
  100731. var distance;
  100732. var maxDistance;
  100733. var vx;
  100734. var vy;
  100735. var vz;
  100736. var v1x;
  100737. var v1y;
  100738. var v1z;
  100739. var v2x;
  100740. var v2y;
  100741. var v2z;
  100742. //vertex1;
  100743. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  100744. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  100745. //vertex2;
  100746. vx = V1[3]; vy = V1[4]; vz = V1[5];
  100747. distance = nx * vx + ny * vy + nz * vz;
  100748. if (distance > maxDistance) {
  100749. maxDistance = distance;
  100750. v1x = vx; v1y = vy; v1z = vz;
  100751. }
  100752. //vertex3;
  100753. vx = V1[6]; vy = V1[7]; vz = V1[8];
  100754. distance = nx * vx + ny * vy + nz * vz;
  100755. if (distance > maxDistance) {
  100756. maxDistance = distance;
  100757. v1x = vx; v1y = vy; v1z = vz;
  100758. }
  100759. //vertex4;
  100760. vx = V1[9]; vy = V1[10]; vz = V1[11];
  100761. distance = nx * vx + ny * vy + nz * vz;
  100762. if (distance > maxDistance) {
  100763. maxDistance = distance;
  100764. v1x = vx; v1y = vy; v1z = vz;
  100765. }
  100766. //vertex5;
  100767. vx = V1[12]; vy = V1[13]; vz = V1[14];
  100768. distance = nx * vx + ny * vy + nz * vz;
  100769. if (distance > maxDistance) {
  100770. maxDistance = distance;
  100771. v1x = vx; v1y = vy; v1z = vz;
  100772. }
  100773. //vertex6;
  100774. vx = V1[15]; vy = V1[16]; vz = V1[17];
  100775. distance = nx * vx + ny * vy + nz * vz;
  100776. if (distance > maxDistance) {
  100777. maxDistance = distance;
  100778. v1x = vx; v1y = vy; v1z = vz;
  100779. }
  100780. //vertex7;
  100781. vx = V1[18]; vy = V1[19]; vz = V1[20];
  100782. distance = nx * vx + ny * vy + nz * vz;
  100783. if (distance > maxDistance) {
  100784. maxDistance = distance;
  100785. v1x = vx; v1y = vy; v1z = vz;
  100786. }
  100787. //vertex8;
  100788. vx = V1[21]; vy = V1[22]; vz = V1[23];
  100789. distance = nx * vx + ny * vy + nz * vz;
  100790. if (distance > maxDistance) {
  100791. maxDistance = distance;
  100792. v1x = vx; v1y = vy; v1z = vz;
  100793. }
  100794. //vertex1;
  100795. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  100796. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  100797. //vertex2;
  100798. vx = V2[3]; vy = V2[4]; vz = V2[5];
  100799. distance = nx * vx + ny * vy + nz * vz;
  100800. if (distance < maxDistance) {
  100801. maxDistance = distance;
  100802. v2x = vx; v2y = vy; v2z = vz;
  100803. }
  100804. //vertex3;
  100805. vx = V2[6]; vy = V2[7]; vz = V2[8];
  100806. distance = nx * vx + ny * vy + nz * vz;
  100807. if (distance < maxDistance) {
  100808. maxDistance = distance;
  100809. v2x = vx; v2y = vy; v2z = vz;
  100810. }
  100811. //vertex4;
  100812. vx = V2[9]; vy = V2[10]; vz = V2[11];
  100813. distance = nx * vx + ny * vy + nz * vz;
  100814. if (distance < maxDistance) {
  100815. maxDistance = distance;
  100816. v2x = vx; v2y = vy; v2z = vz;
  100817. }
  100818. //vertex5;
  100819. vx = V2[12]; vy = V2[13]; vz = V2[14];
  100820. distance = nx * vx + ny * vy + nz * vz;
  100821. if (distance < maxDistance) {
  100822. maxDistance = distance;
  100823. v2x = vx; v2y = vy; v2z = vz;
  100824. }
  100825. //vertex6;
  100826. vx = V2[15]; vy = V2[16]; vz = V2[17];
  100827. distance = nx * vx + ny * vy + nz * vz;
  100828. if (distance < maxDistance) {
  100829. maxDistance = distance;
  100830. v2x = vx; v2y = vy; v2z = vz;
  100831. }
  100832. //vertex7;
  100833. vx = V2[18]; vy = V2[19]; vz = V2[20];
  100834. distance = nx * vx + ny * vy + nz * vz;
  100835. if (distance < maxDistance) {
  100836. maxDistance = distance;
  100837. v2x = vx; v2y = vy; v2z = vz;
  100838. }
  100839. //vertex8;
  100840. vx = V2[21]; vy = V2[22]; vz = V2[23];
  100841. distance = nx * vx + ny * vy + nz * vz;
  100842. if (distance < maxDistance) {
  100843. maxDistance = distance;
  100844. v2x = vx; v2y = vy; v2z = vz;
  100845. }
  100846. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  100847. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  100848. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  100849. 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);
  100850. return;
  100851. }
  100852. // now detect face-face collision...
  100853. // target quad
  100854. var q1x;
  100855. var q1y;
  100856. var q1z;
  100857. var q2x;
  100858. var q2y;
  100859. var q2z;
  100860. var q3x;
  100861. var q3y;
  100862. var q3z;
  100863. var q4x;
  100864. var q4y;
  100865. var q4z;
  100866. // search support face and vertex
  100867. var minDot = 1;
  100868. var dot = 0;
  100869. var minDotIndex = 0;
  100870. if (swap) {
  100871. dot = a1x * nx + a1y * ny + a1z * nz;
  100872. if (dot < minDot) {
  100873. minDot = dot;
  100874. minDotIndex = 0;
  100875. }
  100876. if (-dot < minDot) {
  100877. minDot = -dot;
  100878. minDotIndex = 1;
  100879. }
  100880. dot = a2x * nx + a2y * ny + a2z * nz;
  100881. if (dot < minDot) {
  100882. minDot = dot;
  100883. minDotIndex = 2;
  100884. }
  100885. if (-dot < minDot) {
  100886. minDot = -dot;
  100887. minDotIndex = 3;
  100888. }
  100889. dot = a3x * nx + a3y * ny + a3z * nz;
  100890. if (dot < minDot) {
  100891. minDot = dot;
  100892. minDotIndex = 4;
  100893. }
  100894. if (-dot < minDot) {
  100895. minDot = -dot;
  100896. minDotIndex = 5;
  100897. }
  100898. if (minDotIndex == 0) {// x+ face
  100899. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  100900. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  100901. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  100902. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  100903. }
  100904. else if (minDotIndex == 1) {// x- face
  100905. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  100906. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  100907. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  100908. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  100909. }
  100910. else if (minDotIndex == 2) {// y+ face
  100911. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  100912. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  100913. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  100914. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  100915. }
  100916. else if (minDotIndex == 3) {// y- face
  100917. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  100918. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  100919. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  100920. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  100921. }
  100922. else if (minDotIndex == 4) {// z+ face
  100923. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  100924. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  100925. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  100926. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  100927. }
  100928. else if (minDotIndex == 5) {// z- face
  100929. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  100930. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  100931. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  100932. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  100933. }
  100934. } else {
  100935. dot = a4x * nx + a4y * ny + a4z * nz;
  100936. if (dot < minDot) {
  100937. minDot = dot;
  100938. minDotIndex = 0;
  100939. }
  100940. if (-dot < minDot) {
  100941. minDot = -dot;
  100942. minDotIndex = 1;
  100943. }
  100944. dot = a5x * nx + a5y * ny + a5z * nz;
  100945. if (dot < minDot) {
  100946. minDot = dot;
  100947. minDotIndex = 2;
  100948. }
  100949. if (-dot < minDot) {
  100950. minDot = -dot;
  100951. minDotIndex = 3;
  100952. }
  100953. dot = a6x * nx + a6y * ny + a6z * nz;
  100954. if (dot < minDot) {
  100955. minDot = dot;
  100956. minDotIndex = 4;
  100957. }
  100958. if (-dot < minDot) {
  100959. minDot = -dot;
  100960. minDotIndex = 5;
  100961. }
  100962. //______________________________________________________
  100963. if (minDotIndex == 0) {// x+ face
  100964. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  100965. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  100966. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  100967. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  100968. }
  100969. else if (minDotIndex == 1) {// x- face
  100970. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  100971. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  100972. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  100973. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  100974. }
  100975. else if (minDotIndex == 2) {// y+ face
  100976. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  100977. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  100978. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  100979. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  100980. }
  100981. else if (minDotIndex == 3) {// y- face
  100982. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  100983. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  100984. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  100985. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  100986. }
  100987. else if (minDotIndex == 4) {// z+ face
  100988. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  100989. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  100990. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  100991. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  100992. }
  100993. else if (minDotIndex == 5) {// z- face
  100994. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  100995. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  100996. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  100997. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  100998. }
  100999. }
  101000. // clip vertices
  101001. var numClipVertices;
  101002. var numAddedClipVertices;
  101003. var index;
  101004. var x1;
  101005. var y1;
  101006. var z1;
  101007. var x2;
  101008. var y2;
  101009. var z2;
  101010. this.clipVertices1[0] = q1x;
  101011. this.clipVertices1[1] = q1y;
  101012. this.clipVertices1[2] = q1z;
  101013. this.clipVertices1[3] = q2x;
  101014. this.clipVertices1[4] = q2y;
  101015. this.clipVertices1[5] = q2z;
  101016. this.clipVertices1[6] = q3x;
  101017. this.clipVertices1[7] = q3y;
  101018. this.clipVertices1[8] = q3z;
  101019. this.clipVertices1[9] = q4x;
  101020. this.clipVertices1[10] = q4y;
  101021. this.clipVertices1[11] = q4z;
  101022. numAddedClipVertices = 0;
  101023. x1 = this.clipVertices1[9];
  101024. y1 = this.clipVertices1[10];
  101025. z1 = this.clipVertices1[11];
  101026. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  101027. //var i = 4;
  101028. //while(i--){
  101029. for (var i = 0; i < 4; i++) {
  101030. index = i * 3;
  101031. x2 = this.clipVertices1[index];
  101032. y2 = this.clipVertices1[index + 1];
  101033. z2 = this.clipVertices1[index + 2];
  101034. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  101035. if (dot1 > 0) {
  101036. if (dot2 > 0) {
  101037. index = numAddedClipVertices * 3;
  101038. numAddedClipVertices++;
  101039. this.clipVertices2[index] = x2;
  101040. this.clipVertices2[index + 1] = y2;
  101041. this.clipVertices2[index + 2] = z2;
  101042. } else {
  101043. index = numAddedClipVertices * 3;
  101044. numAddedClipVertices++;
  101045. t = dot1 / (dot1 - dot2);
  101046. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  101047. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  101048. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  101049. }
  101050. } else {
  101051. if (dot2 > 0) {
  101052. index = numAddedClipVertices * 3;
  101053. numAddedClipVertices++;
  101054. t = dot1 / (dot1 - dot2);
  101055. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  101056. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  101057. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  101058. index = numAddedClipVertices * 3;
  101059. numAddedClipVertices++;
  101060. this.clipVertices2[index] = x2;
  101061. this.clipVertices2[index + 1] = y2;
  101062. this.clipVertices2[index + 2] = z2;
  101063. }
  101064. }
  101065. x1 = x2;
  101066. y1 = y2;
  101067. z1 = z2;
  101068. dot1 = dot2;
  101069. }
  101070. numClipVertices = numAddedClipVertices;
  101071. if (numClipVertices == 0) return;
  101072. numAddedClipVertices = 0;
  101073. index = (numClipVertices - 1) * 3;
  101074. x1 = this.clipVertices2[index];
  101075. y1 = this.clipVertices2[index + 1];
  101076. z1 = this.clipVertices2[index + 2];
  101077. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  101078. //i = numClipVertices;
  101079. //while(i--){
  101080. for (i = 0; i < numClipVertices; i++) {
  101081. index = i * 3;
  101082. x2 = this.clipVertices2[index];
  101083. y2 = this.clipVertices2[index + 1];
  101084. z2 = this.clipVertices2[index + 2];
  101085. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  101086. if (dot1 > 0) {
  101087. if (dot2 > 0) {
  101088. index = numAddedClipVertices * 3;
  101089. numAddedClipVertices++;
  101090. this.clipVertices1[index] = x2;
  101091. this.clipVertices1[index + 1] = y2;
  101092. this.clipVertices1[index + 2] = z2;
  101093. } else {
  101094. index = numAddedClipVertices * 3;
  101095. numAddedClipVertices++;
  101096. t = dot1 / (dot1 - dot2);
  101097. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  101098. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  101099. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  101100. }
  101101. } else {
  101102. if (dot2 > 0) {
  101103. index = numAddedClipVertices * 3;
  101104. numAddedClipVertices++;
  101105. t = dot1 / (dot1 - dot2);
  101106. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  101107. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  101108. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  101109. index = numAddedClipVertices * 3;
  101110. numAddedClipVertices++;
  101111. this.clipVertices1[index] = x2;
  101112. this.clipVertices1[index + 1] = y2;
  101113. this.clipVertices1[index + 2] = z2;
  101114. }
  101115. }
  101116. x1 = x2;
  101117. y1 = y2;
  101118. z1 = z2;
  101119. dot1 = dot2;
  101120. }
  101121. numClipVertices = numAddedClipVertices;
  101122. if (numClipVertices == 0) return;
  101123. numAddedClipVertices = 0;
  101124. index = (numClipVertices - 1) * 3;
  101125. x1 = this.clipVertices1[index];
  101126. y1 = this.clipVertices1[index + 1];
  101127. z1 = this.clipVertices1[index + 2];
  101128. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  101129. //i = numClipVertices;
  101130. //while(i--){
  101131. for (i = 0; i < numClipVertices; i++) {
  101132. index = i * 3;
  101133. x2 = this.clipVertices1[index];
  101134. y2 = this.clipVertices1[index + 1];
  101135. z2 = this.clipVertices1[index + 2];
  101136. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  101137. if (dot1 > 0) {
  101138. if (dot2 > 0) {
  101139. index = numAddedClipVertices * 3;
  101140. numAddedClipVertices++;
  101141. this.clipVertices2[index] = x2;
  101142. this.clipVertices2[index + 1] = y2;
  101143. this.clipVertices2[index + 2] = z2;
  101144. } else {
  101145. index = numAddedClipVertices * 3;
  101146. numAddedClipVertices++;
  101147. t = dot1 / (dot1 - dot2);
  101148. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  101149. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  101150. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  101151. }
  101152. } else {
  101153. if (dot2 > 0) {
  101154. index = numAddedClipVertices * 3;
  101155. numAddedClipVertices++;
  101156. t = dot1 / (dot1 - dot2);
  101157. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  101158. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  101159. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  101160. index = numAddedClipVertices * 3;
  101161. numAddedClipVertices++;
  101162. this.clipVertices2[index] = x2;
  101163. this.clipVertices2[index + 1] = y2;
  101164. this.clipVertices2[index + 2] = z2;
  101165. }
  101166. }
  101167. x1 = x2;
  101168. y1 = y2;
  101169. z1 = z2;
  101170. dot1 = dot2;
  101171. }
  101172. numClipVertices = numAddedClipVertices;
  101173. if (numClipVertices == 0) return;
  101174. numAddedClipVertices = 0;
  101175. index = (numClipVertices - 1) * 3;
  101176. x1 = this.clipVertices2[index];
  101177. y1 = this.clipVertices2[index + 1];
  101178. z1 = this.clipVertices2[index + 2];
  101179. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  101180. //i = numClipVertices;
  101181. //while(i--){
  101182. for (i = 0; i < numClipVertices; i++) {
  101183. index = i * 3;
  101184. x2 = this.clipVertices2[index];
  101185. y2 = this.clipVertices2[index + 1];
  101186. z2 = this.clipVertices2[index + 2];
  101187. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  101188. if (dot1 > 0) {
  101189. if (dot2 > 0) {
  101190. index = numAddedClipVertices * 3;
  101191. numAddedClipVertices++;
  101192. this.clipVertices1[index] = x2;
  101193. this.clipVertices1[index + 1] = y2;
  101194. this.clipVertices1[index + 2] = z2;
  101195. } else {
  101196. index = numAddedClipVertices * 3;
  101197. numAddedClipVertices++;
  101198. t = dot1 / (dot1 - dot2);
  101199. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  101200. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  101201. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  101202. }
  101203. } else {
  101204. if (dot2 > 0) {
  101205. index = numAddedClipVertices * 3;
  101206. numAddedClipVertices++;
  101207. t = dot1 / (dot1 - dot2);
  101208. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  101209. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  101210. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  101211. index = numAddedClipVertices * 3;
  101212. numAddedClipVertices++;
  101213. this.clipVertices1[index] = x2;
  101214. this.clipVertices1[index + 1] = y2;
  101215. this.clipVertices1[index + 2] = z2;
  101216. }
  101217. }
  101218. x1 = x2;
  101219. y1 = y2;
  101220. z1 = z2;
  101221. dot1 = dot2;
  101222. }
  101223. numClipVertices = numAddedClipVertices;
  101224. if (swap) {
  101225. var tb = b1;
  101226. b1 = b2;
  101227. b2 = tb;
  101228. }
  101229. if (numClipVertices == 0) return;
  101230. var flipped = b1 != shape1;
  101231. if (numClipVertices > 4) {
  101232. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  101233. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  101234. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  101235. n1x = q1x - x1;
  101236. n1y = q1y - y1;
  101237. n1z = q1z - z1;
  101238. n2x = q2x - x1;
  101239. n2y = q2y - y1;
  101240. n2z = q2z - z1;
  101241. var index1 = 0;
  101242. var index2 = 0;
  101243. var index3 = 0;
  101244. var index4 = 0;
  101245. var maxDot = -this.INF;
  101246. minDot = this.INF;
  101247. //i = numClipVertices;
  101248. //while(i--){
  101249. for (i = 0; i < numClipVertices; i++) {
  101250. this.used[i] = false;
  101251. index = i * 3;
  101252. x1 = this.clipVertices1[index];
  101253. y1 = this.clipVertices1[index + 1];
  101254. z1 = this.clipVertices1[index + 2];
  101255. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  101256. if (dot < minDot) {
  101257. minDot = dot;
  101258. index1 = i;
  101259. }
  101260. if (dot > maxDot) {
  101261. maxDot = dot;
  101262. index3 = i;
  101263. }
  101264. }
  101265. this.used[index1] = true;
  101266. this.used[index3] = true;
  101267. maxDot = -this.INF;
  101268. minDot = this.INF;
  101269. //i = numClipVertices;
  101270. //while(i--){
  101271. for (i = 0; i < numClipVertices; i++) {
  101272. if (this.used[i]) continue;
  101273. index = i * 3;
  101274. x1 = this.clipVertices1[index];
  101275. y1 = this.clipVertices1[index + 1];
  101276. z1 = this.clipVertices1[index + 2];
  101277. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  101278. if (dot < minDot) {
  101279. minDot = dot;
  101280. index2 = i;
  101281. }
  101282. if (dot > maxDot) {
  101283. maxDot = dot;
  101284. index4 = i;
  101285. }
  101286. }
  101287. index = index1 * 3;
  101288. x1 = this.clipVertices1[index];
  101289. y1 = this.clipVertices1[index + 1];
  101290. z1 = this.clipVertices1[index + 2];
  101291. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  101292. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  101293. index = index2 * 3;
  101294. x1 = this.clipVertices1[index];
  101295. y1 = this.clipVertices1[index + 1];
  101296. z1 = this.clipVertices1[index + 2];
  101297. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  101298. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  101299. index = index3 * 3;
  101300. x1 = this.clipVertices1[index];
  101301. y1 = this.clipVertices1[index + 1];
  101302. z1 = this.clipVertices1[index + 2];
  101303. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  101304. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  101305. index = index4 * 3;
  101306. x1 = this.clipVertices1[index];
  101307. y1 = this.clipVertices1[index + 1];
  101308. z1 = this.clipVertices1[index + 2];
  101309. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  101310. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  101311. } else {
  101312. //i = numClipVertices;
  101313. //while(i--){
  101314. for (i = 0; i < numClipVertices; i++) {
  101315. index = i * 3;
  101316. x1 = this.clipVertices1[index];
  101317. y1 = this.clipVertices1[index + 1];
  101318. z1 = this.clipVertices1[index + 2];
  101319. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  101320. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  101321. }
  101322. }
  101323. };
  101324. /**
  101325. * A collision detector which detects collisions between sphere and box.
  101326. * @author saharan
  101327. */
  101328. OIMO.SphereBoxCollisionDetector = function (flip) {
  101329. OIMO.CollisionDetector.call(this);
  101330. this.flip = flip;
  101331. };
  101332. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101333. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  101334. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101335. var s;
  101336. var b;
  101337. if (this.flip) {
  101338. s = (shape2);
  101339. b = (shape1);
  101340. } else {
  101341. s = (shape1);
  101342. b = (shape2);
  101343. }
  101344. var D = b.dimentions;
  101345. var ps = s.position;
  101346. var psx = ps.x;
  101347. var psy = ps.y;
  101348. var psz = ps.z;
  101349. var pb = b.position;
  101350. var pbx = pb.x;
  101351. var pby = pb.y;
  101352. var pbz = pb.z;
  101353. var rad = s.radius;
  101354. var hw = b.halfWidth;
  101355. var hh = b.halfHeight;
  101356. var hd = b.halfDepth;
  101357. var dx = psx - pbx;
  101358. var dy = psy - pby;
  101359. var dz = psz - pbz;
  101360. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  101361. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  101362. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  101363. var cx;
  101364. var cy;
  101365. var cz;
  101366. var len;
  101367. var invLen;
  101368. var overlap = 0;
  101369. if (sx > hw) {
  101370. sx = hw;
  101371. } else if (sx < -hw) {
  101372. sx = -hw;
  101373. } else {
  101374. overlap = 1;
  101375. }
  101376. if (sy > hh) {
  101377. sy = hh;
  101378. } else if (sy < -hh) {
  101379. sy = -hh;
  101380. } else {
  101381. overlap |= 2;
  101382. }
  101383. if (sz > hd) {
  101384. sz = hd;
  101385. } else if (sz < -hd) {
  101386. sz = -hd;
  101387. } else {
  101388. overlap |= 4;
  101389. }
  101390. if (overlap == 7) {
  101391. // center of sphere is in the box
  101392. if (sx < 0) {
  101393. dx = hw + sx;
  101394. } else {
  101395. dx = hw - sx;
  101396. }
  101397. if (sy < 0) {
  101398. dy = hh + sy;
  101399. } else {
  101400. dy = hh - sy;
  101401. }
  101402. if (sz < 0) {
  101403. dz = hd + sz;
  101404. } else {
  101405. dz = hd - sz;
  101406. }
  101407. if (dx < dy) {
  101408. if (dx < dz) {
  101409. len = dx - hw;
  101410. if (sx < 0) {
  101411. sx = -hw;
  101412. dx = D[0];
  101413. dy = D[1];
  101414. dz = D[2];
  101415. } else {
  101416. sx = hw;
  101417. dx = -D[0];
  101418. dy = -D[1];
  101419. dz = -D[2];
  101420. }
  101421. } else {
  101422. len = dz - hd;
  101423. if (sz < 0) {
  101424. sz = -hd;
  101425. dx = D[6];
  101426. dy = D[7];
  101427. dz = D[8];
  101428. } else {
  101429. sz = hd;
  101430. dx = -D[6];
  101431. dy = -D[7];
  101432. dz = -D[8];
  101433. }
  101434. }
  101435. } else {
  101436. if (dy < dz) {
  101437. len = dy - hh;
  101438. if (sy < 0) {
  101439. sy = -hh;
  101440. dx = D[3];
  101441. dy = D[4];
  101442. dz = D[5];
  101443. } else {
  101444. sy = hh;
  101445. dx = -D[3];
  101446. dy = -D[4];
  101447. dz = -D[5];
  101448. }
  101449. } else {
  101450. len = dz - hd;
  101451. if (sz < 0) {
  101452. sz = -hd;
  101453. dx = D[6];
  101454. dy = D[7];
  101455. dz = D[8];
  101456. } else {
  101457. sz = hd;
  101458. dx = -D[6];
  101459. dy = -D[7];
  101460. dz = -D[8];
  101461. }
  101462. }
  101463. }
  101464. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  101465. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  101466. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  101467. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  101468. } else {
  101469. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  101470. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  101471. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  101472. dx = cx - ps.x;
  101473. dy = cy - ps.y;
  101474. dz = cz - ps.z;
  101475. len = dx * dx + dy * dy + dz * dz;
  101476. if (len > 0 && len < rad * rad) {
  101477. len = OIMO.sqrt(len);
  101478. invLen = 1 / len;
  101479. dx *= invLen;
  101480. dy *= invLen;
  101481. dz *= invLen;
  101482. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  101483. }
  101484. }
  101485. };
  101486. /**
  101487. * A collision detector which detects collisions between two spheres.
  101488. * @author saharan
  101489. */
  101490. OIMO.SphereSphereCollisionDetector = function () {
  101491. OIMO.CollisionDetector.call(this);
  101492. };
  101493. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101494. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  101495. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101496. var s1 = shape1;
  101497. var s2 = shape2;
  101498. var p1 = s1.position;
  101499. var p2 = s2.position;
  101500. var dx = p2.x - p1.x;
  101501. var dy = p2.y - p1.y;
  101502. var dz = p2.z - p1.z;
  101503. var len = dx * dx + dy * dy + dz * dz;
  101504. var r1 = s1.radius;
  101505. var r2 = s2.radius;
  101506. var rad = r1 + r2;
  101507. if (len > 0 && len < rad * rad) {
  101508. len = OIMO.sqrt(len);
  101509. var invLen = 1 / len;
  101510. dx *= invLen;
  101511. dy *= invLen;
  101512. dz *= invLen;
  101513. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  101514. }
  101515. };
  101516. OIMO.BoxCylinderCollisionDetector = function (flip) {
  101517. OIMO.CollisionDetector.call(this);
  101518. this.flip = flip;
  101519. };
  101520. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101521. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  101522. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  101523. var t1x;
  101524. var t1y;
  101525. var t1z;
  101526. var t2x;
  101527. var t2y;
  101528. var t2z;
  101529. var sup = new OIMO.Vec3();
  101530. var len;
  101531. var p1x;
  101532. var p1y;
  101533. var p1z;
  101534. var p2x;
  101535. var p2y;
  101536. var p2z;
  101537. var v01x = c1.position.x;
  101538. var v01y = c1.position.y;
  101539. var v01z = c1.position.z;
  101540. var v02x = c2.position.x;
  101541. var v02y = c2.position.y;
  101542. var v02z = c2.position.z;
  101543. var v0x = v02x - v01x;
  101544. var v0y = v02y - v01y;
  101545. var v0z = v02z - v01z;
  101546. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  101547. var nx = -v0x;
  101548. var ny = -v0y;
  101549. var nz = -v0z;
  101550. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101551. var v11x = sup.x;
  101552. var v11y = sup.y;
  101553. var v11z = sup.z;
  101554. this.supportPointC(c2, nx, ny, nz, sup);
  101555. var v12x = sup.x;
  101556. var v12y = sup.y;
  101557. var v12z = sup.z;
  101558. var v1x = v12x - v11x;
  101559. var v1y = v12y - v11y;
  101560. var v1z = v12z - v11z;
  101561. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  101562. return false;
  101563. }
  101564. nx = v1y * v0z - v1z * v0y;
  101565. ny = v1z * v0x - v1x * v0z;
  101566. nz = v1x * v0y - v1y * v0x;
  101567. if (nx * nx + ny * ny + nz * nz == 0) {
  101568. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  101569. sep.normalize(sep);
  101570. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  101571. return true;
  101572. }
  101573. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101574. var v21x = sup.x;
  101575. var v21y = sup.y;
  101576. var v21z = sup.z;
  101577. this.supportPointC(c2, nx, ny, nz, sup);
  101578. var v22x = sup.x;
  101579. var v22y = sup.y;
  101580. var v22z = sup.z;
  101581. var v2x = v22x - v21x;
  101582. var v2y = v22y - v21y;
  101583. var v2z = v22z - v21z;
  101584. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  101585. return false;
  101586. }
  101587. t1x = v1x - v0x;
  101588. t1y = v1y - v0y;
  101589. t1z = v1z - v0z;
  101590. t2x = v2x - v0x;
  101591. t2y = v2y - v0y;
  101592. t2z = v2z - v0z;
  101593. nx = t1y * t2z - t1z * t2y;
  101594. ny = t1z * t2x - t1x * t2z;
  101595. nz = t1x * t2y - t1y * t2x;
  101596. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  101597. t1x = v1x;
  101598. t1y = v1y;
  101599. t1z = v1z;
  101600. v1x = v2x;
  101601. v1y = v2y;
  101602. v1z = v2z;
  101603. v2x = t1x;
  101604. v2y = t1y;
  101605. v2z = t1z;
  101606. t1x = v11x;
  101607. t1y = v11y;
  101608. t1z = v11z;
  101609. v11x = v21x;
  101610. v11y = v21y;
  101611. v11z = v21z;
  101612. v21x = t1x;
  101613. v21y = t1y;
  101614. v21z = t1z;
  101615. t1x = v12x;
  101616. t1y = v12y;
  101617. t1z = v12z;
  101618. v12x = v22x;
  101619. v12y = v22y;
  101620. v12z = v22z;
  101621. v22x = t1x;
  101622. v22y = t1y;
  101623. v22z = t1z;
  101624. nx = -nx;
  101625. ny = -ny;
  101626. nz = -nz;
  101627. }
  101628. var iterations = 0;
  101629. while (true) {
  101630. if (++iterations > 100) {
  101631. return false;
  101632. }
  101633. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101634. var v31x = sup.x;
  101635. var v31y = sup.y;
  101636. var v31z = sup.z;
  101637. this.supportPointC(c2, nx, ny, nz, sup);
  101638. var v32x = sup.x;
  101639. var v32y = sup.y;
  101640. var v32z = sup.z;
  101641. var v3x = v32x - v31x;
  101642. var v3y = v32y - v31y;
  101643. var v3z = v32z - v31z;
  101644. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  101645. return false;
  101646. }
  101647. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  101648. v2x = v3x;
  101649. v2y = v3y;
  101650. v2z = v3z;
  101651. v21x = v31x;
  101652. v21y = v31y;
  101653. v21z = v31z;
  101654. v22x = v32x;
  101655. v22y = v32y;
  101656. v22z = v32z;
  101657. t1x = v1x - v0x;
  101658. t1y = v1y - v0y;
  101659. t1z = v1z - v0z;
  101660. t2x = v3x - v0x;
  101661. t2y = v3y - v0y;
  101662. t2z = v3z - v0z;
  101663. nx = t1y * t2z - t1z * t2y;
  101664. ny = t1z * t2x - t1x * t2z;
  101665. nz = t1x * t2y - t1y * t2x;
  101666. continue;
  101667. }
  101668. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  101669. v1x = v3x;
  101670. v1y = v3y;
  101671. v1z = v3z;
  101672. v11x = v31x;
  101673. v11y = v31y;
  101674. v11z = v31z;
  101675. v12x = v32x;
  101676. v12y = v32y;
  101677. v12z = v32z;
  101678. t1x = v3x - v0x;
  101679. t1y = v3y - v0y;
  101680. t1z = v3z - v0z;
  101681. t2x = v2x - v0x;
  101682. t2y = v2y - v0y;
  101683. t2z = v2z - v0z;
  101684. nx = t1y * t2z - t1z * t2y;
  101685. ny = t1z * t2x - t1x * t2z;
  101686. nz = t1x * t2y - t1y * t2x;
  101687. continue;
  101688. }
  101689. var hit = false;
  101690. while (true) {
  101691. t1x = v2x - v1x;
  101692. t1y = v2y - v1y;
  101693. t1z = v2z - v1z;
  101694. t2x = v3x - v1x;
  101695. t2y = v3y - v1y;
  101696. t2z = v3z - v1z;
  101697. nx = t1y * t2z - t1z * t2y;
  101698. ny = t1z * t2x - t1x * t2z;
  101699. nz = t1x * t2y - t1y * t2x;
  101700. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  101701. nx *= len;
  101702. ny *= len;
  101703. nz *= len;
  101704. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  101705. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  101706. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  101707. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  101708. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  101709. var sum = b0 + b1 + b2 + b3;
  101710. if (sum <= 0) {
  101711. b0 = 0;
  101712. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  101713. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  101714. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  101715. sum = b1 + b2 + b3;
  101716. }
  101717. var inv = 1 / sum;
  101718. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  101719. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  101720. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  101721. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  101722. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  101723. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  101724. hit = true;
  101725. }
  101726. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101727. var v41x = sup.x;
  101728. var v41y = sup.y;
  101729. var v41z = sup.z;
  101730. this.supportPointC(c2, nx, ny, nz, sup);
  101731. var v42x = sup.x;
  101732. var v42y = sup.y;
  101733. var v42z = sup.z;
  101734. var v4x = v42x - v41x;
  101735. var v4y = v42y - v41y;
  101736. var v4z = v42z - v41z;
  101737. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  101738. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  101739. if (hit) {
  101740. sep.init(-nx, -ny, -nz);
  101741. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  101742. dep.x = separation;
  101743. return true;
  101744. }
  101745. return false;
  101746. }
  101747. if (
  101748. (v4y * v1z - v4z * v1y) * v0x +
  101749. (v4z * v1x - v4x * v1z) * v0y +
  101750. (v4x * v1y - v4y * v1x) * v0z < 0
  101751. ) {
  101752. if (
  101753. (v4y * v2z - v4z * v2y) * v0x +
  101754. (v4z * v2x - v4x * v2z) * v0y +
  101755. (v4x * v2y - v4y * v2x) * v0z < 0
  101756. ) {
  101757. v1x = v4x;
  101758. v1y = v4y;
  101759. v1z = v4z;
  101760. v11x = v41x;
  101761. v11y = v41y;
  101762. v11z = v41z;
  101763. v12x = v42x;
  101764. v12y = v42y;
  101765. v12z = v42z;
  101766. } else {
  101767. v3x = v4x;
  101768. v3y = v4y;
  101769. v3z = v4z;
  101770. v31x = v41x;
  101771. v31y = v41y;
  101772. v31z = v41z;
  101773. v32x = v42x;
  101774. v32y = v42y;
  101775. v32z = v42z;
  101776. }
  101777. } else {
  101778. if (
  101779. (v4y * v3z - v4z * v3y) * v0x +
  101780. (v4z * v3x - v4x * v3z) * v0y +
  101781. (v4x * v3y - v4y * v3x) * v0z < 0
  101782. ) {
  101783. v2x = v4x;
  101784. v2y = v4y;
  101785. v2z = v4z;
  101786. v21x = v41x;
  101787. v21y = v41y;
  101788. v21z = v41z;
  101789. v22x = v42x;
  101790. v22y = v42y;
  101791. v22z = v42z;
  101792. } else {
  101793. v1x = v4x;
  101794. v1y = v4y;
  101795. v1z = v4z;
  101796. v11x = v41x;
  101797. v11y = v41y;
  101798. v11z = v41z;
  101799. v12x = v42x;
  101800. v12y = v42y;
  101801. v12z = v42z;
  101802. }
  101803. }
  101804. }
  101805. }
  101806. //return false;
  101807. };
  101808. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  101809. var rot = c.rotation.elements;
  101810. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101811. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101812. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101813. var w = c.halfWidth;
  101814. var h = c.halfHeight;
  101815. var d = c.halfDepth;
  101816. var ox;
  101817. var oy;
  101818. var oz;
  101819. if (ldx < 0) ox = -w;
  101820. else ox = w;
  101821. if (ldy < 0) oy = -h;
  101822. else oy = h;
  101823. if (ldz < 0) oz = -d;
  101824. else oz = d;
  101825. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101826. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101827. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101828. out.init(ldx, ldy, ldz);
  101829. };
  101830. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  101831. var rot = c.rotation.elements;
  101832. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101833. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101834. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101835. var radx = ldx;
  101836. var radz = ldz;
  101837. var len = radx * radx + radz * radz;
  101838. var rad = c.radius;
  101839. var hh = c.halfHeight;
  101840. var ox;
  101841. var oy;
  101842. var oz;
  101843. if (len == 0) {
  101844. if (ldy < 0) {
  101845. ox = rad;
  101846. oy = -hh;
  101847. oz = 0;
  101848. } else {
  101849. ox = rad;
  101850. oy = hh;
  101851. oz = 0;
  101852. }
  101853. } else {
  101854. len = c.radius / OIMO.sqrt(len);
  101855. if (ldy < 0) {
  101856. ox = radx * len;
  101857. oy = -hh;
  101858. oz = radz * len;
  101859. } else {
  101860. ox = radx * len;
  101861. oy = hh;
  101862. oz = radz * len;
  101863. }
  101864. }
  101865. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101866. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101867. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101868. out.init(ldx, ldy, ldz);
  101869. };
  101870. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101871. var b;
  101872. var c;
  101873. if (this.flip) {
  101874. b = shape2;
  101875. c = shape1;
  101876. } else {
  101877. b = shape1;
  101878. c = shape2;
  101879. }
  101880. var sep = new OIMO.Vec3();
  101881. var pos = new OIMO.Vec3();
  101882. var dep = new OIMO.Vec3();
  101883. var co;
  101884. if (!this.getSep(b, c, sep, pos, dep)) return;
  101885. var pbx = b.position.x;
  101886. var pby = b.position.y;
  101887. var pbz = b.position.z;
  101888. var pcx = c.position.x;
  101889. var pcy = c.position.y;
  101890. var pcz = c.position.z;
  101891. var bw = b.halfWidth;
  101892. var bh = b.halfHeight;
  101893. var bd = b.halfDepth;
  101894. var ch = c.halfHeight;
  101895. var r = c.radius;
  101896. var D = b.dimentions;
  101897. var nwx = D[0];//b.normalDirectionWidth.x;
  101898. var nwy = D[1];//b.normalDirectionWidth.y;
  101899. var nwz = D[2];//b.normalDirectionWidth.z;
  101900. var nhx = D[3];//b.normalDirectionHeight.x;
  101901. var nhy = D[4];//b.normalDirectionHeight.y;
  101902. var nhz = D[5];//b.normalDirectionHeight.z;
  101903. var ndx = D[6];//b.normalDirectionDepth.x;
  101904. var ndy = D[7];//b.normalDirectionDepth.y;
  101905. var ndz = D[8];//b.normalDirectionDepth.z;
  101906. var dwx = D[9];//b.halfDirectionWidth.x;
  101907. var dwy = D[10];//b.halfDirectionWidth.y;
  101908. var dwz = D[11];//b.halfDirectionWidth.z;
  101909. var dhx = D[12];//b.halfDirectionHeight.x;
  101910. var dhy = D[13];//b.halfDirectionHeight.y;
  101911. var dhz = D[14];//b.halfDirectionHeight.z;
  101912. var ddx = D[15];//b.halfDirectionDepth.x;
  101913. var ddy = D[16];//b.halfDirectionDepth.y;
  101914. var ddz = D[17];//b.halfDirectionDepth.z;
  101915. var ncx = c.normalDirection.x;
  101916. var ncy = c.normalDirection.y;
  101917. var ncz = c.normalDirection.z;
  101918. var dcx = c.halfDirection.x;
  101919. var dcy = c.halfDirection.y;
  101920. var dcz = c.halfDirection.z;
  101921. var nx = sep.x;
  101922. var ny = sep.y;
  101923. var nz = sep.z;
  101924. var dotw = nx * nwx + ny * nwy + nz * nwz;
  101925. var doth = nx * nhx + ny * nhy + nz * nhz;
  101926. var dotd = nx * ndx + ny * ndy + nz * ndz;
  101927. var dotc = nx * ncx + ny * ncy + nz * ncz;
  101928. var right1 = dotw > 0;
  101929. var right2 = doth > 0;
  101930. var right3 = dotd > 0;
  101931. var right4 = dotc > 0;
  101932. if (!right1) dotw = -dotw;
  101933. if (!right2) doth = -doth;
  101934. if (!right3) dotd = -dotd;
  101935. if (!right4) dotc = -dotc;
  101936. var state = 0;
  101937. if (dotc > 0.999) {
  101938. if (dotw > 0.999) {
  101939. if (dotw > dotc) state = 1;
  101940. else state = 4;
  101941. } else if (doth > 0.999) {
  101942. if (doth > dotc) state = 2;
  101943. else state = 4;
  101944. } else if (dotd > 0.999) {
  101945. if (dotd > dotc) state = 3;
  101946. else state = 4;
  101947. } else state = 4;
  101948. } else {
  101949. if (dotw > 0.999) state = 1;
  101950. else if (doth > 0.999) state = 2;
  101951. else if (dotd > 0.999) state = 3;
  101952. }
  101953. var cbx;
  101954. var cby;
  101955. var cbz;
  101956. var ccx;
  101957. var ccy;
  101958. var ccz;
  101959. var r00;
  101960. var r01;
  101961. var r02;
  101962. var r10;
  101963. var r11;
  101964. var r12;
  101965. var r20;
  101966. var r21;
  101967. var r22;
  101968. var px;
  101969. var py;
  101970. var pz;
  101971. var pd;
  101972. var dot;
  101973. var len;
  101974. var tx;
  101975. var ty;
  101976. var tz;
  101977. var td;
  101978. var dx;
  101979. var dy;
  101980. var dz;
  101981. var d1x;
  101982. var d1y;
  101983. var d1z;
  101984. var d2x;
  101985. var d2y;
  101986. var d2z;
  101987. var sx;
  101988. var sy;
  101989. var sz;
  101990. var sd;
  101991. var ex;
  101992. var ey;
  101993. var ez;
  101994. var ed;
  101995. var dot1;
  101996. var dot2;
  101997. var t1;
  101998. var t2;
  101999. var dir1x;
  102000. var dir1y;
  102001. var dir1z;
  102002. var dir2x;
  102003. var dir2y;
  102004. var dir2z;
  102005. var dir1l;
  102006. var dir2l;
  102007. if (state == 0) {
  102008. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  102009. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  102010. } else if (state == 4) {
  102011. if (right4) {
  102012. ccx = pcx - dcx;
  102013. ccy = pcy - dcy;
  102014. ccz = pcz - dcz;
  102015. nx = -ncx;
  102016. ny = -ncy;
  102017. nz = -ncz;
  102018. } else {
  102019. ccx = pcx + dcx;
  102020. ccy = pcy + dcy;
  102021. ccz = pcz + dcz;
  102022. nx = ncx;
  102023. ny = ncy;
  102024. nz = ncz;
  102025. }
  102026. var v1x;
  102027. var v1y;
  102028. var v1z;
  102029. var v2x;
  102030. var v2y;
  102031. var v2z;
  102032. var v3x;
  102033. var v3y;
  102034. var v3z;
  102035. var v4x;
  102036. var v4y;
  102037. var v4z;
  102038. dot = 1;
  102039. state = 0;
  102040. dot1 = nwx * nx + nwy * ny + nwz * nz;
  102041. if (dot1 < dot) {
  102042. dot = dot1;
  102043. state = 0;
  102044. }
  102045. if (-dot1 < dot) {
  102046. dot = -dot1;
  102047. state = 1;
  102048. }
  102049. dot1 = nhx * nx + nhy * ny + nhz * nz;
  102050. if (dot1 < dot) {
  102051. dot = dot1;
  102052. state = 2;
  102053. }
  102054. if (-dot1 < dot) {
  102055. dot = -dot1;
  102056. state = 3;
  102057. }
  102058. dot1 = ndx * nx + ndy * ny + ndz * nz;
  102059. if (dot1 < dot) {
  102060. dot = dot1;
  102061. state = 4;
  102062. }
  102063. if (-dot1 < dot) {
  102064. dot = -dot1;
  102065. state = 5;
  102066. }
  102067. var v = b.elements;
  102068. switch (state) {
  102069. case 0:
  102070. //v=b.vertex1;
  102071. v1x = v[0];//v.x;
  102072. v1y = v[1];//v.y;
  102073. v1z = v[2];//v.z;
  102074. //v=b.vertex3;
  102075. v2x = v[6];//v.x;
  102076. v2y = v[7];//v.y;
  102077. v2z = v[8];//v.z;
  102078. //v=b.vertex4;
  102079. v3x = v[9];//v.x;
  102080. v3y = v[10];//v.y;
  102081. v3z = v[11];//v.z;
  102082. //v=b.vertex2;
  102083. v4x = v[3];//v.x;
  102084. v4y = v[4];//v.y;
  102085. v4z = v[5];//v.z;
  102086. break;
  102087. case 1:
  102088. //v=b.vertex6;
  102089. v1x = v[15];//v.x;
  102090. v1y = v[16];//v.y;
  102091. v1z = v[17];//v.z;
  102092. //v=b.vertex8;
  102093. v2x = v[21];//v.x;
  102094. v2y = v[22];//v.y;
  102095. v2z = v[23];//v.z;
  102096. //v=b.vertex7;
  102097. v3x = v[18];//v.x;
  102098. v3y = v[19];//v.y;
  102099. v3z = v[20];//v.z;
  102100. //v=b.vertex5;
  102101. v4x = v[12];//v.x;
  102102. v4y = v[13];//v.y;
  102103. v4z = v[14];//v.z;
  102104. break;
  102105. case 2:
  102106. //v=b.vertex5;
  102107. v1x = v[12];//v.x;
  102108. v1y = v[13];//v.y;
  102109. v1z = v[14];//v.z;
  102110. //v=b.vertex1;
  102111. v2x = v[0];//v.x;
  102112. v2y = v[1];//v.y;
  102113. v2z = v[2];//v.z;
  102114. //v=b.vertex2;
  102115. v3x = v[3];//v.x;
  102116. v3y = v[4];//v.y;
  102117. v3z = v[5];//v.z;
  102118. //v=b.vertex6;
  102119. v4x = v[15];//v.x;
  102120. v4y = v[16];//v.y;
  102121. v4z = v[17];//v.z;
  102122. break;
  102123. case 3:
  102124. //v=b.vertex8;
  102125. v1x = v[21];//v.x;
  102126. v1y = v[22];//v.y;
  102127. v1z = v[23];//v.z;
  102128. //v=b.vertex4;
  102129. v2x = v[9];//v.x;
  102130. v2y = v[10];//v.y;
  102131. v2z = v[11];//v.z;
  102132. //v=b.vertex3;
  102133. v3x = v[6];//v.x;
  102134. v3y = v[7];//v.y;
  102135. v3z = v[8];//v.z;
  102136. //v=b.vertex7;
  102137. v4x = v[18];//v.x;
  102138. v4y = v[19];//v.y;
  102139. v4z = v[20];//v.z;
  102140. break;
  102141. case 4:
  102142. //v=b.vertex5;
  102143. v1x = v[12];//v.x;
  102144. v1y = v[13];//v.y;
  102145. v1z = v[14];//v.z;
  102146. //v=b.vertex7;
  102147. v2x = v[18];//v.x;
  102148. v2y = v[19];//v.y;
  102149. v2z = v[20];//v.z;
  102150. //v=b.vertex3;
  102151. v3x = v[6];//v.x;
  102152. v3y = v[7];//v.y;
  102153. v3z = v[8];//v.z;
  102154. //v=b.vertex1;
  102155. v4x = v[0];//v.x;
  102156. v4y = v[1];//v.y;
  102157. v4z = v[2];//v.z;
  102158. break;
  102159. case 5:
  102160. //v=b.vertex2;
  102161. v1x = v[3];//v.x;
  102162. v1y = v[4];//v.y;
  102163. v1z = v[5];//v.z;
  102164. //v=b.vertex4;
  102165. v2x = v[9];//v.x;
  102166. v2y = v[10];//v.y;
  102167. v2z = v[11];//v.z;
  102168. //v=b.vertex8;
  102169. v3x = v[21];//v.x;
  102170. v3y = v[22];//v.y;
  102171. v3z = v[23];//v.z;
  102172. //v=b.vertex6;
  102173. v4x = v[15];//v.x;
  102174. v4y = v[16];//v.y;
  102175. v4z = v[17];//v.z;
  102176. break;
  102177. }
  102178. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  102179. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  102180. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  102181. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  102182. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  102183. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  102184. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  102185. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  102186. } else {
  102187. switch (state) {
  102188. case 1:
  102189. if (right1) {
  102190. cbx = pbx + dwx;
  102191. cby = pby + dwy;
  102192. cbz = pbz + dwz;
  102193. nx = nwx;
  102194. ny = nwy;
  102195. nz = nwz;
  102196. } else {
  102197. cbx = pbx - dwx;
  102198. cby = pby - dwy;
  102199. cbz = pbz - dwz;
  102200. nx = -nwx;
  102201. ny = -nwy;
  102202. nz = -nwz;
  102203. }
  102204. dir1x = nhx;
  102205. dir1y = nhy;
  102206. dir1z = nhz;
  102207. dir1l = bh;
  102208. dir2x = ndx;
  102209. dir2y = ndy;
  102210. dir2z = ndz;
  102211. dir2l = bd;
  102212. break;
  102213. case 2:
  102214. if (right2) {
  102215. cbx = pbx + dhx;
  102216. cby = pby + dhy;
  102217. cbz = pbz + dhz;
  102218. nx = nhx;
  102219. ny = nhy;
  102220. nz = nhz;
  102221. } else {
  102222. cbx = pbx - dhx;
  102223. cby = pby - dhy;
  102224. cbz = pbz - dhz;
  102225. nx = -nhx;
  102226. ny = -nhy;
  102227. nz = -nhz;
  102228. }
  102229. dir1x = nwx;
  102230. dir1y = nwy;
  102231. dir1z = nwz;
  102232. dir1l = bw;
  102233. dir2x = ndx;
  102234. dir2y = ndy;
  102235. dir2z = ndz;
  102236. dir2l = bd;
  102237. break;
  102238. case 3:
  102239. if (right3) {
  102240. cbx = pbx + ddx;
  102241. cby = pby + ddy;
  102242. cbz = pbz + ddz;
  102243. nx = ndx;
  102244. ny = ndy;
  102245. nz = ndz;
  102246. } else {
  102247. cbx = pbx - ddx;
  102248. cby = pby - ddy;
  102249. cbz = pbz - ddz;
  102250. nx = -ndx;
  102251. ny = -ndy;
  102252. nz = -ndz;
  102253. }
  102254. dir1x = nwx;
  102255. dir1y = nwy;
  102256. dir1z = nwz;
  102257. dir1l = bw;
  102258. dir2x = nhx;
  102259. dir2y = nhy;
  102260. dir2z = nhz;
  102261. dir2l = bh;
  102262. break;
  102263. }
  102264. dot = nx * ncx + ny * ncy + nz * ncz;
  102265. if (dot < 0) len = ch;
  102266. else len = -ch;
  102267. ccx = pcx + len * ncx;
  102268. ccy = pcy + len * ncy;
  102269. ccz = pcz + len * ncz;
  102270. if (dotc >= 0.999999) {
  102271. tx = -ny;
  102272. ty = nz;
  102273. tz = nx;
  102274. } else {
  102275. tx = nx;
  102276. ty = ny;
  102277. tz = nz;
  102278. }
  102279. len = tx * ncx + ty * ncy + tz * ncz;
  102280. dx = len * ncx - tx;
  102281. dy = len * ncy - ty;
  102282. dz = len * ncz - tz;
  102283. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  102284. if (len == 0) return;
  102285. len = r / len;
  102286. dx *= len;
  102287. dy *= len;
  102288. dz *= len;
  102289. tx = ccx + dx;
  102290. ty = ccy + dy;
  102291. tz = ccz + dz;
  102292. if (dot < -0.96 || dot > 0.96) {
  102293. r00 = ncx * ncx * 1.5 - 0.5;
  102294. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  102295. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  102296. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  102297. r11 = ncy * ncy * 1.5 - 0.5;
  102298. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  102299. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  102300. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  102301. r22 = ncz * ncz * 1.5 - 0.5;
  102302. px = tx;
  102303. py = ty;
  102304. pz = tz;
  102305. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  102306. tx = px - pd * nx - cbx;
  102307. ty = py - pd * ny - cby;
  102308. tz = pz - pd * nz - cbz;
  102309. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  102310. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  102311. if (sd < -dir1l) sd = -dir1l;
  102312. else if (sd > dir1l) sd = dir1l;
  102313. if (ed < -dir2l) ed = -dir2l;
  102314. else if (ed > dir2l) ed = dir2l;
  102315. tx = sd * dir1x + ed * dir2x;
  102316. ty = sd * dir1y + ed * dir2y;
  102317. tz = sd * dir1z + ed * dir2z;
  102318. px = cbx + tx;
  102319. py = cby + ty;
  102320. pz = cbz + tz;
  102321. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  102322. px = dx * r00 + dy * r01 + dz * r02;
  102323. py = dx * r10 + dy * r11 + dz * r12;
  102324. pz = dx * r20 + dy * r21 + dz * r22;
  102325. px = (dx = px) + ccx;
  102326. py = (dy = py) + ccy;
  102327. pz = (dz = pz) + ccz;
  102328. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  102329. if (pd <= 0) {
  102330. tx = px - pd * nx - cbx;
  102331. ty = py - pd * ny - cby;
  102332. tz = pz - pd * nz - cbz;
  102333. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  102334. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  102335. if (sd < -dir1l) sd = -dir1l;
  102336. else if (sd > dir1l) sd = dir1l;
  102337. if (ed < -dir2l) ed = -dir2l;
  102338. else if (ed > dir2l) ed = dir2l;
  102339. tx = sd * dir1x + ed * dir2x;
  102340. ty = sd * dir1y + ed * dir2y;
  102341. tz = sd * dir1z + ed * dir2z;
  102342. px = cbx + tx;
  102343. py = cby + ty;
  102344. pz = cbz + tz;
  102345. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  102346. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  102347. }
  102348. px = dx * r00 + dy * r01 + dz * r02;
  102349. py = dx * r10 + dy * r11 + dz * r12;
  102350. pz = dx * r20 + dy * r21 + dz * r22;
  102351. px = (dx = px) + ccx;
  102352. py = (dy = py) + ccy;
  102353. pz = (dz = pz) + ccz;
  102354. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  102355. if (pd <= 0) {
  102356. tx = px - pd * nx - cbx;
  102357. ty = py - pd * ny - cby;
  102358. tz = pz - pd * nz - cbz;
  102359. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  102360. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  102361. if (sd < -dir1l) sd = -dir1l;
  102362. else if (sd > dir1l) sd = dir1l;
  102363. if (ed < -dir2l) ed = -dir2l;
  102364. else if (ed > dir2l) ed = dir2l;
  102365. tx = sd * dir1x + ed * dir2x;
  102366. ty = sd * dir1y + ed * dir2y;
  102367. tz = sd * dir1z + ed * dir2z;
  102368. px = cbx + tx;
  102369. py = cby + ty;
  102370. pz = cbz + tz;
  102371. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  102372. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  102373. }
  102374. } else {
  102375. sx = tx;
  102376. sy = ty;
  102377. sz = tz;
  102378. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  102379. sx -= sd * nx;
  102380. sy -= sd * ny;
  102381. sz -= sd * nz;
  102382. if (dot > 0) {
  102383. ex = tx + dcx * 2;
  102384. ey = ty + dcy * 2;
  102385. ez = tz + dcz * 2;
  102386. } else {
  102387. ex = tx - dcx * 2;
  102388. ey = ty - dcy * 2;
  102389. ez = tz - dcz * 2;
  102390. }
  102391. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  102392. ex -= ed * nx;
  102393. ey -= ed * ny;
  102394. ez -= ed * nz;
  102395. d1x = sx - cbx;
  102396. d1y = sy - cby;
  102397. d1z = sz - cbz;
  102398. d2x = ex - cbx;
  102399. d2y = ey - cby;
  102400. d2z = ez - cbz;
  102401. tx = ex - sx;
  102402. ty = ey - sy;
  102403. tz = ez - sz;
  102404. td = ed - sd;
  102405. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  102406. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  102407. dot1 = dotw - dir1l;
  102408. dot2 = doth - dir1l;
  102409. if (dot1 > 0) {
  102410. if (dot2 > 0) return;
  102411. t1 = dot1 / (dot1 - dot2);
  102412. sx = sx + tx * t1;
  102413. sy = sy + ty * t1;
  102414. sz = sz + tz * t1;
  102415. sd = sd + td * t1;
  102416. d1x = sx - cbx;
  102417. d1y = sy - cby;
  102418. d1z = sz - cbz;
  102419. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  102420. tx = ex - sx;
  102421. ty = ey - sy;
  102422. tz = ez - sz;
  102423. td = ed - sd;
  102424. } else if (dot2 > 0) {
  102425. t1 = dot1 / (dot1 - dot2);
  102426. ex = sx + tx * t1;
  102427. ey = sy + ty * t1;
  102428. ez = sz + tz * t1;
  102429. ed = sd + td * t1;
  102430. d2x = ex - cbx;
  102431. d2y = ey - cby;
  102432. d2z = ez - cbz;
  102433. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  102434. tx = ex - sx;
  102435. ty = ey - sy;
  102436. tz = ez - sz;
  102437. td = ed - sd;
  102438. }
  102439. dot1 = dotw + dir1l;
  102440. dot2 = doth + dir1l;
  102441. if (dot1 < 0) {
  102442. if (dot2 < 0) return;
  102443. t1 = dot1 / (dot1 - dot2);
  102444. sx = sx + tx * t1;
  102445. sy = sy + ty * t1;
  102446. sz = sz + tz * t1;
  102447. sd = sd + td * t1;
  102448. d1x = sx - cbx;
  102449. d1y = sy - cby;
  102450. d1z = sz - cbz;
  102451. tx = ex - sx;
  102452. ty = ey - sy;
  102453. tz = ez - sz;
  102454. td = ed - sd;
  102455. } else if (dot2 < 0) {
  102456. t1 = dot1 / (dot1 - dot2);
  102457. ex = sx + tx * t1;
  102458. ey = sy + ty * t1;
  102459. ez = sz + tz * t1;
  102460. ed = sd + td * t1;
  102461. d2x = ex - cbx;
  102462. d2y = ey - cby;
  102463. d2z = ez - cbz;
  102464. tx = ex - sx;
  102465. ty = ey - sy;
  102466. tz = ez - sz;
  102467. td = ed - sd;
  102468. }
  102469. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  102470. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  102471. dot1 = dotw - dir2l;
  102472. dot2 = doth - dir2l;
  102473. if (dot1 > 0) {
  102474. if (dot2 > 0) return;
  102475. t1 = dot1 / (dot1 - dot2);
  102476. sx = sx + tx * t1;
  102477. sy = sy + ty * t1;
  102478. sz = sz + tz * t1;
  102479. sd = sd + td * t1;
  102480. d1x = sx - cbx;
  102481. d1y = sy - cby;
  102482. d1z = sz - cbz;
  102483. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  102484. tx = ex - sx;
  102485. ty = ey - sy;
  102486. tz = ez - sz;
  102487. td = ed - sd;
  102488. } else if (dot2 > 0) {
  102489. t1 = dot1 / (dot1 - dot2);
  102490. ex = sx + tx * t1;
  102491. ey = sy + ty * t1;
  102492. ez = sz + tz * t1;
  102493. ed = sd + td * t1;
  102494. d2x = ex - cbx;
  102495. d2y = ey - cby;
  102496. d2z = ez - cbz;
  102497. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  102498. tx = ex - sx;
  102499. ty = ey - sy;
  102500. tz = ez - sz;
  102501. td = ed - sd;
  102502. }
  102503. dot1 = dotw + dir2l;
  102504. dot2 = doth + dir2l;
  102505. if (dot1 < 0) {
  102506. if (dot2 < 0) return;
  102507. t1 = dot1 / (dot1 - dot2);
  102508. sx = sx + tx * t1;
  102509. sy = sy + ty * t1;
  102510. sz = sz + tz * t1;
  102511. sd = sd + td * t1;
  102512. } else if (dot2 < 0) {
  102513. t1 = dot1 / (dot1 - dot2);
  102514. ex = sx + tx * t1;
  102515. ey = sy + ty * t1;
  102516. ez = sz + tz * t1;
  102517. ed = sd + td * t1;
  102518. }
  102519. if (sd < 0) {
  102520. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  102521. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  102522. }
  102523. if (ed < 0) {
  102524. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  102525. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  102526. }
  102527. }
  102528. }
  102529. };
  102530. OIMO.CylinderCylinderCollisionDetector = function () {
  102531. OIMO.CollisionDetector.call(this);
  102532. };
  102533. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102534. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  102535. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  102536. var t1x;
  102537. var t1y;
  102538. var t1z;
  102539. var t2x;
  102540. var t2y;
  102541. var t2z;
  102542. var sup = new OIMO.Vec3();
  102543. var len;
  102544. var p1x;
  102545. var p1y;
  102546. var p1z;
  102547. var p2x;
  102548. var p2y;
  102549. var p2z;
  102550. var v01x = c1.position.x;
  102551. var v01y = c1.position.y;
  102552. var v01z = c1.position.z;
  102553. var v02x = c2.position.x;
  102554. var v02y = c2.position.y;
  102555. var v02z = c2.position.z;
  102556. var v0x = v02x - v01x;
  102557. var v0y = v02y - v01y;
  102558. var v0z = v02z - v01z;
  102559. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  102560. var nx = -v0x;
  102561. var ny = -v0y;
  102562. var nz = -v0z;
  102563. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102564. var v11x = sup.x;
  102565. var v11y = sup.y;
  102566. var v11z = sup.z;
  102567. this.supportPoint(c2, nx, ny, nz, sup);
  102568. var v12x = sup.x;
  102569. var v12y = sup.y;
  102570. var v12z = sup.z;
  102571. var v1x = v12x - v11x;
  102572. var v1y = v12y - v11y;
  102573. var v1z = v12z - v11z;
  102574. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  102575. return false;
  102576. }
  102577. nx = v1y * v0z - v1z * v0y;
  102578. ny = v1z * v0x - v1x * v0z;
  102579. nz = v1x * v0y - v1y * v0x;
  102580. if (nx * nx + ny * ny + nz * nz == 0) {
  102581. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  102582. sep.normalize(sep);
  102583. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  102584. return true;
  102585. }
  102586. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102587. var v21x = sup.x;
  102588. var v21y = sup.y;
  102589. var v21z = sup.z;
  102590. this.supportPoint(c2, nx, ny, nz, sup);
  102591. var v22x = sup.x;
  102592. var v22y = sup.y;
  102593. var v22z = sup.z;
  102594. var v2x = v22x - v21x;
  102595. var v2y = v22y - v21y;
  102596. var v2z = v22z - v21z;
  102597. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  102598. return false;
  102599. }
  102600. t1x = v1x - v0x;
  102601. t1y = v1y - v0y;
  102602. t1z = v1z - v0z;
  102603. t2x = v2x - v0x;
  102604. t2y = v2y - v0y;
  102605. t2z = v2z - v0z;
  102606. nx = t1y * t2z - t1z * t2y;
  102607. ny = t1z * t2x - t1x * t2z;
  102608. nz = t1x * t2y - t1y * t2x;
  102609. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  102610. t1x = v1x;
  102611. t1y = v1y;
  102612. t1z = v1z;
  102613. v1x = v2x;
  102614. v1y = v2y;
  102615. v1z = v2z;
  102616. v2x = t1x;
  102617. v2y = t1y;
  102618. v2z = t1z;
  102619. t1x = v11x;
  102620. t1y = v11y;
  102621. t1z = v11z;
  102622. v11x = v21x;
  102623. v11y = v21y;
  102624. v11z = v21z;
  102625. v21x = t1x;
  102626. v21y = t1y;
  102627. v21z = t1z;
  102628. t1x = v12x;
  102629. t1y = v12y;
  102630. t1z = v12z;
  102631. v12x = v22x;
  102632. v12y = v22y;
  102633. v12z = v22z;
  102634. v22x = t1x;
  102635. v22y = t1y;
  102636. v22z = t1z;
  102637. nx = -nx;
  102638. ny = -ny;
  102639. nz = -nz;
  102640. }
  102641. var iterations = 0;
  102642. while (true) {
  102643. if (++iterations > 100) {
  102644. return false;
  102645. }
  102646. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102647. var v31x = sup.x;
  102648. var v31y = sup.y;
  102649. var v31z = sup.z;
  102650. this.supportPoint(c2, nx, ny, nz, sup);
  102651. var v32x = sup.x;
  102652. var v32y = sup.y;
  102653. var v32z = sup.z;
  102654. var v3x = v32x - v31x;
  102655. var v3y = v32y - v31y;
  102656. var v3z = v32z - v31z;
  102657. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  102658. return false;
  102659. }
  102660. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  102661. v2x = v3x;
  102662. v2y = v3y;
  102663. v2z = v3z;
  102664. v21x = v31x;
  102665. v21y = v31y;
  102666. v21z = v31z;
  102667. v22x = v32x;
  102668. v22y = v32y;
  102669. v22z = v32z;
  102670. t1x = v1x - v0x;
  102671. t1y = v1y - v0y;
  102672. t1z = v1z - v0z;
  102673. t2x = v3x - v0x;
  102674. t2y = v3y - v0y;
  102675. t2z = v3z - v0z;
  102676. nx = t1y * t2z - t1z * t2y;
  102677. ny = t1z * t2x - t1x * t2z;
  102678. nz = t1x * t2y - t1y * t2x;
  102679. continue;
  102680. }
  102681. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  102682. v1x = v3x;
  102683. v1y = v3y;
  102684. v1z = v3z;
  102685. v11x = v31x;
  102686. v11y = v31y;
  102687. v11z = v31z;
  102688. v12x = v32x;
  102689. v12y = v32y;
  102690. v12z = v32z;
  102691. t1x = v3x - v0x;
  102692. t1y = v3y - v0y;
  102693. t1z = v3z - v0z;
  102694. t2x = v2x - v0x;
  102695. t2y = v2y - v0y;
  102696. t2z = v2z - v0z;
  102697. nx = t1y * t2z - t1z * t2y;
  102698. ny = t1z * t2x - t1x * t2z;
  102699. nz = t1x * t2y - t1y * t2x;
  102700. continue;
  102701. }
  102702. var hit = false;
  102703. while (true) {
  102704. t1x = v2x - v1x;
  102705. t1y = v2y - v1y;
  102706. t1z = v2z - v1z;
  102707. t2x = v3x - v1x;
  102708. t2y = v3y - v1y;
  102709. t2z = v3z - v1z;
  102710. nx = t1y * t2z - t1z * t2y;
  102711. ny = t1z * t2x - t1x * t2z;
  102712. nz = t1x * t2y - t1y * t2x;
  102713. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  102714. nx *= len;
  102715. ny *= len;
  102716. nz *= len;
  102717. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  102718. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  102719. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  102720. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  102721. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  102722. var sum = b0 + b1 + b2 + b3;
  102723. if (sum <= 0) {
  102724. b0 = 0;
  102725. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  102726. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  102727. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  102728. sum = b1 + b2 + b3;
  102729. }
  102730. var inv = 1 / sum;
  102731. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  102732. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  102733. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  102734. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  102735. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  102736. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  102737. hit = true;
  102738. }
  102739. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102740. var v41x = sup.x;
  102741. var v41y = sup.y;
  102742. var v41z = sup.z;
  102743. this.supportPoint(c2, nx, ny, nz, sup);
  102744. var v42x = sup.x;
  102745. var v42y = sup.y;
  102746. var v42z = sup.z;
  102747. var v4x = v42x - v41x;
  102748. var v4y = v42y - v41y;
  102749. var v4z = v42z - v41z;
  102750. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  102751. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  102752. if (hit) {
  102753. sep.init(-nx, -ny, -nz);
  102754. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  102755. dep.x = separation;
  102756. return true;
  102757. }
  102758. return false;
  102759. }
  102760. if (
  102761. (v4y * v1z - v4z * v1y) * v0x +
  102762. (v4z * v1x - v4x * v1z) * v0y +
  102763. (v4x * v1y - v4y * v1x) * v0z < 0
  102764. ) {
  102765. if (
  102766. (v4y * v2z - v4z * v2y) * v0x +
  102767. (v4z * v2x - v4x * v2z) * v0y +
  102768. (v4x * v2y - v4y * v2x) * v0z < 0
  102769. ) {
  102770. v1x = v4x;
  102771. v1y = v4y;
  102772. v1z = v4z;
  102773. v11x = v41x;
  102774. v11y = v41y;
  102775. v11z = v41z;
  102776. v12x = v42x;
  102777. v12y = v42y;
  102778. v12z = v42z;
  102779. } else {
  102780. v3x = v4x;
  102781. v3y = v4y;
  102782. v3z = v4z;
  102783. v31x = v41x;
  102784. v31y = v41y;
  102785. v31z = v41z;
  102786. v32x = v42x;
  102787. v32y = v42y;
  102788. v32z = v42z;
  102789. }
  102790. } else {
  102791. if (
  102792. (v4y * v3z - v4z * v3y) * v0x +
  102793. (v4z * v3x - v4x * v3z) * v0y +
  102794. (v4x * v3y - v4y * v3x) * v0z < 0
  102795. ) {
  102796. v2x = v4x;
  102797. v2y = v4y;
  102798. v2z = v4z;
  102799. v21x = v41x;
  102800. v21y = v41y;
  102801. v21z = v41z;
  102802. v22x = v42x;
  102803. v22y = v42y;
  102804. v22z = v42z;
  102805. } else {
  102806. v1x = v4x;
  102807. v1y = v4y;
  102808. v1z = v4z;
  102809. v11x = v41x;
  102810. v11y = v41y;
  102811. v11z = v41z;
  102812. v12x = v42x;
  102813. v12y = v42y;
  102814. v12z = v42z;
  102815. }
  102816. }
  102817. }
  102818. }
  102819. //return false;
  102820. };
  102821. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  102822. var rot = c.rotation.elements;
  102823. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  102824. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  102825. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  102826. var radx = ldx;
  102827. var radz = ldz;
  102828. var len = radx * radx + radz * radz;
  102829. var rad = c.radius;
  102830. var hh = c.halfHeight;
  102831. var ox;
  102832. var oy;
  102833. var oz;
  102834. if (len == 0) {
  102835. if (ldy < 0) {
  102836. ox = rad;
  102837. oy = -hh;
  102838. oz = 0;
  102839. } else {
  102840. ox = rad;
  102841. oy = hh;
  102842. oz = 0;
  102843. }
  102844. } else {
  102845. len = c.radius / OIMO.sqrt(len);
  102846. if (ldy < 0) {
  102847. ox = radx * len;
  102848. oy = -hh;
  102849. oz = radz * len;
  102850. } else {
  102851. ox = radx * len;
  102852. oy = hh;
  102853. oz = radz * len;
  102854. }
  102855. }
  102856. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  102857. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  102858. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  102859. out.init(ldx, ldy, ldz);
  102860. };
  102861. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  102862. var c1;
  102863. var c2;
  102864. if (shape1.id < shape2.id) {
  102865. c1 = shape1;
  102866. c2 = shape2;
  102867. } else {
  102868. c1 = shape2;
  102869. c2 = shape1;
  102870. }
  102871. var p1 = c1.position;
  102872. var p2 = c2.position;
  102873. var p1x = p1.x;
  102874. var p1y = p1.y;
  102875. var p1z = p1.z;
  102876. var p2x = p2.x;
  102877. var p2y = p2.y;
  102878. var p2z = p2.z;
  102879. var h1 = c1.halfHeight;
  102880. var h2 = c2.halfHeight;
  102881. var n1 = c1.normalDirection;
  102882. var n2 = c2.normalDirection;
  102883. var d1 = c1.halfDirection;
  102884. var d2 = c2.halfDirection;
  102885. var r1 = c1.radius;
  102886. var r2 = c2.radius;
  102887. var n1x = n1.x;
  102888. var n1y = n1.y;
  102889. var n1z = n1.z;
  102890. var n2x = n2.x;
  102891. var n2y = n2.y;
  102892. var n2z = n2.z;
  102893. var d1x = d1.x;
  102894. var d1y = d1.y;
  102895. var d1z = d1.z;
  102896. var d2x = d2.x;
  102897. var d2y = d2.y;
  102898. var d2z = d2.z;
  102899. var dx = p1x - p2x;
  102900. var dy = p1y - p2y;
  102901. var dz = p1z - p2z;
  102902. var len;
  102903. var len1;
  102904. var len2;
  102905. var c;
  102906. var c1x;
  102907. var c1y;
  102908. var c1z;
  102909. var c2x;
  102910. var c2y;
  102911. var c2z;
  102912. var tx;
  102913. var ty;
  102914. var tz;
  102915. var sx;
  102916. var sy;
  102917. var sz;
  102918. var ex;
  102919. var ey;
  102920. var ez;
  102921. var depth1;
  102922. var depth2;
  102923. var dot;
  102924. var t1;
  102925. var t2;
  102926. var sep = new OIMO.Vec3();
  102927. var pos = new OIMO.Vec3();
  102928. var dep = new OIMO.Vec3();
  102929. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  102930. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  102931. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  102932. var right1 = dot1 > 0;
  102933. var right2 = dot2 > 0;
  102934. if (!right1) dot1 = -dot1;
  102935. if (!right2) dot2 = -dot2;
  102936. var state = 0;
  102937. if (dot1 > 0.999 || dot2 > 0.999) {
  102938. if (dot1 > dot2) state = 1;
  102939. else state = 2;
  102940. }
  102941. var nx;
  102942. var ny;
  102943. var nz;
  102944. var depth = dep.x;
  102945. var r00;
  102946. var r01;
  102947. var r02;
  102948. var r10;
  102949. var r11;
  102950. var r12;
  102951. var r20;
  102952. var r21;
  102953. var r22;
  102954. var px;
  102955. var py;
  102956. var pz;
  102957. var pd;
  102958. var a;
  102959. var b;
  102960. var e;
  102961. var f;
  102962. nx = sep.x;
  102963. ny = sep.y;
  102964. nz = sep.z;
  102965. switch (state) {
  102966. case 0:
  102967. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  102968. break;
  102969. case 1:
  102970. if (right1) {
  102971. c1x = p1x + d1x;
  102972. c1y = p1y + d1y;
  102973. c1z = p1z + d1z;
  102974. nx = n1x;
  102975. ny = n1y;
  102976. nz = n1z;
  102977. } else {
  102978. c1x = p1x - d1x;
  102979. c1y = p1y - d1y;
  102980. c1z = p1z - d1z;
  102981. nx = -n1x;
  102982. ny = -n1y;
  102983. nz = -n1z;
  102984. }
  102985. dot = nx * n2x + ny * n2y + nz * n2z;
  102986. if (dot < 0) len = h2;
  102987. else len = -h2;
  102988. c2x = p2x + len * n2x;
  102989. c2y = p2y + len * n2y;
  102990. c2z = p2z + len * n2z;
  102991. if (dot2 >= 0.999999) {
  102992. tx = -ny;
  102993. ty = nz;
  102994. tz = nx;
  102995. } else {
  102996. tx = nx;
  102997. ty = ny;
  102998. tz = nz;
  102999. }
  103000. len = tx * n2x + ty * n2y + tz * n2z;
  103001. dx = len * n2x - tx;
  103002. dy = len * n2y - ty;
  103003. dz = len * n2z - tz;
  103004. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  103005. if (len == 0) break;
  103006. len = r2 / len;
  103007. dx *= len;
  103008. dy *= len;
  103009. dz *= len;
  103010. tx = c2x + dx;
  103011. ty = c2y + dy;
  103012. tz = c2z + dz;
  103013. if (dot < -0.96 || dot > 0.96) {
  103014. r00 = n2x * n2x * 1.5 - 0.5;
  103015. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  103016. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  103017. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  103018. r11 = n2y * n2y * 1.5 - 0.5;
  103019. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  103020. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  103021. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  103022. r22 = n2z * n2z * 1.5 - 0.5;
  103023. px = tx;
  103024. py = ty;
  103025. pz = tz;
  103026. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  103027. tx = px - pd * nx - c1x;
  103028. ty = py - pd * ny - c1y;
  103029. tz = pz - pd * nz - c1z;
  103030. len = tx * tx + ty * ty + tz * tz;
  103031. if (len > r1 * r1) {
  103032. len = r1 / OIMO.sqrt(len);
  103033. tx *= len;
  103034. ty *= len;
  103035. tz *= len;
  103036. }
  103037. px = c1x + tx;
  103038. py = c1y + ty;
  103039. pz = c1z + tz;
  103040. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  103041. px = dx * r00 + dy * r01 + dz * r02;
  103042. py = dx * r10 + dy * r11 + dz * r12;
  103043. pz = dx * r20 + dy * r21 + dz * r22;
  103044. px = (dx = px) + c2x;
  103045. py = (dy = py) + c2y;
  103046. pz = (dz = pz) + c2z;
  103047. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  103048. if (pd <= 0) {
  103049. tx = px - pd * nx - c1x;
  103050. ty = py - pd * ny - c1y;
  103051. tz = pz - pd * nz - c1z;
  103052. len = tx * tx + ty * ty + tz * tz;
  103053. if (len > r1 * r1) {
  103054. len = r1 / OIMO.sqrt(len);
  103055. tx *= len;
  103056. ty *= len;
  103057. tz *= len;
  103058. }
  103059. px = c1x + tx;
  103060. py = c1y + ty;
  103061. pz = c1z + tz;
  103062. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  103063. }
  103064. px = dx * r00 + dy * r01 + dz * r02;
  103065. py = dx * r10 + dy * r11 + dz * r12;
  103066. pz = dx * r20 + dy * r21 + dz * r22;
  103067. px = (dx = px) + c2x;
  103068. py = (dy = py) + c2y;
  103069. pz = (dz = pz) + c2z;
  103070. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  103071. if (pd <= 0) {
  103072. tx = px - pd * nx - c1x;
  103073. ty = py - pd * ny - c1y;
  103074. tz = pz - pd * nz - c1z;
  103075. len = tx * tx + ty * ty + tz * tz;
  103076. if (len > r1 * r1) {
  103077. len = r1 / OIMO.sqrt(len);
  103078. tx *= len;
  103079. ty *= len;
  103080. tz *= len;
  103081. }
  103082. px = c1x + tx;
  103083. py = c1y + ty;
  103084. pz = c1z + tz;
  103085. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  103086. }
  103087. } else {
  103088. sx = tx;
  103089. sy = ty;
  103090. sz = tz;
  103091. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  103092. sx -= depth1 * nx;
  103093. sy -= depth1 * ny;
  103094. sz -= depth1 * nz;
  103095. if (dot > 0) {
  103096. ex = tx + n2x * h2 * 2;
  103097. ey = ty + n2y * h2 * 2;
  103098. ez = tz + n2z * h2 * 2;
  103099. } else {
  103100. ex = tx - n2x * h2 * 2;
  103101. ey = ty - n2y * h2 * 2;
  103102. ez = tz - n2z * h2 * 2;
  103103. }
  103104. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  103105. ex -= depth2 * nx;
  103106. ey -= depth2 * ny;
  103107. ez -= depth2 * nz;
  103108. dx = c1x - sx;
  103109. dy = c1y - sy;
  103110. dz = c1z - sz;
  103111. tx = ex - sx;
  103112. ty = ey - sy;
  103113. tz = ez - sz;
  103114. a = dx * dx + dy * dy + dz * dz;
  103115. b = dx * tx + dy * ty + dz * tz;
  103116. e = tx * tx + ty * ty + tz * tz;
  103117. f = b * b - e * (a - r1 * r1);
  103118. if (f < 0) break;
  103119. f = OIMO.sqrt(f);
  103120. t1 = (b + f) / e;
  103121. t2 = (b - f) / e;
  103122. if (t2 < t1) {
  103123. len = t1;
  103124. t1 = t2;
  103125. t2 = len;
  103126. }
  103127. if (t2 > 1) t2 = 1;
  103128. if (t1 < 0) t1 = 0;
  103129. tx = sx + (ex - sx) * t1;
  103130. ty = sy + (ey - sy) * t1;
  103131. tz = sz + (ez - sz) * t1;
  103132. ex = sx + (ex - sx) * t2;
  103133. ey = sy + (ey - sy) * t2;
  103134. ez = sz + (ez - sz) * t2;
  103135. sx = tx;
  103136. sy = ty;
  103137. sz = tz;
  103138. len = depth1 + (depth2 - depth1) * t1;
  103139. depth2 = depth1 + (depth2 - depth1) * t2;
  103140. depth1 = len;
  103141. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  103142. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  103143. }
  103144. break;
  103145. case 2:
  103146. if (right2) {
  103147. c2x = p2x - d2x;
  103148. c2y = p2y - d2y;
  103149. c2z = p2z - d2z;
  103150. nx = -n2x;
  103151. ny = -n2y;
  103152. nz = -n2z;
  103153. } else {
  103154. c2x = p2x + d2x;
  103155. c2y = p2y + d2y;
  103156. c2z = p2z + d2z;
  103157. nx = n2x;
  103158. ny = n2y;
  103159. nz = n2z;
  103160. }
  103161. dot = nx * n1x + ny * n1y + nz * n1z;
  103162. if (dot < 0) len = h1;
  103163. else len = -h1;
  103164. c1x = p1x + len * n1x;
  103165. c1y = p1y + len * n1y;
  103166. c1z = p1z + len * n1z;
  103167. if (dot1 >= 0.999999) {
  103168. tx = -ny;
  103169. ty = nz;
  103170. tz = nx;
  103171. } else {
  103172. tx = nx;
  103173. ty = ny;
  103174. tz = nz;
  103175. }
  103176. len = tx * n1x + ty * n1y + tz * n1z;
  103177. dx = len * n1x - tx;
  103178. dy = len * n1y - ty;
  103179. dz = len * n1z - tz;
  103180. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  103181. if (len == 0) break;
  103182. len = r1 / len;
  103183. dx *= len;
  103184. dy *= len;
  103185. dz *= len;
  103186. tx = c1x + dx;
  103187. ty = c1y + dy;
  103188. tz = c1z + dz;
  103189. if (dot < -0.96 || dot > 0.96) {
  103190. r00 = n1x * n1x * 1.5 - 0.5;
  103191. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  103192. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  103193. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  103194. r11 = n1y * n1y * 1.5 - 0.5;
  103195. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  103196. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  103197. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  103198. r22 = n1z * n1z * 1.5 - 0.5;
  103199. px = tx;
  103200. py = ty;
  103201. pz = tz;
  103202. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  103203. tx = px - pd * nx - c2x;
  103204. ty = py - pd * ny - c2y;
  103205. tz = pz - pd * nz - c2z;
  103206. len = tx * tx + ty * ty + tz * tz;
  103207. if (len > r2 * r2) {
  103208. len = r2 / OIMO.sqrt(len);
  103209. tx *= len;
  103210. ty *= len;
  103211. tz *= len;
  103212. }
  103213. px = c2x + tx;
  103214. py = c2y + ty;
  103215. pz = c2z + tz;
  103216. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  103217. px = dx * r00 + dy * r01 + dz * r02;
  103218. py = dx * r10 + dy * r11 + dz * r12;
  103219. pz = dx * r20 + dy * r21 + dz * r22;
  103220. px = (dx = px) + c1x;
  103221. py = (dy = py) + c1y;
  103222. pz = (dz = pz) + c1z;
  103223. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  103224. if (pd <= 0) {
  103225. tx = px - pd * nx - c2x;
  103226. ty = py - pd * ny - c2y;
  103227. tz = pz - pd * nz - c2z;
  103228. len = tx * tx + ty * ty + tz * tz;
  103229. if (len > r2 * r2) {
  103230. len = r2 / OIMO.sqrt(len);
  103231. tx *= len;
  103232. ty *= len;
  103233. tz *= len;
  103234. }
  103235. px = c2x + tx;
  103236. py = c2y + ty;
  103237. pz = c2z + tz;
  103238. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  103239. }
  103240. px = dx * r00 + dy * r01 + dz * r02;
  103241. py = dx * r10 + dy * r11 + dz * r12;
  103242. pz = dx * r20 + dy * r21 + dz * r22;
  103243. px = (dx = px) + c1x;
  103244. py = (dy = py) + c1y;
  103245. pz = (dz = pz) + c1z;
  103246. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  103247. if (pd <= 0) {
  103248. tx = px - pd * nx - c2x;
  103249. ty = py - pd * ny - c2y;
  103250. tz = pz - pd * nz - c2z;
  103251. len = tx * tx + ty * ty + tz * tz;
  103252. if (len > r2 * r2) {
  103253. len = r2 / OIMO.sqrt(len);
  103254. tx *= len;
  103255. ty *= len;
  103256. tz *= len;
  103257. }
  103258. px = c2x + tx;
  103259. py = c2y + ty;
  103260. pz = c2z + tz;
  103261. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  103262. }
  103263. } else {
  103264. sx = tx;
  103265. sy = ty;
  103266. sz = tz;
  103267. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  103268. sx -= depth1 * nx;
  103269. sy -= depth1 * ny;
  103270. sz -= depth1 * nz;
  103271. if (dot > 0) {
  103272. ex = tx + n1x * h1 * 2;
  103273. ey = ty + n1y * h1 * 2;
  103274. ez = tz + n1z * h1 * 2;
  103275. } else {
  103276. ex = tx - n1x * h1 * 2;
  103277. ey = ty - n1y * h1 * 2;
  103278. ez = tz - n1z * h1 * 2;
  103279. }
  103280. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  103281. ex -= depth2 * nx;
  103282. ey -= depth2 * ny;
  103283. ez -= depth2 * nz;
  103284. dx = c2x - sx;
  103285. dy = c2y - sy;
  103286. dz = c2z - sz;
  103287. tx = ex - sx;
  103288. ty = ey - sy;
  103289. tz = ez - sz;
  103290. a = dx * dx + dy * dy + dz * dz;
  103291. b = dx * tx + dy * ty + dz * tz;
  103292. e = tx * tx + ty * ty + tz * tz;
  103293. f = b * b - e * (a - r2 * r2);
  103294. if (f < 0) break;
  103295. f = OIMO.sqrt(f);
  103296. t1 = (b + f) / e;
  103297. t2 = (b - f) / e;
  103298. if (t2 < t1) {
  103299. len = t1;
  103300. t1 = t2;
  103301. t2 = len;
  103302. }
  103303. if (t2 > 1) t2 = 1;
  103304. if (t1 < 0) t1 = 0;
  103305. tx = sx + (ex - sx) * t1;
  103306. ty = sy + (ey - sy) * t1;
  103307. tz = sz + (ez - sz) * t1;
  103308. ex = sx + (ex - sx) * t2;
  103309. ey = sy + (ey - sy) * t2;
  103310. ez = sz + (ez - sz) * t2;
  103311. sx = tx;
  103312. sy = ty;
  103313. sz = tz;
  103314. len = depth1 + (depth2 - depth1) * t1;
  103315. depth2 = depth1 + (depth2 - depth1) * t2;
  103316. depth1 = len;
  103317. if (depth1 < 0) {
  103318. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  103319. }
  103320. if (depth2 < 0) {
  103321. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  103322. }
  103323. }
  103324. break;
  103325. }
  103326. };
  103327. OIMO.SphereCylinderCollisionDetector = function (flip) {
  103328. OIMO.CollisionDetector.call(this);
  103329. this.flip = flip;
  103330. };
  103331. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  103332. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  103333. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  103334. var s;
  103335. var c;
  103336. if (this.flip) {
  103337. s = shape2;
  103338. c = shape1;
  103339. } else {
  103340. s = shape1;
  103341. c = shape2;
  103342. }
  103343. var ps = s.position;
  103344. var psx = ps.x;
  103345. var psy = ps.y;
  103346. var psz = ps.z;
  103347. var pc = c.position;
  103348. var pcx = pc.x;
  103349. var pcy = pc.y;
  103350. var pcz = pc.z;
  103351. var dirx = c.normalDirection.x;
  103352. var diry = c.normalDirection.y;
  103353. var dirz = c.normalDirection.z;
  103354. var rads = s.radius;
  103355. var radc = c.radius;
  103356. var rad2 = rads + radc;
  103357. var halfh = c.halfHeight;
  103358. var dx = psx - pcx;
  103359. var dy = psy - pcy;
  103360. var dz = psz - pcz;
  103361. var dot = dx * dirx + dy * diry + dz * dirz;
  103362. if (dot < -halfh - rads || dot > halfh + rads) return;
  103363. var cx = pcx + dot * dirx;
  103364. var cy = pcy + dot * diry;
  103365. var cz = pcz + dot * dirz;
  103366. var d2x = psx - cx;
  103367. var d2y = psy - cy;
  103368. var d2z = psz - cz;
  103369. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  103370. if (len > rad2 * rad2) return;
  103371. if (len > radc * radc) {
  103372. len = radc / OIMO.sqrt(len);
  103373. d2x *= len;
  103374. d2y *= len;
  103375. d2z *= len;
  103376. }
  103377. if (dot < -halfh) dot = -halfh;
  103378. else if (dot > halfh) dot = halfh;
  103379. cx = pcx + dot * dirx + d2x;
  103380. cy = pcy + dot * diry + d2y;
  103381. cz = pcz + dot * dirz + d2z;
  103382. dx = cx - psx;
  103383. dy = cy - psy;
  103384. dz = cz - psz;
  103385. len = dx * dx + dy * dy + dz * dz;
  103386. var invLen;
  103387. if (len > 0 && len < rads * rads) {
  103388. len = OIMO.sqrt(len);
  103389. invLen = 1 / len;
  103390. dx *= invLen;
  103391. dy *= invLen;
  103392. dz *= invLen;
  103393. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  103394. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  103395. }
  103396. };
  103397. /**
  103398. * Class for checking collisions between 2 tetras,
  103399. * a shape that is made with 4 vertices and 4 faces
  103400. * arranged in triangles. With this algorigthm, soft
  103401. * body physics are possible and easier to implement.
  103402. * @author xprogram
  103403. */
  103404. OIMO.TetraTetraCollisionDetector = function () {
  103405. OIMO.CollisionDetector.call(this);
  103406. };
  103407. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  103408. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  103409. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  103410. /*
  103411. * What we are doing:
  103412. * Each tetra is represented by four 3D triangles. The only
  103413. * quick way of finding if another tetra is within the other
  103414. * tetra is to see if a single vertex is within the triangles
  103415. * of the other tetra. So, for example, a tetra is represented
  103416. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  103417. * There is another tetra with a vertex A which was detected for
  103418. * collision by the broadphase. Now, if the point A is between ALL
  103419. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  103420. * is valid and we can pass point A to the manifold. Since the only
  103421. * points on the tetra are the 4 vertices, collision detection is
  103422. * not so complex. However, it can be time-consuming because we
  103423. * need to split the 3D triangles into three 2D triangles each for
  103424. * collision detection.
  103425. */
  103426. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  103427. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  103428. // fs is undeclared
  103429. var fs = fs1;
  103430. for (i = 0; i < 4; i++) {
  103431. vec = vs1[i];
  103432. for (j = 0; j < 4; j++) {
  103433. j1 = vs2[fs[i].a];
  103434. j2 = vs2[fs[i].b];
  103435. j3 = vs2[fs[i].c];
  103436. if (
  103437. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  103438. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  103439. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  103440. )
  103441. ts++;
  103442. if (ts === 4) // Only add point if it is inside all 4 triangles
  103443. manifold.addPoint(vec);
  103444. }
  103445. }
  103446. };
  103447. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  103448. function tricheck(p, p0, p1, p2) {
  103449. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  103450. var sg = A < 0 ? -1 : 1;
  103451. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  103452. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  103453. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  103454. }
  103455. function pt(x, y) { return { x: x, y: y }; }
  103456. /**
  103457. * An axis-aligned bounding box.
  103458. * @author saharan
  103459. * @author lo-th
  103460. */
  103461. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  103462. this.elements = new OIMO_ARRAY_TYPE(6);
  103463. var te = this.elements;
  103464. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  103465. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  103466. };
  103467. OIMO.AABB.prototype = {
  103468. constructor: OIMO.AABB,
  103469. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  103470. var te = this.elements;
  103471. te[0] = minX; te[3] = maxX;
  103472. te[1] = minY; te[4] = maxY;
  103473. te[2] = minZ; te[5] = maxZ;
  103474. return this;
  103475. },
  103476. intersectTest: function (aabb) {
  103477. var te = this.elements;
  103478. var ue = aabb.elements;
  103479. 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];
  103480. },
  103481. intersectTestTwo: function (aabb) {
  103482. var te = this.elements;
  103483. var ue = aabb.elements;
  103484. 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];
  103485. },
  103486. clone: function () {
  103487. return new this.constructor().fromArray(this.elements);
  103488. },
  103489. copy: function (aabb, margin) {
  103490. var m = margin || 0;
  103491. var me = aabb.elements;
  103492. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  103493. return this;
  103494. },
  103495. fromArray: function (array) {
  103496. this.elements.set(array);
  103497. return this;
  103498. },
  103499. // Set this AABB to the combined AABB of aabb1 and aabb2.
  103500. combine: function (aabb1, aabb2) {
  103501. var a = aabb1.elements;
  103502. var b = aabb2.elements;
  103503. var te = this.elements;
  103504. te[0] = a[0] < b[0] ? a[0] : b[0];
  103505. te[1] = a[1] < b[1] ? a[1] : b[1];
  103506. te[2] = a[2] < b[2] ? a[2] : b[2];
  103507. te[3] = a[3] > b[3] ? a[3] : b[3];
  103508. te[4] = a[4] > b[4] ? a[4] : b[4];
  103509. te[5] = a[5] > b[5] ? a[5] : b[5];
  103510. return this;
  103511. },
  103512. // Get the surface area.
  103513. surfaceArea: function () {
  103514. var te = this.elements;
  103515. var a = te[3] - te[0];
  103516. var h = te[4] - te[1];
  103517. var d = te[5] - te[2];
  103518. return 2 * (a * (h + d) + h * d);
  103519. },
  103520. // Get whether the AABB intersects with the point or not.
  103521. intersectsWithPoint: function (x, y, z) {
  103522. var te = this.elements;
  103523. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  103524. },
  103525. /**
  103526. * Set the AABB from an array
  103527. * of vertices. From THREE.
  103528. * @author mrdoob
  103529. * @author xprogram
  103530. */
  103531. setFromPoints: function (arr) {
  103532. this.makeEmpty();
  103533. for (var i = 0; i < arr.length; i++) {
  103534. this.expandByPoint(arr[i]);
  103535. }
  103536. },
  103537. makeEmpty: function () {
  103538. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  103539. },
  103540. expandByPoint: function (pt) {
  103541. var te = this.elements;
  103542. this.set(
  103543. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  103544. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  103545. );
  103546. }
  103547. };
  103548. /**
  103549. * A proxy is used for broad-phase collecting pairs that can be colliding.
  103550. */
  103551. OIMO.Proxy = function (shape) {
  103552. // The parent shape.
  103553. this.shape = shape;
  103554. // The axis-aligned bounding box.
  103555. this.aabb = shape.aabb;
  103556. };
  103557. OIMO.Proxy.prototype = {
  103558. constructor: OIMO.Proxy,
  103559. // Update the proxy.
  103560. update: function () {
  103561. OIMO.Error("Proxy", "Inheritance error.");
  103562. }
  103563. };
  103564. /**
  103565. * A basic implementation of proxies.
  103566. * @author saharan
  103567. */
  103568. OIMO.BasicProxy = function (shape) {
  103569. OIMO.Proxy.call(this, shape);
  103570. this.id = OIMO.proxyID++;
  103571. };
  103572. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103573. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  103574. OIMO.BasicProxy.prototype.update = function () {
  103575. };
  103576. /**
  103577. * The broad-phase is used for collecting all possible pairs for collision.
  103578. */
  103579. OIMO.BroadPhase = function () {
  103580. this.types = OIMO.BR_NULL;
  103581. this.numPairChecks = 0;
  103582. this.numPairs = 0;
  103583. this.pairs = [];
  103584. };
  103585. OIMO.BroadPhase.prototype = {
  103586. constructor: OIMO.BroadPhase,
  103587. /**
  103588. * Create a new proxy.
  103589. * @param shape
  103590. * @return
  103591. */
  103592. createProxy: function (shape) {
  103593. OIMO.Error("BroadPhase", "Inheritance error.");
  103594. },
  103595. /**
  103596. * Add the proxy into the broad-phase.
  103597. * @param proxy
  103598. */
  103599. addProxy: function (proxy) {
  103600. OIMO.Error("BroadPhase", "Inheritance error.");
  103601. },
  103602. /**
  103603. * Remove the proxy from the broad-phase.
  103604. * @param proxy
  103605. */
  103606. removeProxy: function (proxy) {
  103607. OIMO.Error("BroadPhase", "Inheritance error.");
  103608. },
  103609. /**
  103610. * Returns whether the pair is available or not.
  103611. * @param s1
  103612. * @param s2
  103613. * @return
  103614. */
  103615. isAvailablePair: function (s1, s2) {
  103616. var b1 = s1.parent;
  103617. var b2 = s2.parent;
  103618. if (b1 == b2 || // same parents
  103619. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  103620. (s1.belongsTo & s2.collidesWith) == 0 ||
  103621. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  103622. ) { return false; }
  103623. var js;
  103624. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  103625. else js = b2.jointLink;
  103626. while (js !== null) {
  103627. var joint = js.joint;
  103628. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  103629. js = js.next;
  103630. }
  103631. return true;
  103632. },
  103633. // Detect overlapping pairs.
  103634. detectPairs: function () {
  103635. // clear old
  103636. this.pairs = [];
  103637. this.numPairs = 0;
  103638. this.numPairChecks = 0;
  103639. this.collectPairs();
  103640. },
  103641. collectPairs: function () {
  103642. OIMO.Error("BroadPhase", "Inheritance error.");
  103643. },
  103644. addPair: function (s1, s2) {
  103645. var pair = new OIMO.Pair(s1, s2);
  103646. this.pairs.push(pair);
  103647. this.numPairs++;
  103648. }
  103649. };
  103650. /**
  103651. * A broad-phase algorithm with brute-force search.
  103652. * This always checks for all possible pairs.
  103653. */
  103654. OIMO.BruteForceBroadPhase = function () {
  103655. OIMO.BroadPhase.call(this);
  103656. this.types = OIMO.BR_BRUTE_FORCE;;
  103657. //this.numProxies=0;
  103658. ///this.maxProxies = 256;
  103659. this.proxies = [];
  103660. //this.proxies.length = 256;
  103661. };
  103662. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103663. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  103664. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  103665. return new OIMO.BasicProxy(shape);
  103666. };
  103667. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  103668. /*if(this.numProxies==this.maxProxies){
  103669. //this.maxProxies<<=1;
  103670. this.maxProxies*=2;
  103671. var newProxies=[];
  103672. newProxies.length = this.maxProxies;
  103673. var i = this.numProxies;
  103674. while(i--){
  103675. //for(var i=0, l=this.numProxies;i<l;i++){
  103676. newProxies[i]=this.proxies[i];
  103677. }
  103678. this.proxies=newProxies;
  103679. }*/
  103680. //this.proxies[this.numProxies++] = proxy;
  103681. this.proxies.push(proxy);
  103682. //this.numProxies++;
  103683. };
  103684. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  103685. var n = this.proxies.indexOf(proxy);
  103686. if (n > -1) {
  103687. this.proxies.splice(n, 1);
  103688. //this.numProxies--;
  103689. }
  103690. /*var i = this.numProxies;
  103691. while(i--){
  103692. //for(var i=0, l=this.numProxies;i<l;i++){
  103693. if(this.proxies[i] == proxy){
  103694. this.proxies[i] = this.proxies[--this.numProxies];
  103695. this.proxies[this.numProxies] = null;
  103696. return;
  103697. }
  103698. }*/
  103699. };
  103700. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  103701. var i = 0, j, p1, p2;
  103702. var px = this.proxies;
  103703. var l = px.length;//this.numProxies;
  103704. //var ar1 = [];
  103705. //var ar2 = [];
  103706. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  103707. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  103708. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  103709. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  103710. this.numPairChecks = l * (l - 1) >> 1;
  103711. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  103712. while (i < l) {
  103713. p1 = px[i++];
  103714. j = i + 1;
  103715. while (j < l) {
  103716. p2 = px[j++];
  103717. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  103718. this.addPair(p1.shape, p2.shape);
  103719. }
  103720. }
  103721. };
  103722. /**
  103723. * A pair of shapes that may collide.
  103724. * @author saharan
  103725. */
  103726. OIMO.Pair = function (s1, s2) {
  103727. // The first shape.
  103728. this.shape1 = s1 || null;
  103729. // The second shape.
  103730. this.shape2 = s2 || null;
  103731. };
  103732. /**
  103733. * A projection axis for sweep and prune broad-phase.
  103734. * @author saharan
  103735. */
  103736. OIMO.SAPAxis = function () {
  103737. this.numElements = 0;
  103738. this.bufferSize = 256;
  103739. this.elements = [];
  103740. this.elements.length = this.bufferSize;
  103741. this.stack = new OIMO_ARRAY_TYPE(64);
  103742. };
  103743. OIMO.SAPAxis.prototype = {
  103744. constructor: OIMO.SAPAxis,
  103745. addElements: function (min, max) {
  103746. if (this.numElements + 2 >= this.bufferSize) {
  103747. //this.bufferSize<<=1;
  103748. this.bufferSize *= 2;
  103749. var newElements = [];
  103750. var i = this.numElements;
  103751. while (i--) {
  103752. //for(var i=0, l=this.numElements; i<l; i++){
  103753. newElements[i] = this.elements[i];
  103754. }
  103755. }
  103756. this.elements[this.numElements++] = min;
  103757. this.elements[this.numElements++] = max;
  103758. },
  103759. removeElements: function (min, max) {
  103760. var minIndex = -1;
  103761. var maxIndex = -1;
  103762. for (var i = 0, l = this.numElements; i < l; i++) {
  103763. var e = this.elements[i];
  103764. if (e == min || e == max) {
  103765. if (minIndex == -1) {
  103766. minIndex = i;
  103767. } else {
  103768. maxIndex = i;
  103769. break;
  103770. }
  103771. }
  103772. }
  103773. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  103774. this.elements[i - 1] = this.elements[i];
  103775. }
  103776. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  103777. this.elements[i - 2] = this.elements[i];
  103778. }
  103779. this.elements[--this.numElements] = null;
  103780. this.elements[--this.numElements] = null;
  103781. },
  103782. sort: function () {
  103783. var count = 0;
  103784. var threshold = 1;
  103785. while ((this.numElements >> threshold) != 0) threshold++;
  103786. threshold = threshold * this.numElements >> 2;
  103787. count = 0;
  103788. var giveup = false;
  103789. var elements = this.elements;
  103790. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  103791. var tmp = elements[i];
  103792. var pivot = tmp.value;
  103793. var tmp2 = elements[i - 1];
  103794. if (tmp2.value > pivot) {
  103795. var j = i;
  103796. do {
  103797. elements[j] = tmp2;
  103798. if (--j == 0) break;
  103799. tmp2 = elements[j - 1];
  103800. } while (tmp2.value > pivot);
  103801. elements[j] = tmp;
  103802. count += i - j;
  103803. if (count > threshold) {
  103804. giveup = true; // stop and use quick sort
  103805. break;
  103806. }
  103807. }
  103808. }
  103809. if (!giveup) return;
  103810. count = 2; var stack = this.stack;
  103811. stack[0] = 0;
  103812. stack[1] = this.numElements - 1;
  103813. while (count > 0) {
  103814. var right = stack[--count];
  103815. var left = stack[--count];
  103816. var diff = right - left;
  103817. if (diff > 16) { // quick sort
  103818. //var mid=left+(diff>>1);
  103819. var mid = left + (OIMO.floor(diff * 0.5));
  103820. tmp = elements[mid];
  103821. elements[mid] = elements[right];
  103822. elements[right] = tmp;
  103823. pivot = tmp.value;
  103824. i = left - 1;
  103825. j = right;
  103826. while (true) {
  103827. var ei;
  103828. var ej;
  103829. do { ei = elements[++i]; } while (ei.value < pivot);
  103830. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  103831. if (i >= j) break;
  103832. elements[i] = ej;
  103833. elements[j] = ei;
  103834. }
  103835. elements[right] = elements[i];
  103836. elements[i] = tmp;
  103837. if (i - left > right - i) {
  103838. stack[count++] = left;
  103839. stack[count++] = i - 1;
  103840. stack[count++] = i + 1;
  103841. stack[count++] = right;
  103842. } else {
  103843. stack[count++] = i + 1;
  103844. stack[count++] = right;
  103845. stack[count++] = left;
  103846. stack[count++] = i - 1;
  103847. }
  103848. } else {
  103849. for (i = left + 1; i <= right; i++) {
  103850. tmp = elements[i];
  103851. pivot = tmp.value;
  103852. tmp2 = elements[i - 1];
  103853. if (tmp2.value > pivot) {
  103854. j = i;
  103855. do {
  103856. elements[j] = tmp2;
  103857. if (--j == 0) break;
  103858. tmp2 = elements[j - 1];
  103859. } while (tmp2.value > pivot);
  103860. elements[j] = tmp;
  103861. }
  103862. }
  103863. }
  103864. }
  103865. },
  103866. calculateTestCount: function () {
  103867. var num = 1;
  103868. var sum = 0;
  103869. for (var i = 1, l = this.numElements; i < l; i++) {
  103870. if (this.elements[i].max) {
  103871. num--;
  103872. } else {
  103873. sum += num;
  103874. num++;
  103875. }
  103876. }
  103877. return sum;
  103878. }
  103879. }
  103880. /**
  103881. * A broad-phase collision detection algorithm using sweep and prune.
  103882. * @author saharan
  103883. * @author lo-th
  103884. */
  103885. OIMO.SAPBroadPhase = function () {
  103886. OIMO.BroadPhase.call(this);
  103887. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  103888. this.numElementsD = 0;
  103889. this.numElementsS = 0;
  103890. // dynamic proxies
  103891. this.axesD = [
  103892. new OIMO.SAPAxis(),
  103893. new OIMO.SAPAxis(),
  103894. new OIMO.SAPAxis()
  103895. ];
  103896. // static or sleeping proxies
  103897. this.axesS = [
  103898. new OIMO.SAPAxis(),
  103899. new OIMO.SAPAxis(),
  103900. new OIMO.SAPAxis()
  103901. ];
  103902. this.index1 = 0;
  103903. this.index2 = 1;
  103904. };
  103905. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103906. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  103907. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  103908. return new OIMO.SAPProxy(this, shape);
  103909. };
  103910. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  103911. var p = proxy;
  103912. if (p.isDynamic()) {
  103913. this.axesD[0].addElements(p.min[0], p.max[0]);
  103914. this.axesD[1].addElements(p.min[1], p.max[1]);
  103915. this.axesD[2].addElements(p.min[2], p.max[2]);
  103916. p.belongsTo = 1;
  103917. this.numElementsD += 2;
  103918. } else {
  103919. this.axesS[0].addElements(p.min[0], p.max[0]);
  103920. this.axesS[1].addElements(p.min[1], p.max[1]);
  103921. this.axesS[2].addElements(p.min[2], p.max[2]);
  103922. p.belongsTo = 2;
  103923. this.numElementsS += 2;
  103924. }
  103925. };
  103926. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  103927. var p = proxy;
  103928. if (p.belongsTo == 0) return;
  103929. /*else if ( p.belongsTo == 1 ) {
  103930. this.axesD[0].removeElements( p.min[0], p.max[0] );
  103931. this.axesD[1].removeElements( p.min[1], p.max[1] );
  103932. this.axesD[2].removeElements( p.min[2], p.max[2] );
  103933. this.numElementsD -= 2;
  103934. } else if ( p.belongsTo == 2 ) {
  103935. this.axesS[0].removeElements( p.min[0], p.max[0] );
  103936. this.axesS[1].removeElements( p.min[1], p.max[1] );
  103937. this.axesS[2].removeElements( p.min[2], p.max[2] );
  103938. this.numElementsS -= 2;
  103939. }*/
  103940. switch (p.belongsTo) {
  103941. case 1:
  103942. this.axesD[0].removeElements(p.min[0], p.max[0]);
  103943. this.axesD[1].removeElements(p.min[1], p.max[1]);
  103944. this.axesD[2].removeElements(p.min[2], p.max[2]);
  103945. this.numElementsD -= 2;
  103946. break;
  103947. case 2:
  103948. this.axesS[0].removeElements(p.min[0], p.max[0]);
  103949. this.axesS[1].removeElements(p.min[1], p.max[1]);
  103950. this.axesS[2].removeElements(p.min[2], p.max[2]);
  103951. this.numElementsS -= 2;
  103952. break;
  103953. }
  103954. p.belongsTo = 0;
  103955. };
  103956. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  103957. if (this.numElementsD == 0) return;
  103958. var axis1 = this.axesD[this.index1];
  103959. var axis2 = this.axesD[this.index2];
  103960. axis1.sort();
  103961. axis2.sort();
  103962. var count1 = axis1.calculateTestCount();
  103963. var count2 = axis2.calculateTestCount();
  103964. var elementsD;
  103965. var elementsS;
  103966. if (count1 <= count2) {// select the best axis
  103967. axis2 = this.axesS[this.index1];
  103968. axis2.sort();
  103969. elementsD = axis1.elements;
  103970. elementsS = axis2.elements;
  103971. } else {
  103972. axis1 = this.axesS[this.index2];
  103973. axis1.sort();
  103974. elementsD = axis2.elements;
  103975. elementsS = axis1.elements;
  103976. this.index1 ^= this.index2;
  103977. this.index2 ^= this.index1;
  103978. this.index1 ^= this.index2;
  103979. }
  103980. var activeD;
  103981. var activeS;
  103982. var p = 0;
  103983. var q = 0;
  103984. while (p < this.numElementsD) {
  103985. var e1;
  103986. var dyn;
  103987. if (q == this.numElementsS) {
  103988. e1 = elementsD[p];
  103989. dyn = true;
  103990. p++;
  103991. } else {
  103992. var d = elementsD[p];
  103993. var s = elementsS[q];
  103994. if (d.value < s.value) {
  103995. e1 = d;
  103996. dyn = true;
  103997. p++;
  103998. } else {
  103999. e1 = s;
  104000. dyn = false;
  104001. q++;
  104002. }
  104003. }
  104004. if (!e1.max) {
  104005. var s1 = e1.proxy.shape;
  104006. var min1 = e1.min1.value;
  104007. var max1 = e1.max1.value;
  104008. var min2 = e1.min2.value;
  104009. var max2 = e1.max2.value;
  104010. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  104011. var s2 = e2.proxy.shape;
  104012. this.numPairChecks++;
  104013. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  104014. this.addPair(s1, s2);
  104015. }
  104016. if (dyn) {
  104017. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  104018. s2 = e2.proxy.shape;
  104019. this.numPairChecks++;
  104020. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  104021. this.addPair(s1, s2);
  104022. }
  104023. e1.pair = activeD;
  104024. activeD = e1;
  104025. } else {
  104026. e1.pair = activeS;
  104027. activeS = e1;
  104028. }
  104029. } else {
  104030. var min = e1.pair;
  104031. if (dyn) {
  104032. if (min == activeD) {
  104033. activeD = activeD.pair;
  104034. continue;
  104035. } else {
  104036. e1 = activeD;
  104037. }
  104038. } else {
  104039. if (min == activeS) {
  104040. activeS = activeS.pair;
  104041. continue;
  104042. } else {
  104043. e1 = activeS;
  104044. }
  104045. }
  104046. do {
  104047. e2 = e1.pair;
  104048. if (e2 == min) {
  104049. e1.pair = e2.pair;
  104050. break;
  104051. }
  104052. e1 = e2;
  104053. } while (e1 != null);
  104054. }
  104055. }
  104056. this.index2 = (this.index1 | this.index2) ^ 3;
  104057. };
  104058. /**
  104059. * An element of proxies.
  104060. * @author saharan
  104061. */
  104062. OIMO.SAPElement = function (proxy, max) {
  104063. // The parent proxy
  104064. this.proxy = proxy;
  104065. // The pair element.
  104066. this.pair = null;
  104067. // The minimum element on other axis.
  104068. this.min1 = null;
  104069. // The maximum element on other axis.
  104070. this.max1 = null;
  104071. // The minimum element on other axis.
  104072. this.min2 = null;
  104073. // The maximum element on other axis.
  104074. this.max2 = null;
  104075. // Whether the element has maximum value or not.
  104076. this.max = max;
  104077. // The value of the element.
  104078. this.value = 0;
  104079. };
  104080. /**
  104081. * A proxy for sweep and prune broad-phase.
  104082. * @author saharan
  104083. * @author lo-th
  104084. */
  104085. OIMO.SAPProxy = function (sap, shape) {
  104086. OIMO.Proxy.call(this, shape);
  104087. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  104088. this.belongsTo = 0;
  104089. // The maximum elements on each axis.
  104090. this.max = [];
  104091. // The minimum elements on each axis.
  104092. this.min = [];
  104093. this.sap = sap;
  104094. this.min[0] = new OIMO.SAPElement(this, false);
  104095. this.max[0] = new OIMO.SAPElement(this, true);
  104096. this.min[1] = new OIMO.SAPElement(this, false);
  104097. this.max[1] = new OIMO.SAPElement(this, true);
  104098. this.min[2] = new OIMO.SAPElement(this, false);
  104099. this.max[2] = new OIMO.SAPElement(this, true);
  104100. this.max[0].pair = this.min[0];
  104101. this.max[1].pair = this.min[1];
  104102. this.max[2].pair = this.min[2];
  104103. this.min[0].min1 = this.min[1];
  104104. this.min[0].max1 = this.max[1];
  104105. this.min[0].min2 = this.min[2];
  104106. this.min[0].max2 = this.max[2];
  104107. this.min[1].min1 = this.min[0];
  104108. this.min[1].max1 = this.max[0];
  104109. this.min[1].min2 = this.min[2];
  104110. this.min[1].max2 = this.max[2];
  104111. this.min[2].min1 = this.min[0];
  104112. this.min[2].max1 = this.max[0];
  104113. this.min[2].min2 = this.min[1];
  104114. this.min[2].max2 = this.max[1];
  104115. };
  104116. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  104117. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  104118. // Returns whether the proxy is dynamic or not.
  104119. OIMO.SAPProxy.prototype.isDynamic = function () {
  104120. var body = this.shape.parent;
  104121. return body.isDynamic && !body.sleeping;
  104122. };
  104123. OIMO.SAPProxy.prototype.update = function () {
  104124. var te = this.aabb.elements;
  104125. this.min[0].value = te[0];
  104126. this.min[1].value = te[1];
  104127. this.min[2].value = te[2];
  104128. this.max[0].value = te[3];
  104129. this.max[1].value = te[4];
  104130. this.max[2].value = te[5];
  104131. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  104132. this.sap.removeProxy(this);
  104133. this.sap.addProxy(this);
  104134. }
  104135. };
  104136. /**
  104137. * A dynamic bounding volume tree for the broad-phase algorithm.
  104138. * @author saharan
  104139. * @author lo-th
  104140. */
  104141. OIMO.DBVT = function () {
  104142. // The root of the tree.
  104143. this.root = null;
  104144. this.freeNodes = [];
  104145. this.freeNodes.length = 16384;
  104146. this.numFreeNodes = 0;
  104147. this.aabb = new OIMO.AABB();
  104148. };
  104149. OIMO.DBVT.prototype = {
  104150. constructor: OIMO.DBVT,
  104151. /**
  104152. * Move a leaf.
  104153. * @param leaf
  104154. */
  104155. moveLeaf: function (leaf) {
  104156. this.deleteLeaf(leaf);
  104157. this.insertLeaf(leaf);
  104158. },
  104159. /**
  104160. * Insert a leaf to the tree.
  104161. * @param node
  104162. */
  104163. insertLeaf: function (leaf) {
  104164. if (this.root == null) {
  104165. this.root = leaf;
  104166. return;
  104167. }
  104168. var lb = leaf.aabb;
  104169. var sibling = this.root;
  104170. var oldArea;
  104171. var newArea;
  104172. while (sibling.proxy == null) { // descend the node to search the best pair
  104173. var c1 = sibling.child1;
  104174. var c2 = sibling.child2;
  104175. var b = sibling.aabb;
  104176. var c1b = c1.aabb;
  104177. var c2b = c2.aabb;
  104178. oldArea = b.surfaceArea();
  104179. this.aabb.combine(lb, b);
  104180. newArea = this.aabb.surfaceArea();
  104181. var creatingCost = newArea * 2;
  104182. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  104183. var discendingCost1 = incrementalCost;
  104184. this.aabb.combine(lb, c1b);
  104185. if (c1.proxy != null) {
  104186. // leaf cost = area(combined aabb)
  104187. discendingCost1 += this.aabb.surfaceArea();
  104188. } else {
  104189. // node cost = area(combined aabb) - area(old aabb)
  104190. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  104191. }
  104192. var discendingCost2 = incrementalCost;
  104193. this.aabb.combine(lb, c2b);
  104194. if (c2.proxy != null) {
  104195. // leaf cost = area(combined aabb)
  104196. discendingCost2 += this.aabb.surfaceArea();
  104197. } else {
  104198. // node cost = area(combined aabb) - area(old aabb)
  104199. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  104200. }
  104201. if (discendingCost1 < discendingCost2) {
  104202. if (creatingCost < discendingCost1) {
  104203. break;// stop descending
  104204. } else {
  104205. sibling = c1;// descend into first child
  104206. }
  104207. } else {
  104208. if (creatingCost < discendingCost2) {
  104209. break;// stop descending
  104210. } else {
  104211. sibling = c2;// descend into second child
  104212. }
  104213. }
  104214. }
  104215. var oldParent = sibling.parent;
  104216. var newParent;
  104217. if (this.numFreeNodes > 0) {
  104218. newParent = this.freeNodes[--this.numFreeNodes];
  104219. } else {
  104220. newParent = new OIMO.DBVTNode();
  104221. }
  104222. newParent.parent = oldParent;
  104223. newParent.child1 = leaf;
  104224. newParent.child2 = sibling;
  104225. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  104226. newParent.height = sibling.height + 1;
  104227. sibling.parent = newParent;
  104228. leaf.parent = newParent;
  104229. if (sibling == this.root) {
  104230. // replace root
  104231. this.root = newParent;
  104232. } else {
  104233. // replace child
  104234. if (oldParent.child1 == sibling) {
  104235. oldParent.child1 = newParent;
  104236. } else {
  104237. oldParent.child2 = newParent;
  104238. }
  104239. }
  104240. // update whole tree
  104241. do {
  104242. newParent = this.balance(newParent);
  104243. this.fix(newParent);
  104244. newParent = newParent.parent;
  104245. } while (newParent != null);
  104246. },
  104247. getBalance: function (node) {
  104248. if (node.proxy != null) return 0;
  104249. return node.child1.height - node.child2.height;
  104250. },
  104251. /*print:function(node,indent,text){
  104252. var hasChild=node.proxy==null;
  104253. if(hasChild)text=this.print(node.child1,indent+1,text);
  104254. for(var i=indent*2;i>=0;i--){
  104255. text+=" ";
  104256. }
  104257. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  104258. if(hasChild)text=this.print(node.child2,indent+1,text);
  104259. return text;
  104260. },*/
  104261. /**
  104262. * Delete a leaf from the tree.
  104263. * @param node
  104264. */
  104265. deleteLeaf: function (leaf) {
  104266. if (leaf == this.root) {
  104267. this.root = null;
  104268. return;
  104269. }
  104270. var parent = leaf.parent;
  104271. var sibling;
  104272. if (parent.child1 == leaf) {
  104273. sibling = parent.child2;
  104274. } else {
  104275. sibling = parent.child1;
  104276. }
  104277. if (parent == this.root) {
  104278. this.root = sibling;
  104279. sibling.parent = null;
  104280. return;
  104281. }
  104282. var grandParent = parent.parent;
  104283. sibling.parent = grandParent;
  104284. if (grandParent.child1 == parent) {
  104285. grandParent.child1 = sibling;
  104286. } else {
  104287. grandParent.child2 = sibling;
  104288. }
  104289. if (this.numFreeNodes < 16384) {
  104290. this.freeNodes[this.numFreeNodes++] = parent;
  104291. }
  104292. do {
  104293. grandParent = this.balance(grandParent);
  104294. this.fix(grandParent);
  104295. grandParent = grandParent.parent;
  104296. } while (grandParent != null);
  104297. },
  104298. balance: function (node) {
  104299. var nh = node.height;
  104300. if (nh < 2) {
  104301. return node;
  104302. }
  104303. var p = node.parent;
  104304. var l = node.child1;
  104305. var r = node.child2;
  104306. var lh = l.height;
  104307. var rh = r.height;
  104308. var balance = lh - rh;
  104309. var t;// for bit operation
  104310. // [ N ]
  104311. // / \
  104312. // [ L ] [ R ]
  104313. // / \ / \
  104314. // [L-L] [L-R] [R-L] [R-R]
  104315. // Is the tree balanced?
  104316. if (balance > 1) {
  104317. var ll = l.child1;
  104318. var lr = l.child2;
  104319. var llh = ll.height;
  104320. var lrh = lr.height;
  104321. // Is L-L higher than L-R?
  104322. if (llh > lrh) {
  104323. // set N to L-R
  104324. l.child2 = node;
  104325. node.parent = l;
  104326. // [ L ]
  104327. // / \
  104328. // [L-L] [ N ]
  104329. // / \ / \
  104330. // [...] [...] [ L ] [ R ]
  104331. // set L-R
  104332. node.child1 = lr;
  104333. lr.parent = node;
  104334. // [ L ]
  104335. // / \
  104336. // [L-L] [ N ]
  104337. // / \ / \
  104338. // [...] [...] [L-R] [ R ]
  104339. // fix bounds and heights
  104340. node.aabb.combine(lr.aabb, r.aabb);
  104341. t = lrh - rh;
  104342. node.height = lrh - (t & t >> 31) + 1;
  104343. l.aabb.combine(ll.aabb, node.aabb);
  104344. t = llh - nh;
  104345. l.height = llh - (t & t >> 31) + 1;
  104346. } else {
  104347. // set N to L-L
  104348. l.child1 = node;
  104349. node.parent = l;
  104350. // [ L ]
  104351. // / \
  104352. // [ N ] [L-R]
  104353. // / \ / \
  104354. // [ L ] [ R ] [...] [...]
  104355. // set L-L
  104356. node.child1 = ll;
  104357. ll.parent = node;
  104358. // [ L ]
  104359. // / \
  104360. // [ N ] [L-R]
  104361. // / \ / \
  104362. // [L-L] [ R ] [...] [...]
  104363. // fix bounds and heights
  104364. node.aabb.combine(ll.aabb, r.aabb);
  104365. t = llh - rh;
  104366. node.height = llh - (t & t >> 31) + 1;
  104367. l.aabb.combine(node.aabb, lr.aabb);
  104368. t = nh - lrh;
  104369. l.height = nh - (t & t >> 31) + 1;
  104370. }
  104371. // set new parent of L
  104372. if (p != null) {
  104373. if (p.child1 == node) {
  104374. p.child1 = l;
  104375. } else {
  104376. p.child2 = l;
  104377. }
  104378. } else {
  104379. this.root = l;
  104380. }
  104381. l.parent = p;
  104382. return l;
  104383. } else if (balance < -1) {
  104384. var rl = r.child1;
  104385. var rr = r.child2;
  104386. var rlh = rl.height;
  104387. var rrh = rr.height;
  104388. // Is R-L higher than R-R?
  104389. if (rlh > rrh) {
  104390. // set N to R-R
  104391. r.child2 = node;
  104392. node.parent = r;
  104393. // [ R ]
  104394. // / \
  104395. // [R-L] [ N ]
  104396. // / \ / \
  104397. // [...] [...] [ L ] [ R ]
  104398. // set R-R
  104399. node.child2 = rr;
  104400. rr.parent = node;
  104401. // [ R ]
  104402. // / \
  104403. // [R-L] [ N ]
  104404. // / \ / \
  104405. // [...] [...] [ L ] [R-R]
  104406. // fix bounds and heights
  104407. node.aabb.combine(l.aabb, rr.aabb);
  104408. t = lh - rrh;
  104409. node.height = lh - (t & t >> 31) + 1;
  104410. r.aabb.combine(rl.aabb, node.aabb);
  104411. t = rlh - nh;
  104412. r.height = rlh - (t & t >> 31) + 1;
  104413. } else {
  104414. // set N to R-L
  104415. r.child1 = node;
  104416. node.parent = r;
  104417. // [ R ]
  104418. // / \
  104419. // [ N ] [R-R]
  104420. // / \ / \
  104421. // [ L ] [ R ] [...] [...]
  104422. // set R-L
  104423. node.child2 = rl;
  104424. rl.parent = node;
  104425. // [ R ]
  104426. // / \
  104427. // [ N ] [R-R]
  104428. // / \ / \
  104429. // [ L ] [R-L] [...] [...]
  104430. // fix bounds and heights
  104431. node.aabb.combine(l.aabb, rl.aabb);
  104432. t = lh - rlh;
  104433. node.height = lh - (t & t >> 31) + 1;
  104434. r.aabb.combine(node.aabb, rr.aabb);
  104435. t = nh - rrh;
  104436. r.height = nh - (t & t >> 31) + 1;
  104437. }
  104438. // set new parent of R
  104439. if (p != null) {
  104440. if (p.child1 == node) {
  104441. p.child1 = r;
  104442. } else {
  104443. p.child2 = r;
  104444. }
  104445. } else {
  104446. this.root = r;
  104447. }
  104448. r.parent = p;
  104449. return r;
  104450. }
  104451. return node;
  104452. },
  104453. fix: function (node) {
  104454. var c1 = node.child1;
  104455. var c2 = node.child2;
  104456. node.aabb.combine(c1.aabb, c2.aabb);
  104457. //var h1 = c1.height;
  104458. //var h2 = c2.height;
  104459. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  104460. /*if( h1 < h2 ) {
  104461. node.height = h2+1;
  104462. }else{
  104463. node.height = h1+1;
  104464. }*/
  104465. }
  104466. }
  104467. /**
  104468. * A broad-phase algorithm using dynamic bounding volume tree.
  104469. * @author saharan
  104470. * @author lo-th
  104471. */
  104472. OIMO.DBVTBroadPhase = function () {
  104473. OIMO.BroadPhase.call(this);
  104474. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  104475. this.tree = new OIMO.DBVT();
  104476. this.stack = [];
  104477. this.leaves = [];
  104478. this.numLeaves = 0;
  104479. };
  104480. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  104481. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  104482. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  104483. return new OIMO.DBVTProxy(shape);
  104484. };
  104485. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  104486. this.tree.insertLeaf(proxy.leaf);
  104487. this.leaves.push(proxy.leaf);
  104488. this.numLeaves++;
  104489. };
  104490. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  104491. this.tree.deleteLeaf(proxy.leaf);
  104492. var n = this.leaves.indexOf(proxy.leaf);
  104493. if (n > -1) {
  104494. this.leaves.splice(n, 1);
  104495. this.numLeaves--;
  104496. }
  104497. };
  104498. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  104499. if (this.numLeaves < 2) return;
  104500. var leaf, margin = 0.1, i = this.numLeaves;
  104501. while (i--) {
  104502. leaf = this.leaves[i];
  104503. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  104504. leaf.aabb.copy(leaf.proxy.aabb, margin);
  104505. this.tree.deleteLeaf(leaf);
  104506. this.tree.insertLeaf(leaf);
  104507. this.collide(leaf, this.tree.root);
  104508. }
  104509. }
  104510. };
  104511. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  104512. var stackCount = 2;
  104513. var s1, s2, n1, n2, l1, l2;
  104514. this.stack[0] = node1;
  104515. this.stack[1] = node2;
  104516. while (stackCount > 0) {
  104517. n1 = this.stack[--stackCount];
  104518. n2 = this.stack[--stackCount];
  104519. l1 = n1.proxy != null;
  104520. l2 = n2.proxy != null;
  104521. this.numPairChecks++;
  104522. if (l1 && l2) {
  104523. s1 = n1.proxy.shape;
  104524. s2 = n2.proxy.shape;
  104525. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  104526. this.addPair(s1, s2);
  104527. } else {
  104528. if (n1.aabb.intersectTest(n2.aabb)) continue;
  104529. /*if(stackCount+4>=this.maxStack){// expand the stack
  104530. //this.maxStack<<=1;
  104531. this.maxStack*=2;
  104532. var newStack = [];// vector
  104533. newStack.length = this.maxStack;
  104534. for(var i=0;i<stackCount;i++){
  104535. newStack[i] = this.stack[i];
  104536. }
  104537. this.stack = newStack;
  104538. }*/
  104539. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  104540. this.stack[stackCount++] = n1.child1;
  104541. this.stack[stackCount++] = n2;
  104542. this.stack[stackCount++] = n1.child2;
  104543. this.stack[stackCount++] = n2;
  104544. } else {
  104545. this.stack[stackCount++] = n1;
  104546. this.stack[stackCount++] = n2.child1;
  104547. this.stack[stackCount++] = n1;
  104548. this.stack[stackCount++] = n2.child2;
  104549. }
  104550. }
  104551. }
  104552. };
  104553. /**
  104554. * A node of the dynamic bounding volume tree.
  104555. * @author saharan
  104556. */
  104557. OIMO.DBVTNode = function () {
  104558. // The first child node of this node.
  104559. this.child1 = null;
  104560. // The second child node of this node.
  104561. this.child2 = null;
  104562. // The parent node of this tree.
  104563. this.parent = null;
  104564. // The proxy of this node. This has no value if this node is not leaf.
  104565. this.proxy = null;
  104566. // The maximum distance from leaf nodes.
  104567. this.height = 0;
  104568. // The AABB of this node.
  104569. this.aabb = new OIMO.AABB();
  104570. };
  104571. /**
  104572. * A proxy for dynamic bounding volume tree broad-phase.
  104573. * @author saharan
  104574. */
  104575. OIMO.DBVTProxy = function (shape) {
  104576. OIMO.Proxy.call(this, shape);
  104577. // The leaf of the proxy.
  104578. this.leaf = new OIMO.DBVTNode();
  104579. this.leaf.proxy = this;
  104580. };
  104581. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  104582. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  104583. OIMO.DBVTProxy.prototype.update = function () {
  104584. };
  104585. OIMO.World.prototype.add = function (obj) {
  104586. obj = obj || {};
  104587. var type = obj.type || "box";
  104588. if (typeof type === 'string') type = [type];// single shape
  104589. if (type[0].substring(0, 5) == 'joint') { // is joint
  104590. if (type[0] === 'joint') type[0] = 'jointHinge';
  104591. var axe1 = obj.axe1 || [1, 0, 0];
  104592. var axe2 = obj.axe2 || [1, 0, 0];
  104593. var pos1 = obj.pos1 || [0, 0, 0];
  104594. var pos2 = obj.pos2 || [0, 0, 0];
  104595. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  104596. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  104597. var min, max;
  104598. if (type[0] === "jointDistance") {
  104599. min = obj.min || 0;
  104600. max = obj.max || 10;
  104601. min = min * OIMO.INV_SCALE;
  104602. max = max * OIMO.INV_SCALE;
  104603. } else {
  104604. min = obj.min || 57.29578;
  104605. max = obj.max || 0;
  104606. min = min * OIMO.degtorad;
  104607. max = max * OIMO.degtorad;
  104608. }
  104609. var limit = obj.limit || null;
  104610. var spring = obj.spring || null;
  104611. var motor = obj.motor || null;
  104612. // joint setting
  104613. var jc = new OIMO.JointConfig();
  104614. jc.allowCollision = obj.collision || false;;
  104615. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  104616. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  104617. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  104618. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  104619. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  104620. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  104621. jc.body1 = obj.body1;
  104622. jc.body2 = obj.body2;
  104623. var joint;
  104624. switch (type[0]) {
  104625. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  104626. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  104627. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  104628. break;
  104629. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  104630. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  104631. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  104632. break;
  104633. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  104634. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  104635. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  104636. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  104637. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  104638. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  104639. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  104640. break;
  104641. }
  104642. joint.name = obj.name || '';
  104643. // finaly add to physics world
  104644. this.addJoint(joint);
  104645. return joint;
  104646. } else { // is body
  104647. // I'm dynamique or not
  104648. var move = obj.move || false;
  104649. // I can sleep or not
  104650. var noSleep = obj.noSleep || false;
  104651. // My start position
  104652. var p = obj.pos || [0, 0, 0];
  104653. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  104654. // My size
  104655. var s = obj.size || [1, 1, 1];
  104656. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  104657. // My rotation in degre
  104658. var rot = obj.rot || [0, 0, 0];
  104659. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  104660. var r = [];
  104661. for (var i = 0; i < rot.length / 3; i++) {
  104662. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  104663. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  104664. }
  104665. // My physics setting
  104666. var sc = new OIMO.ShapeConfig();
  104667. if (obj.sc !== undefined) sc = obj.sc;
  104668. if (obj.config) {
  104669. // The density of the shape.
  104670. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  104671. // The coefficient of friction of the shape.
  104672. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  104673. // The coefficient of restitution of the shape.
  104674. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  104675. // The bits of the collision groups to which the shape belongs.
  104676. sc.belongsTo = obj.config[3] || 1;
  104677. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  104678. // The bits of the collision groups with which the shape collides.
  104679. sc.collidesWith = obj.config[4] || 0xffffffff;
  104680. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  104681. }
  104682. // direct physics setting
  104683. if (obj.density !== undefined) sc.density = obj.density;
  104684. if (obj.friction !== undefined) sc.friction = obj.friction;
  104685. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  104686. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  104687. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  104688. if (obj.massPos) {
  104689. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  104690. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  104691. }
  104692. if (obj.massRot) {
  104693. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  104694. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  104695. }
  104696. // My rigidbody
  104697. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  104698. // My shapes
  104699. var shapes = [];
  104700. //if( typeof type === 'string' ) type = [type];// single shape
  104701. var n, n2;
  104702. for (var i = 0; i < type.length; i++) {
  104703. n = i * 3;
  104704. n2 = i * 4;
  104705. switch (type[i]) {
  104706. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  104707. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  104708. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  104709. }
  104710. body.addShape(shapes[i]);
  104711. if (i > 0) {
  104712. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  104713. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  104714. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  104715. }
  104716. }
  104717. // I'm static or i move
  104718. if (move) {
  104719. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  104720. else body.setupMass(0x1, true);
  104721. if (noSleep) body.allowSleep = false;
  104722. else body.allowSleep = true;
  104723. } else {
  104724. body.setupMass(0x2);
  104725. }
  104726. body.name = obj.name || ' ';
  104727. // finaly add to physics world
  104728. this.addRigidBody(body);
  104729. return body;
  104730. }
  104731. }
  104732. //UMD simplified
  104733. var root = this;
  104734. if (!root['OIMO']) {
  104735. if (true)
  104736. module.exports = OIMO;
  104737. else if (typeof define === 'function' && define.amd)
  104738. define([], function () {
  104739. return OIMO;
  104740. });
  104741. else if (typeof exports === 'object')
  104742. exports["OIMO"] = OIMO;
  104743. else {
  104744. root["OIMO"] = OIMO;
  104745. }
  104746. }
  104747. /***/ }),
  104748. /* 19 */
  104749. /***/ (function(module, exports, __webpack_require__) {
  104750. "use strict";
  104751. Object.defineProperty(exports, "__esModule", { value: true });
  104752. var babylonjs_1 = __webpack_require__(0);
  104753. var helper_1 = __webpack_require__(2);
  104754. var TemplateManager = (function () {
  104755. function TemplateManager(containerElement) {
  104756. this.containerElement = containerElement;
  104757. this.templates = {};
  104758. this.onInit = new babylonjs_1.Observable();
  104759. this.onLoaded = new babylonjs_1.Observable();
  104760. this.onStateChange = new babylonjs_1.Observable();
  104761. this.onAllLoaded = new babylonjs_1.Observable();
  104762. this.onEventTriggered = new babylonjs_1.Observable();
  104763. this.eventManager = new eventManager_1.EventManager(this);
  104764. }
  104765. TemplateManager.prototype.initTemplate = function (templates) {
  104766. var _this = this;
  104767. var internalInit = function (dependencyMap, name, parentTemplate) {
  104768. var template = _this.templates[name];
  104769. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  104770. return internalInit(dependencyMap[childName], childName, template);
  104771. });
  104772. var addToParent = function () {
  104773. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  104774. template.appendTo(containingElement);
  104775. _this.checkLoadedState();
  104776. };
  104777. if (parentTemplate && !parentTemplate.parent) {
  104778. parentTemplate.onAppended.add(function () {
  104779. addToParent();
  104780. });
  104781. }
  104782. else {
  104783. addToParent();
  104784. }
  104785. return template;
  104786. };
  104787. return this.buildHTMLTree(templates).then(function (htmlTree) {
  104788. if (_this.templates['main']) {
  104789. internalInit(htmlTree, 'main');
  104790. }
  104791. else {
  104792. _this.checkLoadedState();
  104793. }
  104794. return;
  104795. });
  104796. };
  104797. TemplateManager.prototype.buildHTMLTree = function (templates) {
  104798. var _this = this;
  104799. var promises = Object.keys(templates).map(function (name) {
  104800. if (!templates[name])
  104801. return Promise.resolve(false);
  104802. var template = new Template(name, templates[name]);
  104803. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  104804. _this.templates[name] = template;
  104805. return template.initPromise;
  104806. });
  104807. return Promise.all(promises).then(function () {
  104808. var templateStructure = {};
  104809. var buildTree = function (parentObject, name) {
  104810. _this.templates[name].isInHtmlTree = true;
  104811. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  104812. childNodes.forEach(function (element) {
  104813. parentObject[element] = {};
  104814. buildTree(parentObject[element], element);
  104815. });
  104816. };
  104817. if (_this.templates['main']) {
  104818. buildTree(templateStructure, "main");
  104819. }
  104820. return templateStructure;
  104821. });
  104822. };
  104823. TemplateManager.prototype.getCanvas = function () {
  104824. return this.containerElement.querySelector('canvas');
  104825. };
  104826. TemplateManager.prototype.getTemplate = function (name) {
  104827. return this.templates[name];
  104828. };
  104829. TemplateManager.prototype.checkLoadedState = function () {
  104830. var _this = this;
  104831. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  104832. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  104833. });
  104834. if (done) {
  104835. this.onAllLoaded.notifyObservers(this);
  104836. }
  104837. };
  104838. TemplateManager.prototype.dispose = function () {
  104839. var _this = this;
  104840. Object.keys(this.templates).forEach(function (template) {
  104841. _this.templates[template].dispose();
  104842. });
  104843. this.onInit.clear();
  104844. this.onAllLoaded.clear();
  104845. this.onEventTriggered.clear();
  104846. this.onLoaded.clear();
  104847. this.onStateChange.clear();
  104848. };
  104849. return TemplateManager;
  104850. }());
  104851. exports.TemplateManager = TemplateManager;
  104852. var Handlebars = __webpack_require__(20);
  104853. var eventManager_1 = __webpack_require__(21);
  104854. Handlebars.registerHelper('eachInMap', function (map, block) {
  104855. var out = '';
  104856. Object.keys(map).map(function (prop) {
  104857. var data = map[prop];
  104858. if (typeof data === 'object') {
  104859. data.id = data.id || prop;
  104860. out += block.fn(data);
  104861. }
  104862. else {
  104863. out += block.fn({ id: prop, value: data });
  104864. }
  104865. });
  104866. return out;
  104867. });
  104868. var Template = (function () {
  104869. function Template(name, _configuration) {
  104870. var _this = this;
  104871. this.name = name;
  104872. this._configuration = _configuration;
  104873. this.onInit = new babylonjs_1.Observable();
  104874. this.onLoaded = new babylonjs_1.Observable();
  104875. this.onAppended = new babylonjs_1.Observable();
  104876. this.onStateChange = new babylonjs_1.Observable();
  104877. this.onEventTriggered = new babylonjs_1.Observable();
  104878. this.loadRequests = [];
  104879. this.isLoaded = false;
  104880. this.isShown = false;
  104881. this.isInHtmlTree = false;
  104882. this.onInit.notifyObservers(this);
  104883. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  104884. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  104885. if (htmlTemplate) {
  104886. _this.htmlTemplate = htmlTemplate;
  104887. var compiledTemplate = Handlebars.compile(htmlTemplate);
  104888. var config = _this._configuration.params || {};
  104889. var rawHtml = compiledTemplate(config);
  104890. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  104891. _this.isLoaded = true;
  104892. _this.isShown = true;
  104893. _this.onLoaded.notifyObservers(_this);
  104894. }
  104895. return _this;
  104896. });
  104897. }
  104898. Template.prototype.updateParams = function (params) {
  104899. this._configuration.params = params;
  104900. if (this.isLoaded) {
  104901. this.dispose();
  104902. }
  104903. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  104904. var config = this._configuration.params || {};
  104905. var rawHtml = compiledTemplate(config);
  104906. this.fragment = document.createRange().createContextualFragment(rawHtml);
  104907. if (this.parent) {
  104908. this.appendTo(this.parent, true);
  104909. }
  104910. };
  104911. Object.defineProperty(Template.prototype, "configuration", {
  104912. get: function () {
  104913. return this._configuration;
  104914. },
  104915. enumerable: true,
  104916. configurable: true
  104917. });
  104918. Template.prototype.getChildElements = function () {
  104919. var childrenArray = [];
  104920. var children = this.fragment.children;
  104921. if (!children) {
  104922. children = this.fragment.querySelectorAll('*');
  104923. }
  104924. for (var i = 0; i < children.length; ++i) {
  104925. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  104926. }
  104927. return childrenArray;
  104928. };
  104929. Template.prototype.appendTo = function (parent, forceRemove) {
  104930. var _this = this;
  104931. if (this.parent) {
  104932. if (forceRemove) {
  104933. this.parent.removeChild(this.fragment);
  104934. }
  104935. else {
  104936. return;
  104937. }
  104938. }
  104939. this.parent = parent;
  104940. if (this._configuration.id) {
  104941. this.parent.id = this._configuration.id;
  104942. }
  104943. this.fragment = this.parent.appendChild(this.fragment);
  104944. setTimeout(function () {
  104945. _this.registerEvents();
  104946. _this.onAppended.notifyObservers(_this);
  104947. });
  104948. };
  104949. Template.prototype.show = function (visibilityFunction) {
  104950. var _this = this;
  104951. if (this.isHiding)
  104952. return Promise.resolve(this);
  104953. return Promise.resolve().then(function () {
  104954. _this.isShowing = true;
  104955. if (visibilityFunction) {
  104956. return visibilityFunction(_this);
  104957. }
  104958. else {
  104959. _this.parent.style.display = 'flex';
  104960. return _this;
  104961. }
  104962. }).then(function () {
  104963. _this.isShown = true;
  104964. _this.isShowing = false;
  104965. _this.onStateChange.notifyObservers(_this);
  104966. return _this;
  104967. });
  104968. };
  104969. Template.prototype.hide = function (visibilityFunction) {
  104970. var _this = this;
  104971. if (this.isShowing)
  104972. return Promise.resolve(this);
  104973. return Promise.resolve().then(function () {
  104974. _this.isHiding = true;
  104975. if (visibilityFunction) {
  104976. return visibilityFunction(_this);
  104977. }
  104978. else {
  104979. _this.parent.style.display = 'hide';
  104980. return _this;
  104981. }
  104982. }).then(function () {
  104983. _this.isShown = false;
  104984. _this.isHiding = false;
  104985. _this.onStateChange.notifyObservers(_this);
  104986. return _this;
  104987. });
  104988. };
  104989. Template.prototype.dispose = function () {
  104990. this.onAppended.clear();
  104991. this.onEventTriggered.clear();
  104992. this.onInit.clear();
  104993. this.onLoaded.clear();
  104994. this.onStateChange.clear();
  104995. this.isLoaded = false;
  104996. this.parent.removeChild(this.fragment);
  104997. this.loadRequests.forEach(function (request) {
  104998. request.abort();
  104999. });
  105000. };
  105001. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  105002. var _this = this;
  105003. if (!templateConfig) {
  105004. return Promise.reject('No templateConfig provided');
  105005. }
  105006. else if (templateConfig.html !== undefined) {
  105007. return Promise.resolve(templateConfig.html);
  105008. }
  105009. else {
  105010. var location_1 = getTemplateLocation(templateConfig);
  105011. if (helper_1.isUrl(location_1)) {
  105012. return new Promise(function (resolve, reject) {
  105013. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  105014. resolve(data);
  105015. }, undefined, undefined, false, function (request, error) {
  105016. reject(error);
  105017. });
  105018. _this.loadRequests.push(fileRequest);
  105019. });
  105020. }
  105021. else {
  105022. location_1 = location_1.replace('#', '');
  105023. var element = document.getElementById(location_1);
  105024. if (element) {
  105025. return Promise.resolve(element.innerHTML);
  105026. }
  105027. else {
  105028. return Promise.reject('Template ID not found');
  105029. }
  105030. }
  105031. }
  105032. };
  105033. Template.prototype.registerEvents = function () {
  105034. var _this = this;
  105035. this.registeredEvents = this.registeredEvents || [];
  105036. if (this.registeredEvents.length) {
  105037. this.registeredEvents.forEach(function (evt) {
  105038. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  105039. });
  105040. }
  105041. if (this._configuration.events) {
  105042. var _loop_1 = function (eventName) {
  105043. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  105044. var functionToFire_1 = function (selector, event) {
  105045. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  105046. };
  105047. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  105048. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  105049. }
  105050. else if (typeof this_1._configuration.events[eventName] === 'object') {
  105051. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  105052. var event_1 = this_1._configuration.events[eventName] || {};
  105053. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  105054. if (selector && selector.indexOf('#') !== 0) {
  105055. selector = '#' + selector;
  105056. }
  105057. var htmlElement = _this.parent.querySelector(selector);
  105058. if (htmlElement) {
  105059. var binding = functionToFire_1.bind(_this, selector);
  105060. htmlElement.addEventListener(eventName, binding, false);
  105061. _this.registeredEvents.push({
  105062. htmlElement: htmlElement,
  105063. eventName: eventName,
  105064. function: binding
  105065. });
  105066. }
  105067. });
  105068. }
  105069. }
  105070. };
  105071. var this_1 = this;
  105072. for (var eventName in this._configuration.events) {
  105073. _loop_1(eventName);
  105074. }
  105075. }
  105076. };
  105077. return Template;
  105078. }());
  105079. exports.Template = Template;
  105080. function getTemplateLocation(templateConfig) {
  105081. if (!templateConfig || typeof templateConfig === 'string') {
  105082. return templateConfig;
  105083. }
  105084. else {
  105085. return templateConfig.location;
  105086. }
  105087. }
  105088. exports.getTemplateLocation = getTemplateLocation;
  105089. /***/ }),
  105090. /* 20 */
  105091. /***/ (function(module, exports, __webpack_require__) {
  105092. /**!
  105093. @license
  105094. handlebars v4.0.11
  105095. Copyright (C) 2011-2017 by Yehuda Katz
  105096. Permission is hereby granted, free of charge, to any person obtaining a copy
  105097. of this software and associated documentation files (the "Software"), to deal
  105098. in the Software without restriction, including without limitation the rights
  105099. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  105100. copies of the Software, and to permit persons to whom the Software is
  105101. furnished to do so, subject to the following conditions:
  105102. The above copyright notice and this permission notice shall be included in
  105103. all copies or substantial portions of the Software.
  105104. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  105105. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  105106. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  105107. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  105108. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  105109. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  105110. THE SOFTWARE.
  105111. */
  105112. !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],
  105113. 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){
  105114. 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"]}])});
  105115. /***/ }),
  105116. /* 21 */
  105117. /***/ (function(module, exports, __webpack_require__) {
  105118. "use strict";
  105119. Object.defineProperty(exports, "__esModule", { value: true });
  105120. var EventManager = (function () {
  105121. function EventManager(templateManager) {
  105122. var _this = this;
  105123. this.templateManager = templateManager;
  105124. this.callbacksContainer = {};
  105125. this.templateManager.onEventTriggered.add(function (eventData) {
  105126. _this.eventTriggered(eventData);
  105127. });
  105128. }
  105129. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  105130. if (!this.callbacksContainer[templateName]) {
  105131. this.callbacksContainer[templateName] = [];
  105132. }
  105133. this.callbacksContainer[templateName].push({
  105134. eventType: eventType,
  105135. callback: callback
  105136. });
  105137. };
  105138. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  105139. var callbackDefs = this.callbacksContainer[templateName] || [];
  105140. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  105141. };
  105142. EventManager.prototype.eventTriggered = function (data) {
  105143. var templateName = data.template.name;
  105144. var eventType = data.event.type;
  105145. var selector = data.selector;
  105146. var callbackDefs = this.callbacksContainer[templateName] || [];
  105147. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  105148. callbackDef.callback(data);
  105149. });
  105150. };
  105151. return EventManager;
  105152. }());
  105153. exports.EventManager = EventManager;
  105154. /***/ }),
  105155. /* 22 */
  105156. /***/ (function(module, exports, __webpack_require__) {
  105157. "use strict";
  105158. Object.defineProperty(exports, "__esModule", { value: true });
  105159. var mappers_1 = __webpack_require__(1);
  105160. var types_1 = __webpack_require__(23);
  105161. var deepmerge = __webpack_require__(13);
  105162. var babylonjs_1 = __webpack_require__(0);
  105163. var ConfigurationLoader = (function () {
  105164. function ConfigurationLoader() {
  105165. this.configurationCache = {};
  105166. this.loadRequests = [];
  105167. }
  105168. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  105169. var _this = this;
  105170. if (initConfig === void 0) { initConfig = {}; }
  105171. var loadedConfig = deepmerge({}, initConfig);
  105172. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  105173. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  105174. if (loadedConfig.configuration) {
  105175. var mapperType_1 = "json";
  105176. return Promise.resolve().then(function () {
  105177. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  105178. var url = '';
  105179. if (typeof loadedConfig.configuration === "string") {
  105180. url = loadedConfig.configuration;
  105181. }
  105182. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  105183. url = loadedConfig.configuration.url;
  105184. var type = loadedConfig.configuration.mapper;
  105185. if (!type) {
  105186. type = loadedConfig.configuration.url.split('.').pop();
  105187. }
  105188. mapperType_1 = type || mapperType_1;
  105189. }
  105190. return _this.loadFile(url);
  105191. }
  105192. else {
  105193. if (typeof loadedConfig.configuration === "object") {
  105194. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  105195. return loadedConfig.configuration.payload || {};
  105196. }
  105197. return {};
  105198. }
  105199. }).then(function (data) {
  105200. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  105201. var parsed = mapper.map(data);
  105202. var merged = deepmerge(loadedConfig, parsed);
  105203. if (callback)
  105204. callback(merged);
  105205. return merged;
  105206. });
  105207. }
  105208. else {
  105209. if (callback)
  105210. callback(loadedConfig);
  105211. return Promise.resolve(loadedConfig);
  105212. }
  105213. };
  105214. ConfigurationLoader.prototype.dispose = function () {
  105215. this.loadRequests.forEach(function (request) {
  105216. request.abort();
  105217. });
  105218. };
  105219. ConfigurationLoader.prototype.loadFile = function (url) {
  105220. var _this = this;
  105221. var cacheReference = this.configurationCache;
  105222. if (cacheReference[url]) {
  105223. return Promise.resolve(cacheReference[url]);
  105224. }
  105225. return new Promise(function (resolve, reject) {
  105226. var fileRequest = babylonjs_1.Tools.LoadFile(url, resolve, undefined, undefined, false, function (request, error) {
  105227. reject(error);
  105228. });
  105229. _this.loadRequests.push(fileRequest);
  105230. });
  105231. };
  105232. return ConfigurationLoader;
  105233. }());
  105234. exports.ConfigurationLoader = ConfigurationLoader;
  105235. exports.configurationLoader = new ConfigurationLoader();
  105236. exports.default = exports.configurationLoader;
  105237. /***/ }),
  105238. /* 23 */
  105239. /***/ (function(module, exports, __webpack_require__) {
  105240. "use strict";
  105241. Object.defineProperty(exports, "__esModule", { value: true });
  105242. var minimal_1 = __webpack_require__(24);
  105243. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  105244. var default_1 = __webpack_require__(25);
  105245. exports.defaultConfiguration = default_1.defaultConfiguration;
  105246. var getConfigurationType = function (type) {
  105247. switch (type) {
  105248. case 'default':
  105249. return default_1.defaultConfiguration;
  105250. case 'minimal':
  105251. return minimal_1.minimalConfiguration;
  105252. case 'none':
  105253. return {};
  105254. default:
  105255. return default_1.defaultConfiguration;
  105256. }
  105257. };
  105258. exports.getConfigurationType = getConfigurationType;
  105259. /***/ }),
  105260. /* 24 */
  105261. /***/ (function(module, exports, __webpack_require__) {
  105262. "use strict";
  105263. Object.defineProperty(exports, "__esModule", { value: true });
  105264. exports.minimalConfiguration = {
  105265. version: "0.1",
  105266. templates: {
  105267. main: {
  105268. html: __webpack_require__(6)
  105269. },
  105270. loadingScreen: {
  105271. html: __webpack_require__(7),
  105272. params: {
  105273. backgroundColor: "#000000",
  105274. loadingImage: __webpack_require__(8)
  105275. }
  105276. },
  105277. viewer: {
  105278. html: __webpack_require__(9),
  105279. },
  105280. overlay: {
  105281. html: __webpack_require__(10),
  105282. params: {
  105283. closeImage: __webpack_require__(11),
  105284. closeText: 'Close'
  105285. }
  105286. },
  105287. error: {
  105288. html: __webpack_require__(12)
  105289. }
  105290. },
  105291. engine: {
  105292. antialiasing: true
  105293. }
  105294. };
  105295. /***/ }),
  105296. /* 25 */
  105297. /***/ (function(module, exports, __webpack_require__) {
  105298. "use strict";
  105299. Object.defineProperty(exports, "__esModule", { value: true });
  105300. exports.defaultConfiguration = {
  105301. version: "3.2.0-alpha4",
  105302. templates: {
  105303. main: {
  105304. html: __webpack_require__(6)
  105305. },
  105306. loadingScreen: {
  105307. html: __webpack_require__(7),
  105308. params: {
  105309. backgroundColor: "#000000",
  105310. loadingImage: __webpack_require__(8)
  105311. }
  105312. },
  105313. viewer: {
  105314. html: __webpack_require__(9),
  105315. events: {
  105316. pointerout: true,
  105317. pointerdown: true,
  105318. pointerup: true
  105319. }
  105320. },
  105321. navBar: {
  105322. html: __webpack_require__(26),
  105323. params: {
  105324. buttons: {
  105325. "fullscreen-button": {
  105326. altText: "Fullscreen",
  105327. image: __webpack_require__(27)
  105328. }
  105329. },
  105330. visibilityTimeout: 2000
  105331. },
  105332. events: {
  105333. pointerdown: { 'fullscreen-button': true },
  105334. pointerover: true
  105335. }
  105336. },
  105337. overlay: {
  105338. html: __webpack_require__(10),
  105339. params: {
  105340. closeImage: __webpack_require__(11),
  105341. closeText: 'Close'
  105342. }
  105343. },
  105344. help: {
  105345. html: __webpack_require__(28)
  105346. },
  105347. share: {
  105348. html: __webpack_require__(29)
  105349. },
  105350. error: {
  105351. html: __webpack_require__(12)
  105352. }
  105353. },
  105354. camera: {
  105355. behaviors: {
  105356. autoRotate: 0,
  105357. framing: {
  105358. type: 2,
  105359. zoomOnBoundingInfo: true,
  105360. zoomStopsAnimation: false
  105361. }
  105362. }
  105363. },
  105364. skybox: {
  105365. pbr: true,
  105366. blur: 0.7,
  105367. infiniteDIstance: false,
  105368. },
  105369. ground: true,
  105370. engine: {
  105371. antialiasing: true
  105372. },
  105373. scene: {
  105374. imageProcessingConfiguration: {
  105375. exposure: 1.4,
  105376. contrast: 1.66,
  105377. toneMappingEnabled: true
  105378. }
  105379. }
  105380. };
  105381. /***/ }),
  105382. /* 26 */
  105383. /***/ (function(module, exports) {
  105384. 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>";
  105385. /***/ }),
  105386. /* 27 */
  105387. /***/ (function(module, exports) {
  105388. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  105389. /***/ }),
  105390. /* 28 */
  105391. /***/ (function(module, exports) {
  105392. module.exports = "HELP";
  105393. /***/ }),
  105394. /* 29 */
  105395. /***/ (function(module, exports) {
  105396. module.exports = "SHARE";
  105397. /***/ }),
  105398. /* 30 */
  105399. /***/ (function(module, exports, __webpack_require__) {
  105400. "use strict";
  105401. Object.defineProperty(exports, "__esModule", { value: true });
  105402. var babylonjs_1 = __webpack_require__(0);
  105403. var modelAnimation_1 = __webpack_require__(31);
  105404. var ViewerModel = (function () {
  105405. function ViewerModel(_modelConfiguration, _scene, disableAutoLoad) {
  105406. if (disableAutoLoad === void 0) { disableAutoLoad = false; }
  105407. this._modelConfiguration = _modelConfiguration;
  105408. this._scene = _scene;
  105409. this.onLoadedObservable = new babylonjs_1.Observable();
  105410. this.onLoadErrorObservable = new babylonjs_1.Observable();
  105411. this.onLoadProgressObservable = new babylonjs_1.Observable();
  105412. this._animations = [];
  105413. if (!disableAutoLoad) {
  105414. this._initLoad();
  105415. }
  105416. }
  105417. ViewerModel.prototype.load = function () {
  105418. if (this.loader) {
  105419. babylonjs_1.Tools.Error("Model was already loaded or in the process of loading.");
  105420. }
  105421. else {
  105422. this._initLoad();
  105423. }
  105424. };
  105425. ViewerModel.prototype.getAnimationNames = function () {
  105426. return this._animations.map(function (a) { return a.name; });
  105427. };
  105428. ViewerModel.prototype._getAnimationByName = function (name) {
  105429. var filtered = this._animations.filter(function (a) { return a.name === name; });
  105430. if (filtered.length === 1) {
  105431. return filtered[0];
  105432. }
  105433. else {
  105434. return null;
  105435. }
  105436. };
  105437. ViewerModel.prototype.playAnimation = function (name) {
  105438. var animation = this._getAnimationByName(name);
  105439. if (animation) {
  105440. if (this.currentAnimation) {
  105441. this.currentAnimation.stop();
  105442. }
  105443. this.currentAnimation = animation;
  105444. animation.start();
  105445. return animation;
  105446. }
  105447. else {
  105448. throw new Error("animation not found - " + name);
  105449. }
  105450. };
  105451. ViewerModel.prototype._initLoad = function () {
  105452. var _this = this;
  105453. if (!this._modelConfiguration || !this._modelConfiguration.url) {
  105454. return babylonjs_1.Tools.Error("No model URL to load.");
  105455. }
  105456. var parts = this._modelConfiguration.url.split('/');
  105457. var filename = parts.pop() || this._modelConfiguration.url;
  105458. var base = parts.length ? parts.join('/') + '/' : './';
  105459. var plugin = this._modelConfiguration.loader;
  105460. var animationsArray = this._scene.animationGroups.slice();
  105461. this.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._scene, function (meshes, particleSystems, skeletons) {
  105462. meshes.forEach(function (mesh) {
  105463. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  105464. });
  105465. _this.meshes = meshes;
  105466. _this.particleSystems = particleSystems;
  105467. _this.skeletons = skeletons;
  105468. if (_this.loader.name === 'gltf') {
  105469. _this._scene.animationGroups.forEach(function (ag) {
  105470. if (animationsArray.indexOf(ag) === -1) {
  105471. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  105472. }
  105473. });
  105474. }
  105475. else {
  105476. skeletons.forEach(function (skeleton, idx) {
  105477. var ag = new BABYLON.AnimationGroup("animation-" + idx, _this._scene);
  105478. skeleton.getAnimatables().forEach(function (a) {
  105479. if (a.animations[0]) {
  105480. ag.addTargetedAnimation(a.animations[0], a);
  105481. }
  105482. });
  105483. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  105484. });
  105485. }
  105486. if (_this._modelConfiguration.animation) {
  105487. if (_this._modelConfiguration.animation.playOnce) {
  105488. _this._animations.forEach(function (a) {
  105489. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  105490. });
  105491. }
  105492. if (_this._modelConfiguration.animation.autoStart && _this._animations.length) {
  105493. var animationName = _this._modelConfiguration.animation.autoStart === true ?
  105494. _this._animations[0].name : _this._modelConfiguration.animation.autoStart;
  105495. _this.playAnimation(animationName);
  105496. }
  105497. }
  105498. _this.onLoadedObservable.notifyObserversWithPromise(_this);
  105499. }, function (progressEvent) {
  105500. _this.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  105501. }, function (e, m, exception) {
  105502. _this.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  105503. }, plugin);
  105504. this.loader['animationStartMode'] = 0;
  105505. };
  105506. ViewerModel.prototype.dispose = function () {
  105507. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  105508. this.skeletons.forEach(function (s) { return s.dispose(); });
  105509. this._animations.forEach(function (ag) { return ag.dispose(); });
  105510. this.meshes.forEach(function (m) { return m.dispose(); });
  105511. };
  105512. return ViewerModel;
  105513. }());
  105514. exports.ViewerModel = ViewerModel;
  105515. /***/ }),
  105516. /* 31 */
  105517. /***/ (function(module, exports, __webpack_require__) {
  105518. "use strict";
  105519. Object.defineProperty(exports, "__esModule", { value: true });
  105520. var AnimationPlayMode;
  105521. (function (AnimationPlayMode) {
  105522. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  105523. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  105524. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  105525. var AnimationState;
  105526. (function (AnimationState) {
  105527. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  105528. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  105529. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  105530. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  105531. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  105532. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  105533. var GroupModelAnimation = (function () {
  105534. function GroupModelAnimation(_animationGroup) {
  105535. var _this = this;
  105536. this._animationGroup = _animationGroup;
  105537. this._state = AnimationState.INIT;
  105538. this._playMode = AnimationPlayMode.LOOP;
  105539. this._animationGroup.onAnimationEndObservable.add(function () {
  105540. _this.stop();
  105541. _this._state = AnimationState.ENDED;
  105542. });
  105543. }
  105544. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  105545. get: function () {
  105546. return this._animationGroup.name;
  105547. },
  105548. enumerable: true,
  105549. configurable: true
  105550. });
  105551. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  105552. get: function () {
  105553. return this._state;
  105554. },
  105555. enumerable: true,
  105556. configurable: true
  105557. });
  105558. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  105559. get: function () {
  105560. return this._animationGroup.speedRatio;
  105561. },
  105562. set: function (value) {
  105563. this._animationGroup.speedRatio = value;
  105564. },
  105565. enumerable: true,
  105566. configurable: true
  105567. });
  105568. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  105569. get: function () {
  105570. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  105571. var keys = ta.animation.getKeys();
  105572. return keys[keys.length - 1].frame;
  105573. });
  105574. return Math.max.apply(null, animationFrames);
  105575. },
  105576. enumerable: true,
  105577. configurable: true
  105578. });
  105579. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  105580. get: function () {
  105581. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  105582. var animatable = this._animationGroup.animatables[i];
  105583. var animations = animatable.getAnimations();
  105584. if (!animations || !animations.length) {
  105585. continue;
  105586. }
  105587. for (var idx = 0; idx < animations.length; ++idx) {
  105588. if (animations[idx].currentFrame) {
  105589. return animations[idx].currentFrame;
  105590. }
  105591. }
  105592. }
  105593. return 0;
  105594. },
  105595. enumerable: true,
  105596. configurable: true
  105597. });
  105598. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  105599. get: function () {
  105600. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  105601. var animatable = this._animationGroup.animatables[i];
  105602. var animations = animatable.getAnimations();
  105603. if (!animations || !animations.length) {
  105604. continue;
  105605. }
  105606. for (var idx = 0; idx < animations.length; ++idx) {
  105607. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  105608. return animations[idx].animation.framePerSecond;
  105609. }
  105610. }
  105611. }
  105612. return 0;
  105613. },
  105614. enumerable: true,
  105615. configurable: true
  105616. });
  105617. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  105618. get: function () {
  105619. return this._playMode;
  105620. },
  105621. set: function (value) {
  105622. if (value === this._playMode) {
  105623. return;
  105624. }
  105625. this._playMode = value;
  105626. if (this.state === AnimationState.PLAYING) {
  105627. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  105628. }
  105629. else {
  105630. this._animationGroup.reset();
  105631. this._state = AnimationState.INIT;
  105632. }
  105633. },
  105634. enumerable: true,
  105635. configurable: true
  105636. });
  105637. GroupModelAnimation.prototype.reset = function () {
  105638. this._animationGroup.reset();
  105639. };
  105640. GroupModelAnimation.prototype.restart = function () {
  105641. this._animationGroup.restart();
  105642. };
  105643. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  105644. this._animationGroup['_animatables'].forEach(function (a) {
  105645. a.goToFrame(frameNumber);
  105646. });
  105647. };
  105648. GroupModelAnimation.prototype.start = function () {
  105649. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  105650. if (this._animationGroup.isStarted) {
  105651. this._state = AnimationState.PLAYING;
  105652. }
  105653. };
  105654. GroupModelAnimation.prototype.pause = function () {
  105655. this._animationGroup.pause();
  105656. this._state = AnimationState.PAUSED;
  105657. };
  105658. GroupModelAnimation.prototype.stop = function () {
  105659. this._animationGroup.stop();
  105660. if (!this._animationGroup.isStarted) {
  105661. this._state = AnimationState.STOPPED;
  105662. }
  105663. };
  105664. GroupModelAnimation.prototype.dispose = function () {
  105665. this._animationGroup.dispose();
  105666. };
  105667. return GroupModelAnimation;
  105668. }());
  105669. exports.GroupModelAnimation = GroupModelAnimation;
  105670. /***/ }),
  105671. /* 32 */
  105672. /***/ (function(module, exports, __webpack_require__) {
  105673. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  105674. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  105675. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  105676. 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;
  105677. return c > 3 && r && Object.defineProperty(target, key, r), r;
  105678. };
  105679. var __extends = (this && this.__extends) || (function () {
  105680. var extendStatics = Object.setPrototypeOf ||
  105681. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  105682. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  105683. return function (d, b) {
  105684. extendStatics(d, b);
  105685. function __() { this.constructor = d; }
  105686. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  105687. };
  105688. })();
  105689. (function universalModuleDefinition(root, factory) {
  105690. if(true)
  105691. module.exports = factory(__webpack_require__(0));
  105692. else if(typeof define === 'function' && define.amd)
  105693. define("babylonjs-loaders", ["babylonjs"], factory);
  105694. else if(typeof exports === 'object')
  105695. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  105696. else {
  105697. root["BABYLON"] = factory(root["BABYLON"]);
  105698. }
  105699. })(this, function(BABYLON) {
  105700. "use strict";
  105701. var BABYLON;
  105702. (function (BABYLON) {
  105703. var STLFileLoader = /** @class */ (function () {
  105704. function STLFileLoader() {
  105705. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  105706. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  105707. 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;
  105708. 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;
  105709. this.name = "stl";
  105710. // force data to come in as an ArrayBuffer
  105711. // we'll convert to string if it looks like it's an ASCII .stl
  105712. this.extensions = {
  105713. ".stl": { isBinary: true },
  105714. };
  105715. }
  105716. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105717. var matches;
  105718. if (this.isBinary(data)) {
  105719. // binary .stl
  105720. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  105721. this.parseBinary(babylonMesh, data);
  105722. if (meshes) {
  105723. meshes.push(babylonMesh);
  105724. }
  105725. return true;
  105726. }
  105727. // ASCII .stl
  105728. // convert to string
  105729. var array_buffer = new Uint8Array(data);
  105730. var str = '';
  105731. for (var i = 0; i < data.byteLength; i++) {
  105732. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  105733. }
  105734. data = str;
  105735. while (matches = this.solidPattern.exec(data)) {
  105736. var meshName = matches[1];
  105737. var meshNameFromEnd = matches[3];
  105738. if (meshName != meshNameFromEnd) {
  105739. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  105740. return false;
  105741. }
  105742. // check meshesNames
  105743. if (meshesNames && meshName) {
  105744. if (meshesNames instanceof Array) {
  105745. if (!meshesNames.indexOf(meshName)) {
  105746. continue;
  105747. }
  105748. }
  105749. else {
  105750. if (meshName !== meshesNames) {
  105751. continue;
  105752. }
  105753. }
  105754. }
  105755. // stl mesh name can be empty as well
  105756. meshName = meshName || "stlmesh";
  105757. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  105758. this.parseASCII(babylonMesh, matches[2]);
  105759. if (meshes) {
  105760. meshes.push(babylonMesh);
  105761. }
  105762. }
  105763. return true;
  105764. };
  105765. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  105766. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  105767. if (result) {
  105768. scene.createDefaultCameraOrLight();
  105769. }
  105770. return result;
  105771. };
  105772. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105773. var container = new BABYLON.AssetContainer(scene);
  105774. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105775. container.removeAllFromScene();
  105776. return container;
  105777. };
  105778. STLFileLoader.prototype.isBinary = function (data) {
  105779. // check if file size is correct for binary stl
  105780. var faceSize, nFaces, reader;
  105781. reader = new DataView(data);
  105782. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  105783. nFaces = reader.getUint32(80, true);
  105784. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  105785. return true;
  105786. }
  105787. // check characters higher than ASCII to confirm binary
  105788. var fileLength = reader.byteLength;
  105789. for (var index = 0; index < fileLength; index++) {
  105790. if (reader.getUint8(index) > 127) {
  105791. return true;
  105792. }
  105793. }
  105794. return false;
  105795. };
  105796. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  105797. var reader = new DataView(data);
  105798. var faces = reader.getUint32(80, true);
  105799. var dataOffset = 84;
  105800. var faceLength = 12 * 4 + 2;
  105801. var offset = 0;
  105802. var positions = new Float32Array(faces * 3 * 3);
  105803. var normals = new Float32Array(faces * 3 * 3);
  105804. var indices = new Uint32Array(faces * 3);
  105805. var indicesCount = 0;
  105806. for (var face = 0; face < faces; face++) {
  105807. var start = dataOffset + face * faceLength;
  105808. var normalX = reader.getFloat32(start, true);
  105809. var normalY = reader.getFloat32(start + 4, true);
  105810. var normalZ = reader.getFloat32(start + 8, true);
  105811. for (var i = 1; i <= 3; i++) {
  105812. var vertexstart = start + i * 12;
  105813. // ordering is intentional to match ascii import
  105814. positions[offset] = reader.getFloat32(vertexstart, true);
  105815. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  105816. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  105817. normals[offset] = normalX;
  105818. normals[offset + 2] = normalY;
  105819. normals[offset + 1] = normalZ;
  105820. offset += 3;
  105821. }
  105822. indices[indicesCount] = indicesCount++;
  105823. indices[indicesCount] = indicesCount++;
  105824. indices[indicesCount] = indicesCount++;
  105825. }
  105826. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  105827. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  105828. mesh.setIndices(indices);
  105829. mesh.computeWorldMatrix(true);
  105830. };
  105831. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  105832. var positions = [];
  105833. var normals = [];
  105834. var indices = [];
  105835. var indicesCount = 0;
  105836. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  105837. var matches;
  105838. while (matches = this.facetsPattern.exec(solidData)) {
  105839. var facet = matches[1];
  105840. //one normal per face
  105841. var normalMatches = this.normalPattern.exec(facet);
  105842. this.normalPattern.lastIndex = 0;
  105843. if (!normalMatches) {
  105844. continue;
  105845. }
  105846. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  105847. var vertexMatch;
  105848. while (vertexMatch = this.vertexPattern.exec(facet)) {
  105849. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  105850. normals.push(normal[0], normal[1], normal[2]);
  105851. }
  105852. indices.push(indicesCount++, indicesCount++, indicesCount++);
  105853. this.vertexPattern.lastIndex = 0;
  105854. }
  105855. this.facetsPattern.lastIndex = 0;
  105856. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  105857. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  105858. mesh.setIndices(indices);
  105859. mesh.computeWorldMatrix(true);
  105860. };
  105861. return STLFileLoader;
  105862. }());
  105863. BABYLON.STLFileLoader = STLFileLoader;
  105864. if (BABYLON.SceneLoader) {
  105865. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  105866. }
  105867. })(BABYLON || (BABYLON = {}));
  105868. //# sourceMappingURL=babylon.stlFileLoader.js.map
  105869. "use strict";
  105870. var BABYLON;
  105871. (function (BABYLON) {
  105872. /**
  105873. * Class reading and parsing the MTL file bundled with the obj file.
  105874. */
  105875. var MTLFileLoader = /** @class */ (function () {
  105876. function MTLFileLoader() {
  105877. // All material loaded from the mtl will be set here
  105878. this.materials = [];
  105879. }
  105880. /**
  105881. * This function will read the mtl file and create each material described inside
  105882. * This function could be improve by adding :
  105883. * -some component missing (Ni, Tf...)
  105884. * -including the specific options available
  105885. *
  105886. * @param scene
  105887. * @param data
  105888. * @param rootUrl
  105889. */
  105890. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  105891. //Split the lines from the file
  105892. var lines = data.split('\n');
  105893. //Space char
  105894. var delimiter_pattern = /\s+/;
  105895. //Array with RGB colors
  105896. var color;
  105897. //New material
  105898. var material = null;
  105899. //Look at each line
  105900. for (var i = 0; i < lines.length; i++) {
  105901. var line = lines[i].trim();
  105902. // Blank line or comment
  105903. if (line.length === 0 || line.charAt(0) === '#') {
  105904. continue;
  105905. }
  105906. //Get the first parameter (keyword)
  105907. var pos = line.indexOf(' ');
  105908. var key = (pos >= 0) ? line.substring(0, pos) : line;
  105909. key = key.toLowerCase();
  105910. //Get the data following the key
  105911. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  105912. //This mtl keyword will create the new material
  105913. if (key === "newmtl") {
  105914. //Check if it is the first material.
  105915. // Materials specifications are described after this keyword.
  105916. if (material) {
  105917. //Add the previous material in the material array.
  105918. this.materials.push(material);
  105919. }
  105920. //Create a new material.
  105921. // value is the name of the material read in the mtl file
  105922. material = new BABYLON.StandardMaterial(value, scene);
  105923. }
  105924. else if (key === "kd" && material) {
  105925. // Diffuse color (color under white light) using RGB values
  105926. //value = "r g b"
  105927. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105928. //color = [r,g,b]
  105929. //Set tghe color into the material
  105930. material.diffuseColor = BABYLON.Color3.FromArray(color);
  105931. }
  105932. else if (key === "ka" && material) {
  105933. // Ambient color (color under shadow) using RGB values
  105934. //value = "r g b"
  105935. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105936. //color = [r,g,b]
  105937. //Set tghe color into the material
  105938. material.ambientColor = BABYLON.Color3.FromArray(color);
  105939. }
  105940. else if (key === "ks" && material) {
  105941. // Specular color (color when light is reflected from shiny surface) using RGB values
  105942. //value = "r g b"
  105943. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105944. //color = [r,g,b]
  105945. //Set the color into the material
  105946. material.specularColor = BABYLON.Color3.FromArray(color);
  105947. }
  105948. else if (key === "ke" && material) {
  105949. // Emissive color using RGB values
  105950. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105951. material.emissiveColor = BABYLON.Color3.FromArray(color);
  105952. }
  105953. else if (key === "ns" && material) {
  105954. //value = "Integer"
  105955. material.specularPower = parseFloat(value);
  105956. }
  105957. else if (key === "d" && material) {
  105958. //d is dissolve for current material. It mean alpha for BABYLON
  105959. material.alpha = parseFloat(value);
  105960. //Texture
  105961. //This part can be improved by adding the possible options of texture
  105962. }
  105963. else if (key === "map_ka" && material) {
  105964. // ambient texture map with a loaded image
  105965. //We must first get the folder of the image
  105966. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105967. }
  105968. else if (key === "map_kd" && material) {
  105969. // Diffuse texture map with a loaded image
  105970. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105971. }
  105972. else if (key === "map_ks" && material) {
  105973. // Specular texture map with a loaded image
  105974. //We must first get the folder of the image
  105975. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105976. }
  105977. else if (key === "map_ns") {
  105978. //Specular
  105979. //Specular highlight component
  105980. //We must first get the folder of the image
  105981. //
  105982. //Not supported by BABYLON
  105983. //
  105984. // continue;
  105985. }
  105986. else if (key === "map_bump" && material) {
  105987. //The bump texture
  105988. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105989. }
  105990. else if (key === "map_d" && material) {
  105991. // The dissolve of the material
  105992. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105993. //Options for illumination
  105994. }
  105995. else if (key === "illum") {
  105996. //Illumination
  105997. if (value === "0") {
  105998. //That mean Kd == Kd
  105999. }
  106000. else if (value === "1") {
  106001. //Color on and Ambient on
  106002. }
  106003. else if (value === "2") {
  106004. //Highlight on
  106005. }
  106006. else if (value === "3") {
  106007. //Reflection on and Ray trace on
  106008. }
  106009. else if (value === "4") {
  106010. //Transparency: Glass on, Reflection: Ray trace on
  106011. }
  106012. else if (value === "5") {
  106013. //Reflection: Fresnel on and Ray trace on
  106014. }
  106015. else if (value === "6") {
  106016. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  106017. }
  106018. else if (value === "7") {
  106019. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  106020. }
  106021. else if (value === "8") {
  106022. //Reflection on and Ray trace off
  106023. }
  106024. else if (value === "9") {
  106025. //Transparency: Glass on, Reflection: Ray trace off
  106026. }
  106027. else if (value === "10") {
  106028. //Casts shadows onto invisible surfaces
  106029. }
  106030. }
  106031. else {
  106032. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  106033. }
  106034. }
  106035. //At the end of the file, add the last material
  106036. if (material) {
  106037. this.materials.push(material);
  106038. }
  106039. };
  106040. /**
  106041. * Gets the texture for the material.
  106042. *
  106043. * If the material is imported from input file,
  106044. * We sanitize the url to ensure it takes the textre from aside the material.
  106045. *
  106046. * @param rootUrl The root url to load from
  106047. * @param value The value stored in the mtl
  106048. * @return The Texture
  106049. */
  106050. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  106051. if (!value) {
  106052. return null;
  106053. }
  106054. var url = rootUrl;
  106055. // Load from input file.
  106056. if (rootUrl === "file:") {
  106057. var lastDelimiter = value.lastIndexOf("\\");
  106058. if (lastDelimiter === -1) {
  106059. lastDelimiter = value.lastIndexOf("/");
  106060. }
  106061. if (lastDelimiter > -1) {
  106062. url += value.substr(lastDelimiter + 1);
  106063. }
  106064. else {
  106065. url += value;
  106066. }
  106067. }
  106068. else {
  106069. url += value;
  106070. }
  106071. return new BABYLON.Texture(url, scene);
  106072. };
  106073. return MTLFileLoader;
  106074. }());
  106075. BABYLON.MTLFileLoader = MTLFileLoader;
  106076. var OBJFileLoader = /** @class */ (function () {
  106077. function OBJFileLoader() {
  106078. this.name = "obj";
  106079. this.extensions = ".obj";
  106080. this.obj = /^o/;
  106081. this.group = /^g/;
  106082. this.mtllib = /^mtllib /;
  106083. this.usemtl = /^usemtl /;
  106084. this.smooth = /^s /;
  106085. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  106086. // vn float float float
  106087. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  106088. // vt float float
  106089. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  106090. // f vertex vertex vertex ...
  106091. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  106092. // f vertex/uvs vertex/uvs vertex/uvs ...
  106093. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  106094. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  106095. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  106096. // f vertex//normal vertex//normal vertex//normal ...
  106097. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  106098. }
  106099. /**
  106100. * Calls synchronously the MTL file attached to this obj.
  106101. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  106102. * Without this function materials are not displayed in the first frame (but displayed after).
  106103. * In consequence it is impossible to get material information in your HTML file
  106104. *
  106105. * @param url The URL of the MTL file
  106106. * @param rootUrl
  106107. * @param onSuccess Callback function to be called when the MTL file is loaded
  106108. * @private
  106109. */
  106110. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  106111. //The complete path to the mtl file
  106112. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  106113. // Loads through the babylon tools to allow fileInput search.
  106114. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  106115. };
  106116. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  106117. //get the meshes from OBJ file
  106118. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  106119. //Push meshes from OBJ file into the variable mesh of this function
  106120. if (meshes) {
  106121. loadedMeshes.forEach(function (mesh) {
  106122. meshes.push(mesh);
  106123. });
  106124. }
  106125. return true;
  106126. };
  106127. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  106128. //Get the 3D model
  106129. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  106130. };
  106131. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  106132. var container = new BABYLON.AssetContainer(scene);
  106133. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  106134. container.removeAllFromScene();
  106135. return container;
  106136. };
  106137. /**
  106138. * Read the OBJ file and create an Array of meshes.
  106139. * Each mesh contains all information given by the OBJ and the MTL file.
  106140. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  106141. *
  106142. * @param meshesNames
  106143. * @param scene BABYLON.Scene The scene where are displayed the data
  106144. * @param data String The content of the obj file
  106145. * @param rootUrl String The path to the folder
  106146. * @returns Array<AbstractMesh>
  106147. * @private
  106148. */
  106149. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  106150. var positions = []; //values for the positions of vertices
  106151. var normals = []; //Values for the normals
  106152. var uvs = []; //Values for the textures
  106153. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  106154. var handledMesh; //The current mesh of meshes array
  106155. var indicesForBabylon = []; //The list of indices for VertexData
  106156. var wrappedPositionForBabylon = []; //The list of position in vectors
  106157. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  106158. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  106159. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  106160. var curPositionInIndices = 0;
  106161. var hasMeshes = false; //Meshes are defined in the file
  106162. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  106163. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  106164. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  106165. var triangles = []; //Indices from new triangles coming from polygons
  106166. var materialNameFromObj = ""; //The name of the current material
  106167. var fileToLoad = ""; //The name of the mtlFile to load
  106168. var materialsFromMTLFile = new MTLFileLoader();
  106169. var objMeshName = ""; //The name of the current obj mesh
  106170. var increment = 1; //Id for meshes created by the multimaterial
  106171. var isFirstMaterial = true;
  106172. /**
  106173. * Search for obj in the given array.
  106174. * This function is called to check if a couple of data already exists in an array.
  106175. *
  106176. * If found, returns the index of the founded tuple index. Returns -1 if not found
  106177. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  106178. * @param obj Array<number>
  106179. * @returns {boolean}
  106180. */
  106181. var isInArray = function (arr, obj) {
  106182. if (!arr[obj[0]])
  106183. arr[obj[0]] = { normals: [], idx: [] };
  106184. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  106185. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  106186. };
  106187. var isInArrayUV = function (arr, obj) {
  106188. if (!arr[obj[0]])
  106189. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  106190. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  106191. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  106192. return arr[obj[0]].idx[idx];
  106193. }
  106194. return -1;
  106195. };
  106196. /**
  106197. * This function set the data for each triangle.
  106198. * Data are position, normals and uvs
  106199. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  106200. * If the tuple already exist, add only their indice
  106201. *
  106202. * @param indicePositionFromObj Integer The index in positions array
  106203. * @param indiceUvsFromObj Integer The index in uvs array
  106204. * @param indiceNormalFromObj Integer The index in normals array
  106205. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  106206. * @param textureVectorFromOBJ Vector3 The value of uvs
  106207. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  106208. */
  106209. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  106210. //Check if this tuple already exists in the list of tuples
  106211. var _index;
  106212. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  106213. _index = isInArrayUV(tuplePosNorm, [
  106214. indicePositionFromObj,
  106215. indiceNormalFromObj,
  106216. indiceUvsFromObj
  106217. ]);
  106218. }
  106219. else {
  106220. _index = isInArray(tuplePosNorm, [
  106221. indicePositionFromObj,
  106222. indiceNormalFromObj
  106223. ]);
  106224. }
  106225. //If it not exists
  106226. if (_index == -1) {
  106227. //Add an new indice.
  106228. //The array of indices is only an array with his length equal to the number of triangles - 1.
  106229. //We add vertices data in this order
  106230. indicesForBabylon.push(wrappedPositionForBabylon.length);
  106231. //Push the position of vertice for Babylon
  106232. //Each element is a BABYLON.Vector3(x,y,z)
  106233. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  106234. //Push the uvs for Babylon
  106235. //Each element is a BABYLON.Vector3(u,v)
  106236. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  106237. //Push the normals for Babylon
  106238. //Each element is a BABYLON.Vector3(x,y,z)
  106239. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  106240. //Add the tuple in the comparison list
  106241. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  106242. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  106243. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  106244. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  106245. }
  106246. else {
  106247. //The tuple already exists
  106248. //Add the index of the already existing tuple
  106249. //At this index we can get the value of position, normal and uvs of vertex
  106250. indicesForBabylon.push(_index);
  106251. }
  106252. };
  106253. /**
  106254. * Transform BABYLON.Vector() object onto 3 digits in an array
  106255. */
  106256. var unwrapData = function () {
  106257. //Every array has the same length
  106258. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  106259. //Push the x, y, z values of each element in the unwrapped array
  106260. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  106261. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  106262. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  106263. }
  106264. // Reset arrays for the next new meshes
  106265. wrappedPositionForBabylon = [];
  106266. wrappedNormalsForBabylon = [];
  106267. wrappedUvsForBabylon = [];
  106268. tuplePosNorm = [];
  106269. curPositionInIndices = 0;
  106270. };
  106271. /**
  106272. * Create triangles from polygons by recursion
  106273. * The best to understand how it works is to draw it in the same time you get the recursion.
  106274. * It is important to notice that a triangle is a polygon
  106275. * We get 4 patterns of face defined in OBJ File :
  106276. * facePattern1 = ["1","2","3","4","5","6"]
  106277. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  106278. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  106279. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  106280. * Each pattern is divided by the same method
  106281. * @param face Array[String] The indices of elements
  106282. * @param v Integer The variable to increment
  106283. */
  106284. var getTriangles = function (face, v) {
  106285. //Work for each element of the array
  106286. if (v + 1 < face.length) {
  106287. //Add on the triangle variable the indexes to obtain triangles
  106288. triangles.push(face[0], face[v], face[v + 1]);
  106289. //Incrementation for recursion
  106290. v += 1;
  106291. //Recursion
  106292. getTriangles(face, v);
  106293. }
  106294. //Result obtained after 2 iterations:
  106295. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  106296. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  106297. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  106298. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  106299. };
  106300. /**
  106301. * Create triangles and push the data for each polygon for the pattern 1
  106302. * In this pattern we get vertice positions
  106303. * @param face
  106304. * @param v
  106305. */
  106306. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  106307. //Get the indices of triangles for each polygon
  106308. getTriangles(face, v);
  106309. //For each element in the triangles array.
  106310. //This var could contains 1 to an infinity of triangles
  106311. for (var k = 0; k < triangles.length; k++) {
  106312. // Set position indice
  106313. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  106314. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  106315. positions[indicePositionFromObj], //Get the vectors data
  106316. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  106317. );
  106318. }
  106319. //Reset variable for the next line
  106320. triangles = [];
  106321. };
  106322. /**
  106323. * Create triangles and push the data for each polygon for the pattern 2
  106324. * In this pattern we get vertice positions and uvsu
  106325. * @param face
  106326. * @param v
  106327. */
  106328. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  106329. //Get the indices of triangles for each polygon
  106330. getTriangles(face, v);
  106331. for (var k = 0; k < triangles.length; k++) {
  106332. //triangle[k] = "1/1"
  106333. //Split the data for getting position and uv
  106334. var point = triangles[k].split("/"); // ["1", "1"]
  106335. //Set position indice
  106336. var indicePositionFromObj = parseInt(point[0]) - 1;
  106337. //Set uv indice
  106338. var indiceUvsFromObj = parseInt(point[1]) - 1;
  106339. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  106340. positions[indicePositionFromObj], //Get the values for each element
  106341. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  106342. );
  106343. }
  106344. //Reset variable for the next line
  106345. triangles = [];
  106346. };
  106347. /**
  106348. * Create triangles and push the data for each polygon for the pattern 3
  106349. * In this pattern we get vertice positions, uvs and normals
  106350. * @param face
  106351. * @param v
  106352. */
  106353. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  106354. //Get the indices of triangles for each polygon
  106355. getTriangles(face, v);
  106356. for (var k = 0; k < triangles.length; k++) {
  106357. //triangle[k] = "1/1/1"
  106358. //Split the data for getting position, uv, and normals
  106359. var point = triangles[k].split("/"); // ["1", "1", "1"]
  106360. // Set position indice
  106361. var indicePositionFromObj = parseInt(point[0]) - 1;
  106362. // Set uv indice
  106363. var indiceUvsFromObj = parseInt(point[1]) - 1;
  106364. // Set normal indice
  106365. var indiceNormalFromObj = parseInt(point[2]) - 1;
  106366. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  106367. );
  106368. }
  106369. //Reset variable for the next line
  106370. triangles = [];
  106371. };
  106372. /**
  106373. * Create triangles and push the data for each polygon for the pattern 4
  106374. * In this pattern we get vertice positions and normals
  106375. * @param face
  106376. * @param v
  106377. */
  106378. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  106379. getTriangles(face, v);
  106380. for (var k = 0; k < triangles.length; k++) {
  106381. //triangle[k] = "1//1"
  106382. //Split the data for getting position and normals
  106383. var point = triangles[k].split("//"); // ["1", "1"]
  106384. // We check indices, and normals
  106385. var indicePositionFromObj = parseInt(point[0]) - 1;
  106386. var indiceNormalFromObj = parseInt(point[1]) - 1;
  106387. setData(indicePositionFromObj, 1, //Default value for uv
  106388. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  106389. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  106390. }
  106391. //Reset variable for the next line
  106392. triangles = [];
  106393. };
  106394. var addPreviousObjMesh = function () {
  106395. //Check if it is not the first mesh. Otherwise we don't have data.
  106396. if (meshesFromObj.length > 0) {
  106397. //Get the previous mesh for applying the data about the faces
  106398. //=> in obj file, faces definition append after the name of the mesh
  106399. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  106400. //Set the data into Array for the mesh
  106401. unwrapData();
  106402. // Reverse tab. Otherwise face are displayed in the wrong sens
  106403. indicesForBabylon.reverse();
  106404. //Set the information for the mesh
  106405. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  106406. handledMesh.indices = indicesForBabylon.slice();
  106407. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  106408. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  106409. handledMesh.uvs = unwrappedUVForBabylon.slice();
  106410. //Reset the array for the next mesh
  106411. indicesForBabylon = [];
  106412. unwrappedPositionsForBabylon = [];
  106413. unwrappedNormalsForBabylon = [];
  106414. unwrappedUVForBabylon = [];
  106415. }
  106416. };
  106417. //Main function
  106418. //Split the file into lines
  106419. var lines = data.split('\n');
  106420. //Look at each line
  106421. for (var i = 0; i < lines.length; i++) {
  106422. var line = lines[i].trim();
  106423. var result;
  106424. //Comment or newLine
  106425. if (line.length === 0 || line.charAt(0) === '#') {
  106426. continue;
  106427. //Get information about one position possible for the vertices
  106428. }
  106429. else if ((result = this.vertexPattern.exec(line)) !== null) {
  106430. //Create a Vector3 with the position x, y, z
  106431. //Value of result:
  106432. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  106433. //Add the Vector in the list of positions
  106434. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  106435. }
  106436. else if ((result = this.normalPattern.exec(line)) !== null) {
  106437. //Create a Vector3 with the normals x, y, z
  106438. //Value of result
  106439. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  106440. //Add the Vector in the list of normals
  106441. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  106442. }
  106443. else if ((result = this.uvPattern.exec(line)) !== null) {
  106444. //Create a Vector2 with the normals u, v
  106445. //Value of result
  106446. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  106447. //Add the Vector in the list of uvs
  106448. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  106449. //Identify patterns of faces
  106450. //Face could be defined in different type of pattern
  106451. }
  106452. else if ((result = this.facePattern3.exec(line)) !== null) {
  106453. //Value of result:
  106454. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  106455. //Set the data for this face
  106456. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  106457. 1);
  106458. }
  106459. else if ((result = this.facePattern4.exec(line)) !== null) {
  106460. //Value of result:
  106461. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  106462. //Set the data for this face
  106463. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  106464. 1);
  106465. }
  106466. else if ((result = this.facePattern2.exec(line)) !== null) {
  106467. //Value of result:
  106468. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  106469. //Set the data for this face
  106470. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  106471. 1);
  106472. }
  106473. else if ((result = this.facePattern1.exec(line)) !== null) {
  106474. //Value of result
  106475. //["f 1 2 3", "1 2 3"...]
  106476. //Set the data for this face
  106477. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  106478. 1);
  106479. //Define a mesh or an object
  106480. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  106481. }
  106482. else if (this.group.test(line) || this.obj.test(line)) {
  106483. //Create a new mesh corresponding to the name of the group.
  106484. //Definition of the mesh
  106485. var objMesh =
  106486. //Set the name of the current obj mesh
  106487. {
  106488. name: line.substring(2).trim(),
  106489. indices: undefined,
  106490. positions: undefined,
  106491. normals: undefined,
  106492. uvs: undefined,
  106493. materialName: ""
  106494. };
  106495. addPreviousObjMesh();
  106496. //Push the last mesh created with only the name
  106497. meshesFromObj.push(objMesh);
  106498. //Set this variable to indicate that now meshesFromObj has objects defined inside
  106499. hasMeshes = true;
  106500. isFirstMaterial = true;
  106501. increment = 1;
  106502. //Keyword for applying a material
  106503. }
  106504. else if (this.usemtl.test(line)) {
  106505. //Get the name of the material
  106506. materialNameFromObj = line.substring(7).trim();
  106507. //If this new material is in the same mesh
  106508. if (!isFirstMaterial) {
  106509. //Set the data for the previous mesh
  106510. addPreviousObjMesh();
  106511. //Create a new mesh
  106512. var objMesh =
  106513. //Set the name of the current obj mesh
  106514. {
  106515. name: objMeshName + "_mm" + increment.toString(),
  106516. indices: undefined,
  106517. positions: undefined,
  106518. normals: undefined,
  106519. uvs: undefined,
  106520. materialName: materialNameFromObj
  106521. };
  106522. increment++;
  106523. //If meshes are already defined
  106524. meshesFromObj.push(objMesh);
  106525. }
  106526. //Set the material name if the previous line define a mesh
  106527. if (hasMeshes && isFirstMaterial) {
  106528. //Set the material name to the previous mesh (1 material per mesh)
  106529. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  106530. isFirstMaterial = false;
  106531. }
  106532. //Keyword for loading the mtl file
  106533. }
  106534. else if (this.mtllib.test(line)) {
  106535. //Get the name of mtl file
  106536. fileToLoad = line.substring(7).trim();
  106537. //Apply smoothing
  106538. }
  106539. else if (this.smooth.test(line)) {
  106540. // smooth shading => apply smoothing
  106541. //Toda y I don't know it work with babylon and with obj.
  106542. //With the obj file an integer is set
  106543. }
  106544. else {
  106545. //If there is another possibility
  106546. console.log("Unhandled expression at line : " + line);
  106547. }
  106548. }
  106549. //At the end of the file, add the last mesh into the meshesFromObj array
  106550. if (hasMeshes) {
  106551. //Set the data for the last mesh
  106552. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  106553. //Reverse indices for displaying faces in the good sens
  106554. indicesForBabylon.reverse();
  106555. //Get the good array
  106556. unwrapData();
  106557. //Set array
  106558. handledMesh.indices = indicesForBabylon;
  106559. handledMesh.positions = unwrappedPositionsForBabylon;
  106560. handledMesh.normals = unwrappedNormalsForBabylon;
  106561. handledMesh.uvs = unwrappedUVForBabylon;
  106562. }
  106563. //If any o or g keyword found, create a mesj with a random id
  106564. if (!hasMeshes) {
  106565. // reverse tab of indices
  106566. indicesForBabylon.reverse();
  106567. //Get positions normals uvs
  106568. unwrapData();
  106569. //Set data for one mesh
  106570. meshesFromObj.push({
  106571. name: BABYLON.Geometry.RandomId(),
  106572. indices: indicesForBabylon,
  106573. positions: unwrappedPositionsForBabylon,
  106574. normals: unwrappedNormalsForBabylon,
  106575. uvs: unwrappedUVForBabylon,
  106576. materialName: materialNameFromObj
  106577. });
  106578. }
  106579. //Create a BABYLON.Mesh list
  106580. var babylonMeshesArray = []; //The mesh for babylon
  106581. var materialToUse = new Array();
  106582. //Set data for each mesh
  106583. for (var j = 0; j < meshesFromObj.length; j++) {
  106584. //check meshesNames (stlFileLoader)
  106585. if (meshesNames && meshesFromObj[j].name) {
  106586. if (meshesNames instanceof Array) {
  106587. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  106588. continue;
  106589. }
  106590. }
  106591. else {
  106592. if (meshesFromObj[j].name !== meshesNames) {
  106593. continue;
  106594. }
  106595. }
  106596. }
  106597. //Get the current mesh
  106598. //Set the data with VertexBuffer for each mesh
  106599. handledMesh = meshesFromObj[j];
  106600. //Create a BABYLON.Mesh with the name of the obj mesh
  106601. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  106602. //Push the name of the material to an array
  106603. //This is indispensable for the importMesh function
  106604. materialToUse.push(meshesFromObj[j].materialName);
  106605. var vertexData = new BABYLON.VertexData(); //The container for the values
  106606. //Set the data for the babylonMesh
  106607. vertexData.positions = handledMesh.positions;
  106608. vertexData.normals = handledMesh.normals;
  106609. vertexData.uvs = handledMesh.uvs;
  106610. vertexData.indices = handledMesh.indices;
  106611. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  106612. vertexData.applyToMesh(babylonMesh);
  106613. //Push the mesh into an array
  106614. babylonMeshesArray.push(babylonMesh);
  106615. }
  106616. //load the materials
  106617. //Check if we have a file to load
  106618. if (fileToLoad !== "") {
  106619. //Load the file synchronously
  106620. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  106621. //Create materials thanks MTLLoader function
  106622. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  106623. //Look at each material loaded in the mtl file
  106624. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  106625. //Three variables to get all meshes with the same material
  106626. var startIndex = 0;
  106627. var _indices = [];
  106628. var _index;
  106629. //The material from MTL file is used in the meshes loaded
  106630. //Push the indice in an array
  106631. //Check if the material is not used for another mesh
  106632. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  106633. _indices.push(_index);
  106634. startIndex = _index + 1;
  106635. }
  106636. //If the material is not used dispose it
  106637. if (_index == -1 && _indices.length == 0) {
  106638. //If the material is not needed, remove it
  106639. materialsFromMTLFile.materials[n].dispose();
  106640. }
  106641. else {
  106642. for (var o = 0; o < _indices.length; o++) {
  106643. //Apply the material to the BABYLON.Mesh for each mesh with the material
  106644. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  106645. }
  106646. }
  106647. }
  106648. });
  106649. }
  106650. //Return an array with all BABYLON.Mesh
  106651. return babylonMeshesArray;
  106652. };
  106653. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  106654. return OBJFileLoader;
  106655. }());
  106656. BABYLON.OBJFileLoader = OBJFileLoader;
  106657. if (BABYLON.SceneLoader) {
  106658. //Add this loader into the register plugin
  106659. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  106660. }
  106661. })(BABYLON || (BABYLON = {}));
  106662. //# sourceMappingURL=babylon.objFileLoader.js.map
  106663. "use strict";
  106664. var BABYLON;
  106665. (function (BABYLON) {
  106666. var GLTFLoaderCoordinateSystemMode;
  106667. (function (GLTFLoaderCoordinateSystemMode) {
  106668. /**
  106669. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  106670. */
  106671. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  106672. /**
  106673. * Sets the useRightHandedSystem flag on the scene.
  106674. */
  106675. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  106676. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  106677. var GLTFLoaderAnimationStartMode;
  106678. (function (GLTFLoaderAnimationStartMode) {
  106679. /**
  106680. * No animation will start.
  106681. */
  106682. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  106683. /**
  106684. * The first animation will start.
  106685. */
  106686. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  106687. /**
  106688. * All animations will start.
  106689. */
  106690. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  106691. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  106692. var GLTFLoaderState;
  106693. (function (GLTFLoaderState) {
  106694. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  106695. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  106696. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  106697. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  106698. var GLTFFileLoader = /** @class */ (function () {
  106699. function GLTFFileLoader() {
  106700. // #region Common options
  106701. /**
  106702. * Raised when the asset has been parsed.
  106703. * The data.json property stores the glTF JSON.
  106704. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  106705. */
  106706. this.onParsedObservable = new BABYLON.Observable();
  106707. // #endregion
  106708. // #region V2 options
  106709. /**
  106710. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  106711. */
  106712. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  106713. /**
  106714. * The animation start mode (NONE, FIRST, ALL).
  106715. */
  106716. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  106717. /**
  106718. * Set to true to compile materials before raising the success callback.
  106719. */
  106720. this.compileMaterials = false;
  106721. /**
  106722. * Set to true to also compile materials with clip planes.
  106723. */
  106724. this.useClipPlane = false;
  106725. /**
  106726. * Set to true to compile shadow generators before raising the success callback.
  106727. */
  106728. this.compileShadowGenerators = false;
  106729. /**
  106730. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  106731. */
  106732. this.onMeshLoadedObservable = new BABYLON.Observable();
  106733. /**
  106734. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  106735. */
  106736. this.onTextureLoadedObservable = new BABYLON.Observable();
  106737. /**
  106738. * Raised when the loader creates a material after parsing the glTF properties of the material.
  106739. */
  106740. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106741. /**
  106742. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  106743. */
  106744. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  106745. /**
  106746. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  106747. * For assets with LODs, raised when all of the LODs are complete.
  106748. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  106749. */
  106750. this.onCompleteObservable = new BABYLON.Observable();
  106751. /**
  106752. * Raised when the loader is disposed.
  106753. */
  106754. this.onDisposeObservable = new BABYLON.Observable();
  106755. /**
  106756. * Raised after a loader extension is created.
  106757. * Set additional options for a loader extension in this event.
  106758. */
  106759. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106760. // #endregion
  106761. this._loader = null;
  106762. this.name = "gltf";
  106763. this.extensions = {
  106764. ".gltf": { isBinary: false },
  106765. ".glb": { isBinary: true }
  106766. };
  106767. }
  106768. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  106769. set: function (callback) {
  106770. if (this._onParsedObserver) {
  106771. this.onParsedObservable.remove(this._onParsedObserver);
  106772. }
  106773. this._onParsedObserver = this.onParsedObservable.add(callback);
  106774. },
  106775. enumerable: true,
  106776. configurable: true
  106777. });
  106778. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  106779. set: function (callback) {
  106780. if (this._onMeshLoadedObserver) {
  106781. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  106782. }
  106783. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  106784. },
  106785. enumerable: true,
  106786. configurable: true
  106787. });
  106788. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  106789. set: function (callback) {
  106790. if (this._onTextureLoadedObserver) {
  106791. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  106792. }
  106793. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  106794. },
  106795. enumerable: true,
  106796. configurable: true
  106797. });
  106798. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  106799. set: function (callback) {
  106800. if (this._onMaterialLoadedObserver) {
  106801. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  106802. }
  106803. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  106804. },
  106805. enumerable: true,
  106806. configurable: true
  106807. });
  106808. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  106809. set: function (callback) {
  106810. if (this._onAnimationGroupLoadedObserver) {
  106811. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  106812. }
  106813. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  106814. },
  106815. enumerable: true,
  106816. configurable: true
  106817. });
  106818. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  106819. set: function (callback) {
  106820. if (this._onCompleteObserver) {
  106821. this.onCompleteObservable.remove(this._onCompleteObserver);
  106822. }
  106823. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  106824. },
  106825. enumerable: true,
  106826. configurable: true
  106827. });
  106828. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  106829. set: function (callback) {
  106830. if (this._onDisposeObserver) {
  106831. this.onDisposeObservable.remove(this._onDisposeObserver);
  106832. }
  106833. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  106834. },
  106835. enumerable: true,
  106836. configurable: true
  106837. });
  106838. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  106839. set: function (callback) {
  106840. if (this._onExtensionLoadedObserver) {
  106841. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  106842. }
  106843. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  106844. },
  106845. enumerable: true,
  106846. configurable: true
  106847. });
  106848. /**
  106849. * Gets a promise that resolves when the asset is completely loaded.
  106850. * @returns A promise that resolves when the asset is completely loaded.
  106851. */
  106852. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  106853. var _this = this;
  106854. return new Promise(function (resolve) {
  106855. _this.onCompleteObservable.add(function () {
  106856. resolve();
  106857. }, undefined, undefined, undefined, true);
  106858. });
  106859. };
  106860. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  106861. /**
  106862. * The loader state or null if not active.
  106863. */
  106864. get: function () {
  106865. return this._loader ? this._loader.state : null;
  106866. },
  106867. enumerable: true,
  106868. configurable: true
  106869. });
  106870. /**
  106871. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  106872. */
  106873. GLTFFileLoader.prototype.dispose = function () {
  106874. if (this._loader) {
  106875. this._loader.dispose();
  106876. this._loader = null;
  106877. }
  106878. this.onMeshLoadedObservable.clear();
  106879. this.onTextureLoadedObservable.clear();
  106880. this.onMaterialLoadedObservable.clear();
  106881. this.onDisposeObservable.notifyObservers(this);
  106882. this.onDisposeObservable.clear();
  106883. };
  106884. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106885. var _this = this;
  106886. return Promise.resolve().then(function () {
  106887. var loaderData = _this._parse(data);
  106888. _this._loader = _this._getLoader(loaderData);
  106889. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  106890. });
  106891. };
  106892. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106893. var _this = this;
  106894. return Promise.resolve().then(function () {
  106895. var loaderData = _this._parse(data);
  106896. _this._loader = _this._getLoader(loaderData);
  106897. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  106898. });
  106899. };
  106900. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  106901. var _this = this;
  106902. return Promise.resolve().then(function () {
  106903. var loaderData = _this._parse(data);
  106904. _this._loader = _this._getLoader(loaderData);
  106905. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  106906. var container = new BABYLON.AssetContainer(scene);
  106907. Array.prototype.push.apply(container.meshes, result.meshes);
  106908. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  106909. Array.prototype.push.apply(container.skeletons, result.skeletons);
  106910. container.removeAllFromScene();
  106911. return container;
  106912. });
  106913. });
  106914. };
  106915. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  106916. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  106917. };
  106918. GLTFFileLoader.prototype.createPlugin = function () {
  106919. return new GLTFFileLoader();
  106920. };
  106921. GLTFFileLoader.prototype._parse = function (data) {
  106922. var parsedData;
  106923. if (data instanceof ArrayBuffer) {
  106924. parsedData = GLTFFileLoader._parseBinary(data);
  106925. }
  106926. else {
  106927. parsedData = {
  106928. json: JSON.parse(data),
  106929. bin: null
  106930. };
  106931. }
  106932. this.onParsedObservable.notifyObservers(parsedData);
  106933. this.onParsedObservable.clear();
  106934. return parsedData;
  106935. };
  106936. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  106937. var _this = this;
  106938. var loaderVersion = { major: 2, minor: 0 };
  106939. var asset = loaderData.json.asset || {};
  106940. var version = GLTFFileLoader._parseVersion(asset.version);
  106941. if (!version) {
  106942. throw new Error("Invalid version: " + asset.version);
  106943. }
  106944. if (asset.minVersion !== undefined) {
  106945. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  106946. if (!minVersion) {
  106947. throw new Error("Invalid minimum version: " + asset.minVersion);
  106948. }
  106949. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  106950. throw new Error("Incompatible minimum version: " + asset.minVersion);
  106951. }
  106952. }
  106953. var createLoaders = {
  106954. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  106955. 2: GLTFFileLoader.CreateGLTFLoaderV2
  106956. };
  106957. var createLoader = createLoaders[version.major];
  106958. if (!createLoader) {
  106959. throw new Error("Unsupported version: " + asset.version);
  106960. }
  106961. var loader = createLoader();
  106962. loader.coordinateSystemMode = this.coordinateSystemMode;
  106963. loader.animationStartMode = this.animationStartMode;
  106964. loader.compileMaterials = this.compileMaterials;
  106965. loader.useClipPlane = this.useClipPlane;
  106966. loader.compileShadowGenerators = this.compileShadowGenerators;
  106967. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  106968. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  106969. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  106970. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  106971. loader.onCompleteObservable.add(function () {
  106972. _this.onMeshLoadedObservable.clear();
  106973. _this.onTextureLoadedObservable.clear();
  106974. _this.onMaterialLoadedObservable.clear();
  106975. _this.onCompleteObservable.notifyObservers(_this);
  106976. _this.onCompleteObservable.clear();
  106977. });
  106978. return loader;
  106979. };
  106980. GLTFFileLoader._parseBinary = function (data) {
  106981. var Binary = {
  106982. Magic: 0x46546C67
  106983. };
  106984. var binaryReader = new BinaryReader(data);
  106985. var magic = binaryReader.readUint32();
  106986. if (magic !== Binary.Magic) {
  106987. throw new Error("Unexpected magic: " + magic);
  106988. }
  106989. var version = binaryReader.readUint32();
  106990. switch (version) {
  106991. case 1: return GLTFFileLoader._parseV1(binaryReader);
  106992. case 2: return GLTFFileLoader._parseV2(binaryReader);
  106993. }
  106994. throw new Error("Unsupported version: " + version);
  106995. };
  106996. GLTFFileLoader._parseV1 = function (binaryReader) {
  106997. var ContentFormat = {
  106998. JSON: 0
  106999. };
  107000. var length = binaryReader.readUint32();
  107001. if (length != binaryReader.getLength()) {
  107002. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  107003. }
  107004. var contentLength = binaryReader.readUint32();
  107005. var contentFormat = binaryReader.readUint32();
  107006. var content;
  107007. switch (contentFormat) {
  107008. case ContentFormat.JSON: {
  107009. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  107010. break;
  107011. }
  107012. default: {
  107013. throw new Error("Unexpected content format: " + contentFormat);
  107014. }
  107015. }
  107016. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  107017. var body = binaryReader.readUint8Array(bytesRemaining);
  107018. return {
  107019. json: content,
  107020. bin: body
  107021. };
  107022. };
  107023. GLTFFileLoader._parseV2 = function (binaryReader) {
  107024. var ChunkFormat = {
  107025. JSON: 0x4E4F534A,
  107026. BIN: 0x004E4942
  107027. };
  107028. var length = binaryReader.readUint32();
  107029. if (length !== binaryReader.getLength()) {
  107030. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  107031. }
  107032. // JSON chunk
  107033. var chunkLength = binaryReader.readUint32();
  107034. var chunkFormat = binaryReader.readUint32();
  107035. if (chunkFormat !== ChunkFormat.JSON) {
  107036. throw new Error("First chunk format is not JSON");
  107037. }
  107038. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  107039. // Look for BIN chunk
  107040. var bin = null;
  107041. while (binaryReader.getPosition() < binaryReader.getLength()) {
  107042. var chunkLength_1 = binaryReader.readUint32();
  107043. var chunkFormat_1 = binaryReader.readUint32();
  107044. switch (chunkFormat_1) {
  107045. case ChunkFormat.JSON: {
  107046. throw new Error("Unexpected JSON chunk");
  107047. }
  107048. case ChunkFormat.BIN: {
  107049. bin = binaryReader.readUint8Array(chunkLength_1);
  107050. break;
  107051. }
  107052. default: {
  107053. // ignore unrecognized chunkFormat
  107054. binaryReader.skipBytes(chunkLength_1);
  107055. break;
  107056. }
  107057. }
  107058. }
  107059. return {
  107060. json: json,
  107061. bin: bin
  107062. };
  107063. };
  107064. GLTFFileLoader._parseVersion = function (version) {
  107065. if (version === "1.0" || version === "1.0.1") {
  107066. return {
  107067. major: 1,
  107068. minor: 0
  107069. };
  107070. }
  107071. var match = (version + "").match(/^(\d+)\.(\d+)/);
  107072. if (!match) {
  107073. return null;
  107074. }
  107075. return {
  107076. major: parseInt(match[1]),
  107077. minor: parseInt(match[2])
  107078. };
  107079. };
  107080. GLTFFileLoader._compareVersion = function (a, b) {
  107081. if (a.major > b.major)
  107082. return 1;
  107083. if (a.major < b.major)
  107084. return -1;
  107085. if (a.minor > b.minor)
  107086. return 1;
  107087. if (a.minor < b.minor)
  107088. return -1;
  107089. return 0;
  107090. };
  107091. GLTFFileLoader._decodeBufferToText = function (buffer) {
  107092. var result = "";
  107093. var length = buffer.byteLength;
  107094. for (var i = 0; i < length; i++) {
  107095. result += String.fromCharCode(buffer[i]);
  107096. }
  107097. return result;
  107098. };
  107099. // #endregion
  107100. // #region V1 options
  107101. GLTFFileLoader.IncrementalLoading = true;
  107102. GLTFFileLoader.HomogeneousCoordinates = false;
  107103. return GLTFFileLoader;
  107104. }());
  107105. BABYLON.GLTFFileLoader = GLTFFileLoader;
  107106. var BinaryReader = /** @class */ (function () {
  107107. function BinaryReader(arrayBuffer) {
  107108. this._arrayBuffer = arrayBuffer;
  107109. this._dataView = new DataView(arrayBuffer);
  107110. this._byteOffset = 0;
  107111. }
  107112. BinaryReader.prototype.getPosition = function () {
  107113. return this._byteOffset;
  107114. };
  107115. BinaryReader.prototype.getLength = function () {
  107116. return this._arrayBuffer.byteLength;
  107117. };
  107118. BinaryReader.prototype.readUint32 = function () {
  107119. var value = this._dataView.getUint32(this._byteOffset, true);
  107120. this._byteOffset += 4;
  107121. return value;
  107122. };
  107123. BinaryReader.prototype.readUint8Array = function (length) {
  107124. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  107125. this._byteOffset += length;
  107126. return value;
  107127. };
  107128. BinaryReader.prototype.skipBytes = function (length) {
  107129. this._byteOffset += length;
  107130. };
  107131. return BinaryReader;
  107132. }());
  107133. if (BABYLON.SceneLoader) {
  107134. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  107135. }
  107136. })(BABYLON || (BABYLON = {}));
  107137. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  107138. "use strict";
  107139. var BABYLON;
  107140. (function (BABYLON) {
  107141. var GLTF1;
  107142. (function (GLTF1) {
  107143. /**
  107144. * Enums
  107145. */
  107146. var EComponentType;
  107147. (function (EComponentType) {
  107148. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  107149. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  107150. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  107151. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  107152. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  107153. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  107154. var EShaderType;
  107155. (function (EShaderType) {
  107156. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  107157. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  107158. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  107159. var EParameterType;
  107160. (function (EParameterType) {
  107161. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  107162. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  107163. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  107164. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  107165. EParameterType[EParameterType["INT"] = 5124] = "INT";
  107166. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  107167. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  107168. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  107169. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  107170. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  107171. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  107172. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  107173. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  107174. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  107175. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  107176. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  107177. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  107178. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  107179. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  107180. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  107181. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  107182. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  107183. var ETextureWrapMode;
  107184. (function (ETextureWrapMode) {
  107185. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  107186. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  107187. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  107188. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  107189. var ETextureFilterType;
  107190. (function (ETextureFilterType) {
  107191. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  107192. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  107193. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  107194. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  107195. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  107196. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  107197. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  107198. var ETextureFormat;
  107199. (function (ETextureFormat) {
  107200. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  107201. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  107202. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  107203. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  107204. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  107205. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  107206. var ECullingType;
  107207. (function (ECullingType) {
  107208. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  107209. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  107210. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  107211. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  107212. var EBlendingFunction;
  107213. (function (EBlendingFunction) {
  107214. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  107215. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  107216. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  107217. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  107218. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  107219. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  107220. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  107221. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  107222. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  107223. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  107224. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  107225. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  107226. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  107227. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  107228. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  107229. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  107230. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107231. })(BABYLON || (BABYLON = {}));
  107232. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  107233. "use strict";
  107234. var BABYLON;
  107235. (function (BABYLON) {
  107236. var GLTF1;
  107237. (function (GLTF1) {
  107238. /**
  107239. * Tokenizer. Used for shaders compatibility
  107240. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  107241. */
  107242. var ETokenType;
  107243. (function (ETokenType) {
  107244. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  107245. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  107246. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  107247. })(ETokenType || (ETokenType = {}));
  107248. var Tokenizer = /** @class */ (function () {
  107249. function Tokenizer(toParse) {
  107250. this._pos = 0;
  107251. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  107252. this._toParse = toParse;
  107253. this._maxPos = toParse.length;
  107254. }
  107255. Tokenizer.prototype.getNextToken = function () {
  107256. if (this.isEnd())
  107257. return ETokenType.END_OF_INPUT;
  107258. this.currentString = this.read();
  107259. this.currentToken = ETokenType.UNKNOWN;
  107260. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  107261. this.currentToken = ETokenType.IDENTIFIER;
  107262. this.currentIdentifier = this.currentString;
  107263. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  107264. this.currentIdentifier += this.currentString;
  107265. this.forward();
  107266. }
  107267. }
  107268. return this.currentToken;
  107269. };
  107270. Tokenizer.prototype.peek = function () {
  107271. return this._toParse[this._pos];
  107272. };
  107273. Tokenizer.prototype.read = function () {
  107274. return this._toParse[this._pos++];
  107275. };
  107276. Tokenizer.prototype.forward = function () {
  107277. this._pos++;
  107278. };
  107279. Tokenizer.prototype.isEnd = function () {
  107280. return this._pos >= this._maxPos;
  107281. };
  107282. return Tokenizer;
  107283. }());
  107284. /**
  107285. * Values
  107286. */
  107287. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  107288. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  107289. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  107290. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  107291. /**
  107292. * Parse
  107293. */
  107294. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  107295. for (var buf in parsedBuffers) {
  107296. var parsedBuffer = parsedBuffers[buf];
  107297. gltfRuntime.buffers[buf] = parsedBuffer;
  107298. gltfRuntime.buffersCount++;
  107299. }
  107300. };
  107301. var parseShaders = function (parsedShaders, gltfRuntime) {
  107302. for (var sha in parsedShaders) {
  107303. var parsedShader = parsedShaders[sha];
  107304. gltfRuntime.shaders[sha] = parsedShader;
  107305. gltfRuntime.shaderscount++;
  107306. }
  107307. };
  107308. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  107309. for (var object in parsedObjects) {
  107310. var parsedObject = parsedObjects[object];
  107311. gltfRuntime[runtimeProperty][object] = parsedObject;
  107312. }
  107313. };
  107314. /**
  107315. * Utils
  107316. */
  107317. var normalizeUVs = function (buffer) {
  107318. if (!buffer) {
  107319. return;
  107320. }
  107321. for (var i = 0; i < buffer.length / 2; i++) {
  107322. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  107323. }
  107324. };
  107325. var getAttribute = function (attributeParameter) {
  107326. if (attributeParameter.semantic === "NORMAL") {
  107327. return "normal";
  107328. }
  107329. else if (attributeParameter.semantic === "POSITION") {
  107330. return "position";
  107331. }
  107332. else if (attributeParameter.semantic === "JOINT") {
  107333. return "matricesIndices";
  107334. }
  107335. else if (attributeParameter.semantic === "WEIGHT") {
  107336. return "matricesWeights";
  107337. }
  107338. else if (attributeParameter.semantic === "COLOR") {
  107339. return "color";
  107340. }
  107341. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  107342. var channel = Number(attributeParameter.semantic.split("_")[1]);
  107343. return "uv" + (channel === 0 ? "" : channel + 1);
  107344. }
  107345. return null;
  107346. };
  107347. /**
  107348. * Loads and creates animations
  107349. */
  107350. var loadAnimations = function (gltfRuntime) {
  107351. for (var anim in gltfRuntime.animations) {
  107352. var animation = gltfRuntime.animations[anim];
  107353. if (!animation.channels || !animation.samplers) {
  107354. continue;
  107355. }
  107356. var lastAnimation = null;
  107357. for (var i = 0; i < animation.channels.length; i++) {
  107358. // Get parameters and load buffers
  107359. var channel = animation.channels[i];
  107360. var sampler = animation.samplers[channel.sampler];
  107361. if (!sampler) {
  107362. continue;
  107363. }
  107364. var inputData = null;
  107365. var outputData = null;
  107366. if (animation.parameters) {
  107367. inputData = animation.parameters[sampler.input];
  107368. outputData = animation.parameters[sampler.output];
  107369. }
  107370. else {
  107371. inputData = sampler.input;
  107372. outputData = sampler.output;
  107373. }
  107374. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  107375. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  107376. var targetID = channel.target.id;
  107377. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  107378. if (targetNode === null) {
  107379. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  107380. }
  107381. if (targetNode === null) {
  107382. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  107383. continue;
  107384. }
  107385. var isBone = targetNode instanceof BABYLON.Bone;
  107386. // Get target path (position, rotation or scaling)
  107387. var targetPath = channel.target.path;
  107388. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  107389. if (targetPathIndex !== -1) {
  107390. targetPath = babylonAnimationPaths[targetPathIndex];
  107391. }
  107392. // Determine animation type
  107393. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  107394. if (!isBone) {
  107395. if (targetPath === "rotationQuaternion") {
  107396. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  107397. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  107398. }
  107399. else {
  107400. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  107401. }
  107402. }
  107403. // Create animation and key frames
  107404. var babylonAnimation = null;
  107405. var keys = [];
  107406. var arrayOffset = 0;
  107407. var modifyKey = false;
  107408. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  107409. babylonAnimation = lastAnimation;
  107410. modifyKey = true;
  107411. }
  107412. if (!modifyKey) {
  107413. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  107414. }
  107415. // For each frame
  107416. for (var j = 0; j < bufferInput.length; j++) {
  107417. var value = null;
  107418. if (targetPath === "rotationQuaternion") {
  107419. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  107420. arrayOffset += 4;
  107421. }
  107422. else {
  107423. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  107424. arrayOffset += 3;
  107425. }
  107426. if (isBone) {
  107427. var bone = targetNode;
  107428. var translation = BABYLON.Vector3.Zero();
  107429. var rotationQuaternion = new BABYLON.Quaternion();
  107430. var scaling = BABYLON.Vector3.Zero();
  107431. // Warning on decompose
  107432. var mat = bone.getBaseMatrix();
  107433. if (modifyKey && lastAnimation) {
  107434. mat = lastAnimation.getKeys()[j].value;
  107435. }
  107436. mat.decompose(scaling, rotationQuaternion, translation);
  107437. if (targetPath === "position") {
  107438. translation = value;
  107439. }
  107440. else if (targetPath === "rotationQuaternion") {
  107441. rotationQuaternion = value;
  107442. }
  107443. else {
  107444. scaling = value;
  107445. }
  107446. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  107447. }
  107448. if (!modifyKey) {
  107449. keys.push({
  107450. frame: bufferInput[j],
  107451. value: value
  107452. });
  107453. }
  107454. else if (lastAnimation) {
  107455. lastAnimation.getKeys()[j].value = value;
  107456. }
  107457. }
  107458. // Finish
  107459. if (!modifyKey && babylonAnimation) {
  107460. babylonAnimation.setKeys(keys);
  107461. targetNode.animations.push(babylonAnimation);
  107462. }
  107463. lastAnimation = babylonAnimation;
  107464. gltfRuntime.scene.stopAnimation(targetNode);
  107465. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  107466. }
  107467. }
  107468. };
  107469. /**
  107470. * Returns the bones transformation matrix
  107471. */
  107472. var configureBoneTransformation = function (node) {
  107473. var mat = null;
  107474. if (node.translation || node.rotation || node.scale) {
  107475. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  107476. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  107477. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  107478. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  107479. }
  107480. else {
  107481. mat = BABYLON.Matrix.FromArray(node.matrix);
  107482. }
  107483. return mat;
  107484. };
  107485. /**
  107486. * Returns the parent bone
  107487. */
  107488. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  107489. // Try to find
  107490. for (var i = 0; i < newSkeleton.bones.length; i++) {
  107491. if (newSkeleton.bones[i].name === jointName) {
  107492. return newSkeleton.bones[i];
  107493. }
  107494. }
  107495. // Not found, search in gltf nodes
  107496. var nodes = gltfRuntime.nodes;
  107497. for (var nde in nodes) {
  107498. var node = nodes[nde];
  107499. if (!node.jointName) {
  107500. continue;
  107501. }
  107502. var children = node.children;
  107503. for (var i = 0; i < children.length; i++) {
  107504. var child = gltfRuntime.nodes[children[i]];
  107505. if (!child.jointName) {
  107506. continue;
  107507. }
  107508. if (child.jointName === jointName) {
  107509. var mat = configureBoneTransformation(node);
  107510. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  107511. bone.id = nde;
  107512. return bone;
  107513. }
  107514. }
  107515. }
  107516. return null;
  107517. };
  107518. /**
  107519. * Returns the appropriate root node
  107520. */
  107521. var getNodeToRoot = function (nodesToRoot, id) {
  107522. for (var i = 0; i < nodesToRoot.length; i++) {
  107523. var nodeToRoot = nodesToRoot[i];
  107524. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  107525. var child = nodeToRoot.node.children[j];
  107526. if (child === id) {
  107527. return nodeToRoot.bone;
  107528. }
  107529. }
  107530. }
  107531. return null;
  107532. };
  107533. /**
  107534. * Returns the node with the joint name
  107535. */
  107536. var getJointNode = function (gltfRuntime, jointName) {
  107537. var nodes = gltfRuntime.nodes;
  107538. var node = nodes[jointName];
  107539. if (node) {
  107540. return {
  107541. node: node,
  107542. id: jointName
  107543. };
  107544. }
  107545. for (var nde in nodes) {
  107546. node = nodes[nde];
  107547. if (node.jointName === jointName) {
  107548. return {
  107549. node: node,
  107550. id: nde
  107551. };
  107552. }
  107553. }
  107554. return null;
  107555. };
  107556. /**
  107557. * Checks if a nodes is in joints
  107558. */
  107559. var nodeIsInJoints = function (skins, id) {
  107560. for (var i = 0; i < skins.jointNames.length; i++) {
  107561. if (skins.jointNames[i] === id) {
  107562. return true;
  107563. }
  107564. }
  107565. return false;
  107566. };
  107567. /**
  107568. * Fills the nodes to root for bones and builds hierarchy
  107569. */
  107570. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  107571. // Creates nodes for root
  107572. for (var nde in gltfRuntime.nodes) {
  107573. var node = gltfRuntime.nodes[nde];
  107574. var id = nde;
  107575. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  107576. continue;
  107577. }
  107578. // Create node to root bone
  107579. var mat = configureBoneTransformation(node);
  107580. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  107581. bone.id = id;
  107582. nodesToRoot.push({ bone: bone, node: node, id: id });
  107583. }
  107584. // Parenting
  107585. for (var i = 0; i < nodesToRoot.length; i++) {
  107586. var nodeToRoot = nodesToRoot[i];
  107587. var children = nodeToRoot.node.children;
  107588. for (var j = 0; j < children.length; j++) {
  107589. var child = null;
  107590. for (var k = 0; k < nodesToRoot.length; k++) {
  107591. if (nodesToRoot[k].id === children[j]) {
  107592. child = nodesToRoot[k];
  107593. break;
  107594. }
  107595. }
  107596. if (child) {
  107597. child.bone._parent = nodeToRoot.bone;
  107598. nodeToRoot.bone.children.push(child.bone);
  107599. }
  107600. }
  107601. }
  107602. };
  107603. /**
  107604. * Imports a skeleton
  107605. */
  107606. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  107607. if (!newSkeleton) {
  107608. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  107609. }
  107610. if (!skins.babylonSkeleton) {
  107611. return newSkeleton;
  107612. }
  107613. // Find the root bones
  107614. var nodesToRoot = [];
  107615. var nodesToRootToAdd = [];
  107616. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  107617. newSkeleton.bones = [];
  107618. // Joints
  107619. for (var i = 0; i < skins.jointNames.length; i++) {
  107620. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  107621. if (!jointNode) {
  107622. continue;
  107623. }
  107624. var node = jointNode.node;
  107625. if (!node) {
  107626. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  107627. continue;
  107628. }
  107629. var id = jointNode.id;
  107630. // Optimize, if the bone already exists...
  107631. var existingBone = gltfRuntime.scene.getBoneByID(id);
  107632. if (existingBone) {
  107633. newSkeleton.bones.push(existingBone);
  107634. continue;
  107635. }
  107636. // Search for parent bone
  107637. var foundBone = false;
  107638. var parentBone = null;
  107639. for (var j = 0; j < i; j++) {
  107640. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  107641. if (!jointNode_1) {
  107642. continue;
  107643. }
  107644. var joint = jointNode_1.node;
  107645. if (!joint) {
  107646. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  107647. continue;
  107648. }
  107649. var children = joint.children;
  107650. if (!children) {
  107651. continue;
  107652. }
  107653. foundBone = false;
  107654. for (var k = 0; k < children.length; k++) {
  107655. if (children[k] === id) {
  107656. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  107657. foundBone = true;
  107658. break;
  107659. }
  107660. }
  107661. if (foundBone) {
  107662. break;
  107663. }
  107664. }
  107665. // Create bone
  107666. var mat = configureBoneTransformation(node);
  107667. if (!parentBone && nodesToRoot.length > 0) {
  107668. parentBone = getNodeToRoot(nodesToRoot, id);
  107669. if (parentBone) {
  107670. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  107671. nodesToRootToAdd.push(parentBone);
  107672. }
  107673. }
  107674. }
  107675. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  107676. bone.id = id;
  107677. }
  107678. // Polish
  107679. var bones = newSkeleton.bones;
  107680. newSkeleton.bones = [];
  107681. for (var i = 0; i < skins.jointNames.length; i++) {
  107682. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  107683. if (!jointNode) {
  107684. continue;
  107685. }
  107686. for (var j = 0; j < bones.length; j++) {
  107687. if (bones[j].id === jointNode.id) {
  107688. newSkeleton.bones.push(bones[j]);
  107689. break;
  107690. }
  107691. }
  107692. }
  107693. newSkeleton.prepare();
  107694. // Finish
  107695. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  107696. newSkeleton.bones.push(nodesToRootToAdd[i]);
  107697. }
  107698. return newSkeleton;
  107699. };
  107700. /**
  107701. * Imports a mesh and its geometries
  107702. */
  107703. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  107704. if (!newMesh) {
  107705. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107706. newMesh.id = id;
  107707. }
  107708. if (!node.babylonNode) {
  107709. return newMesh;
  107710. }
  107711. var subMaterials = [];
  107712. var vertexData = null;
  107713. var verticesStarts = new Array();
  107714. var verticesCounts = new Array();
  107715. var indexStarts = new Array();
  107716. var indexCounts = new Array();
  107717. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107718. var meshID = meshes[meshIndex];
  107719. var mesh = gltfRuntime.meshes[meshID];
  107720. if (!mesh) {
  107721. continue;
  107722. }
  107723. // Positions, normals and UVs
  107724. for (var i = 0; i < mesh.primitives.length; i++) {
  107725. // Temporary vertex data
  107726. var tempVertexData = new BABYLON.VertexData();
  107727. var primitive = mesh.primitives[i];
  107728. if (primitive.mode !== 4) {
  107729. // continue;
  107730. }
  107731. var attributes = primitive.attributes;
  107732. var accessor = null;
  107733. var buffer = null;
  107734. // Set positions, normal and uvs
  107735. for (var semantic in attributes) {
  107736. // Link accessor and buffer view
  107737. accessor = gltfRuntime.accessors[attributes[semantic]];
  107738. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107739. if (semantic === "NORMAL") {
  107740. tempVertexData.normals = new Float32Array(buffer.length);
  107741. tempVertexData.normals.set(buffer);
  107742. }
  107743. else if (semantic === "POSITION") {
  107744. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  107745. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  107746. for (var j = 0; j < buffer.length; j += 4) {
  107747. tempVertexData.positions[j] = buffer[j];
  107748. tempVertexData.positions[j + 1] = buffer[j + 1];
  107749. tempVertexData.positions[j + 2] = buffer[j + 2];
  107750. }
  107751. }
  107752. else {
  107753. tempVertexData.positions = new Float32Array(buffer.length);
  107754. tempVertexData.positions.set(buffer);
  107755. }
  107756. verticesCounts.push(tempVertexData.positions.length);
  107757. }
  107758. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  107759. var channel = Number(semantic.split("_")[1]);
  107760. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  107761. var uvs = new Float32Array(buffer.length);
  107762. uvs.set(buffer);
  107763. normalizeUVs(uvs);
  107764. tempVertexData.set(uvs, uvKind);
  107765. }
  107766. else if (semantic === "JOINT") {
  107767. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  107768. tempVertexData.matricesIndices.set(buffer);
  107769. }
  107770. else if (semantic === "WEIGHT") {
  107771. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  107772. tempVertexData.matricesWeights.set(buffer);
  107773. }
  107774. else if (semantic === "COLOR") {
  107775. tempVertexData.colors = new Float32Array(buffer.length);
  107776. tempVertexData.colors.set(buffer);
  107777. }
  107778. }
  107779. // Indices
  107780. accessor = gltfRuntime.accessors[primitive.indices];
  107781. if (accessor) {
  107782. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107783. tempVertexData.indices = new Int32Array(buffer.length);
  107784. tempVertexData.indices.set(buffer);
  107785. indexCounts.push(tempVertexData.indices.length);
  107786. }
  107787. else {
  107788. // Set indices on the fly
  107789. var indices = [];
  107790. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  107791. indices.push(j);
  107792. }
  107793. tempVertexData.indices = new Int32Array(indices);
  107794. indexCounts.push(tempVertexData.indices.length);
  107795. }
  107796. if (!vertexData) {
  107797. vertexData = tempVertexData;
  107798. }
  107799. else {
  107800. vertexData.merge(tempVertexData);
  107801. }
  107802. // Sub material
  107803. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  107804. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  107805. // Update vertices start and index start
  107806. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  107807. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  107808. }
  107809. }
  107810. var material;
  107811. if (subMaterials.length > 1) {
  107812. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  107813. material.subMaterials = subMaterials;
  107814. }
  107815. else {
  107816. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  107817. }
  107818. if (subMaterials.length === 1) {
  107819. material = subMaterials[0];
  107820. }
  107821. if (!newMesh.material) {
  107822. newMesh.material = material;
  107823. }
  107824. // Apply geometry
  107825. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  107826. newMesh.computeWorldMatrix(true);
  107827. // Apply submeshes
  107828. newMesh.subMeshes = [];
  107829. var index = 0;
  107830. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107831. var meshID = meshes[meshIndex];
  107832. var mesh = gltfRuntime.meshes[meshID];
  107833. if (!mesh) {
  107834. continue;
  107835. }
  107836. for (var i = 0; i < mesh.primitives.length; i++) {
  107837. if (mesh.primitives[i].mode !== 4) {
  107838. //continue;
  107839. }
  107840. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  107841. index++;
  107842. }
  107843. }
  107844. // Finish
  107845. return newMesh;
  107846. };
  107847. /**
  107848. * Configure node transformation from position, rotation and scaling
  107849. */
  107850. var configureNode = function (newNode, position, rotation, scaling) {
  107851. if (newNode.position) {
  107852. newNode.position = position;
  107853. }
  107854. if (newNode.rotationQuaternion || newNode.rotation) {
  107855. newNode.rotationQuaternion = rotation;
  107856. }
  107857. if (newNode.scaling) {
  107858. newNode.scaling = scaling;
  107859. }
  107860. };
  107861. /**
  107862. * Configures node from transformation matrix
  107863. */
  107864. var configureNodeFromMatrix = function (newNode, node, parent) {
  107865. if (node.matrix) {
  107866. var position = new BABYLON.Vector3(0, 0, 0);
  107867. var rotation = new BABYLON.Quaternion();
  107868. var scaling = new BABYLON.Vector3(0, 0, 0);
  107869. var mat = BABYLON.Matrix.FromArray(node.matrix);
  107870. mat.decompose(scaling, rotation, position);
  107871. configureNode(newNode, position, rotation, scaling);
  107872. }
  107873. else if (node.translation && node.rotation && node.scale) {
  107874. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  107875. }
  107876. newNode.computeWorldMatrix(true);
  107877. };
  107878. /**
  107879. * Imports a node
  107880. */
  107881. var importNode = function (gltfRuntime, node, id, parent) {
  107882. var lastNode = null;
  107883. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  107884. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  107885. return null;
  107886. }
  107887. }
  107888. // Meshes
  107889. if (node.skin) {
  107890. if (node.meshes) {
  107891. var skin = gltfRuntime.skins[node.skin];
  107892. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  107893. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  107894. if (newMesh.skeleton === null) {
  107895. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  107896. if (!skin.babylonSkeleton) {
  107897. skin.babylonSkeleton = newMesh.skeleton;
  107898. }
  107899. }
  107900. lastNode = newMesh;
  107901. }
  107902. }
  107903. else if (node.meshes) {
  107904. /**
  107905. * Improve meshes property
  107906. */
  107907. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  107908. lastNode = newMesh;
  107909. }
  107910. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107911. var light = gltfRuntime.lights[node.light];
  107912. if (light) {
  107913. if (light.type === "ambient") {
  107914. var ambienLight = light[light.type];
  107915. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107916. hemiLight.name = node.name || "";
  107917. if (ambienLight.color) {
  107918. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  107919. }
  107920. lastNode = hemiLight;
  107921. }
  107922. else if (light.type === "directional") {
  107923. var directionalLight = light[light.type];
  107924. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107925. dirLight.name = node.name || "";
  107926. if (directionalLight.color) {
  107927. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  107928. }
  107929. lastNode = dirLight;
  107930. }
  107931. else if (light.type === "point") {
  107932. var pointLight = light[light.type];
  107933. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107934. ptLight.name = node.name || "";
  107935. if (pointLight.color) {
  107936. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  107937. }
  107938. lastNode = ptLight;
  107939. }
  107940. else if (light.type === "spot") {
  107941. var spotLight = light[light.type];
  107942. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  107943. spLight.name = node.name || "";
  107944. if (spotLight.color) {
  107945. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  107946. }
  107947. if (spotLight.fallOfAngle) {
  107948. spLight.angle = spotLight.fallOfAngle;
  107949. }
  107950. if (spotLight.fallOffExponent) {
  107951. spLight.exponent = spotLight.fallOffExponent;
  107952. }
  107953. lastNode = spLight;
  107954. }
  107955. }
  107956. }
  107957. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107958. var camera = gltfRuntime.cameras[node.camera];
  107959. if (camera) {
  107960. if (camera.type === "orthographic") {
  107961. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107962. orthoCamera.name = node.name || "";
  107963. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  107964. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107965. lastNode = orthoCamera;
  107966. }
  107967. else if (camera.type === "perspective") {
  107968. var perspectiveCamera = camera[camera.type];
  107969. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107970. persCamera.name = node.name || "";
  107971. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107972. if (!perspectiveCamera.aspectRatio) {
  107973. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  107974. }
  107975. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  107976. persCamera.maxZ = perspectiveCamera.zfar;
  107977. persCamera.minZ = perspectiveCamera.znear;
  107978. }
  107979. lastNode = persCamera;
  107980. }
  107981. }
  107982. }
  107983. // Empty node
  107984. if (!node.jointName) {
  107985. if (node.babylonNode) {
  107986. return node.babylonNode;
  107987. }
  107988. else if (lastNode === null) {
  107989. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107990. node.babylonNode = dummy;
  107991. lastNode = dummy;
  107992. }
  107993. }
  107994. if (lastNode !== null) {
  107995. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  107996. configureNodeFromMatrix(lastNode, node, parent);
  107997. }
  107998. else {
  107999. var translation = node.translation || [0, 0, 0];
  108000. var rotation = node.rotation || [0, 0, 0, 1];
  108001. var scale = node.scale || [1, 1, 1];
  108002. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  108003. }
  108004. lastNode.updateCache(true);
  108005. node.babylonNode = lastNode;
  108006. }
  108007. return lastNode;
  108008. };
  108009. /**
  108010. * Traverses nodes and creates them
  108011. */
  108012. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  108013. if (meshIncluded === void 0) { meshIncluded = false; }
  108014. var node = gltfRuntime.nodes[id];
  108015. var newNode = null;
  108016. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  108017. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  108018. meshIncluded = true;
  108019. }
  108020. else {
  108021. meshIncluded = false;
  108022. }
  108023. }
  108024. else {
  108025. meshIncluded = true;
  108026. }
  108027. if (!node.jointName && meshIncluded) {
  108028. newNode = importNode(gltfRuntime, node, id, parent);
  108029. if (newNode !== null) {
  108030. newNode.id = id;
  108031. newNode.parent = parent;
  108032. }
  108033. }
  108034. if (node.children) {
  108035. for (var i = 0; i < node.children.length; i++) {
  108036. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  108037. }
  108038. }
  108039. };
  108040. /**
  108041. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  108042. */
  108043. var postLoad = function (gltfRuntime) {
  108044. // Nodes
  108045. var currentScene = gltfRuntime.currentScene;
  108046. if (currentScene) {
  108047. for (var i = 0; i < currentScene.nodes.length; i++) {
  108048. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108049. }
  108050. }
  108051. else {
  108052. for (var thing in gltfRuntime.scenes) {
  108053. currentScene = gltfRuntime.scenes[thing];
  108054. for (var i = 0; i < currentScene.nodes.length; i++) {
  108055. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108056. }
  108057. }
  108058. }
  108059. // Set animations
  108060. loadAnimations(gltfRuntime);
  108061. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  108062. var skeleton = gltfRuntime.scene.skeletons[i];
  108063. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  108064. }
  108065. };
  108066. /**
  108067. * onBind shaderrs callback to set uniforms and matrices
  108068. */
  108069. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  108070. var materialValues = material.values || technique.parameters;
  108071. for (var unif in unTreatedUniforms) {
  108072. var uniform = unTreatedUniforms[unif];
  108073. var type = uniform.type;
  108074. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  108075. if (uniform.semantic && !uniform.source && !uniform.node) {
  108076. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  108077. }
  108078. else if (uniform.semantic && (uniform.source || uniform.node)) {
  108079. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  108080. if (source === null) {
  108081. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  108082. }
  108083. if (source === null) {
  108084. continue;
  108085. }
  108086. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  108087. }
  108088. }
  108089. else {
  108090. var value = materialValues[technique.uniforms[unif]];
  108091. if (!value) {
  108092. continue;
  108093. }
  108094. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  108095. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  108096. if (texture === null || texture === undefined) {
  108097. continue;
  108098. }
  108099. shaderMaterial.getEffect().setTexture(unif, texture);
  108100. }
  108101. else {
  108102. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  108103. }
  108104. }
  108105. }
  108106. onSuccess(shaderMaterial);
  108107. };
  108108. /**
  108109. * Prepare uniforms to send the only one time
  108110. * Loads the appropriate textures
  108111. */
  108112. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  108113. var materialValues = material.values || technique.parameters;
  108114. var techniqueUniforms = technique.uniforms;
  108115. /**
  108116. * Prepare values here (not matrices)
  108117. */
  108118. for (var unif in unTreatedUniforms) {
  108119. var uniform = unTreatedUniforms[unif];
  108120. var type = uniform.type;
  108121. var value = materialValues[techniqueUniforms[unif]];
  108122. if (value === undefined) {
  108123. // In case the value is the same for all materials
  108124. value = uniform.value;
  108125. }
  108126. if (!value) {
  108127. continue;
  108128. }
  108129. var onLoadTexture = function (uniformName) {
  108130. return function (texture) {
  108131. if (uniform.value && uniformName) {
  108132. // Static uniform
  108133. shaderMaterial.setTexture(uniformName, texture);
  108134. delete unTreatedUniforms[uniformName];
  108135. }
  108136. };
  108137. };
  108138. // Texture (sampler2D)
  108139. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  108140. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  108141. }
  108142. else {
  108143. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  108144. // Static uniform
  108145. delete unTreatedUniforms[unif];
  108146. }
  108147. }
  108148. }
  108149. };
  108150. /**
  108151. * Shader compilation failed
  108152. */
  108153. var onShaderCompileError = function (program, shaderMaterial, onError) {
  108154. return function (effect, error) {
  108155. shaderMaterial.dispose(true);
  108156. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  108157. };
  108158. };
  108159. /**
  108160. * Shader compilation success
  108161. */
  108162. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  108163. return function (_) {
  108164. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  108165. shaderMaterial.onBind = function (mesh) {
  108166. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  108167. };
  108168. };
  108169. };
  108170. /**
  108171. * Returns the appropriate uniform if already handled by babylon
  108172. */
  108173. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  108174. for (var unif in technique.uniforms) {
  108175. var uniform = technique.uniforms[unif];
  108176. var uniformParameter = technique.parameters[uniform];
  108177. if (tokenizer.currentIdentifier === unif) {
  108178. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  108179. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  108180. if (transformIndex !== -1) {
  108181. delete unTreatedUniforms[unif];
  108182. return babylonTransforms[transformIndex];
  108183. }
  108184. }
  108185. }
  108186. }
  108187. return tokenizer.currentIdentifier;
  108188. };
  108189. /**
  108190. * All shaders loaded. Create materials one by one
  108191. */
  108192. var importMaterials = function (gltfRuntime) {
  108193. // Create materials
  108194. for (var mat in gltfRuntime.materials) {
  108195. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  108196. }
  108197. };
  108198. /**
  108199. * Implementation of the base glTF spec
  108200. */
  108201. var GLTFLoaderBase = /** @class */ (function () {
  108202. function GLTFLoaderBase() {
  108203. }
  108204. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  108205. var gltfRuntime = {
  108206. extensions: {},
  108207. accessors: {},
  108208. buffers: {},
  108209. bufferViews: {},
  108210. meshes: {},
  108211. lights: {},
  108212. cameras: {},
  108213. nodes: {},
  108214. images: {},
  108215. textures: {},
  108216. shaders: {},
  108217. programs: {},
  108218. samplers: {},
  108219. techniques: {},
  108220. materials: {},
  108221. animations: {},
  108222. skins: {},
  108223. extensionsUsed: [],
  108224. scenes: {},
  108225. buffersCount: 0,
  108226. shaderscount: 0,
  108227. scene: scene,
  108228. rootUrl: rootUrl,
  108229. loadedBufferCount: 0,
  108230. loadedBufferViews: {},
  108231. loadedShaderCount: 0,
  108232. importOnlyMeshes: false,
  108233. dummyNodes: []
  108234. };
  108235. // Parse
  108236. if (parsedData.extensions) {
  108237. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  108238. }
  108239. if (parsedData.extensionsUsed) {
  108240. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  108241. }
  108242. if (parsedData.buffers) {
  108243. parseBuffers(parsedData.buffers, gltfRuntime);
  108244. }
  108245. if (parsedData.bufferViews) {
  108246. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  108247. }
  108248. if (parsedData.accessors) {
  108249. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  108250. }
  108251. if (parsedData.meshes) {
  108252. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  108253. }
  108254. if (parsedData.lights) {
  108255. parseObject(parsedData.lights, "lights", gltfRuntime);
  108256. }
  108257. if (parsedData.cameras) {
  108258. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  108259. }
  108260. if (parsedData.nodes) {
  108261. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  108262. }
  108263. if (parsedData.images) {
  108264. parseObject(parsedData.images, "images", gltfRuntime);
  108265. }
  108266. if (parsedData.textures) {
  108267. parseObject(parsedData.textures, "textures", gltfRuntime);
  108268. }
  108269. if (parsedData.shaders) {
  108270. parseShaders(parsedData.shaders, gltfRuntime);
  108271. }
  108272. if (parsedData.programs) {
  108273. parseObject(parsedData.programs, "programs", gltfRuntime);
  108274. }
  108275. if (parsedData.samplers) {
  108276. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  108277. }
  108278. if (parsedData.techniques) {
  108279. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  108280. }
  108281. if (parsedData.materials) {
  108282. parseObject(parsedData.materials, "materials", gltfRuntime);
  108283. }
  108284. if (parsedData.animations) {
  108285. parseObject(parsedData.animations, "animations", gltfRuntime);
  108286. }
  108287. if (parsedData.skins) {
  108288. parseObject(parsedData.skins, "skins", gltfRuntime);
  108289. }
  108290. if (parsedData.scenes) {
  108291. gltfRuntime.scenes = parsedData.scenes;
  108292. }
  108293. if (parsedData.scene && parsedData.scenes) {
  108294. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  108295. }
  108296. return gltfRuntime;
  108297. };
  108298. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108299. var buffer = gltfRuntime.buffers[id];
  108300. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  108301. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  108302. }
  108303. else {
  108304. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  108305. if (request) {
  108306. onError(request.status + " " + request.statusText);
  108307. }
  108308. });
  108309. }
  108310. };
  108311. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108312. var texture = gltfRuntime.textures[id];
  108313. if (!texture || !texture.source) {
  108314. onError("");
  108315. return;
  108316. }
  108317. if (texture.babylonTexture) {
  108318. onSuccess(null);
  108319. return;
  108320. }
  108321. var source = gltfRuntime.images[texture.source];
  108322. if (BABYLON.Tools.IsBase64(source.uri)) {
  108323. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  108324. }
  108325. else {
  108326. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  108327. if (request) {
  108328. onError(request.status + " " + request.statusText);
  108329. }
  108330. });
  108331. }
  108332. };
  108333. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108334. var texture = gltfRuntime.textures[id];
  108335. if (texture.babylonTexture) {
  108336. onSuccess(texture.babylonTexture);
  108337. return;
  108338. }
  108339. var sampler = gltfRuntime.samplers[texture.sampler];
  108340. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  108341. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  108342. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  108343. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  108344. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  108345. var blob = new Blob([buffer]);
  108346. var blobURL = URL.createObjectURL(blob);
  108347. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  108348. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  108349. if (sampler.wrapS !== undefined) {
  108350. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  108351. }
  108352. if (sampler.wrapT !== undefined) {
  108353. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  108354. }
  108355. newTexture.name = id;
  108356. texture.babylonTexture = newTexture;
  108357. onSuccess(newTexture);
  108358. };
  108359. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108360. var shader = gltfRuntime.shaders[id];
  108361. if (BABYLON.Tools.IsBase64(shader.uri)) {
  108362. var shaderString = atob(shader.uri.split(",")[1]);
  108363. onSuccess(shaderString);
  108364. }
  108365. else {
  108366. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  108367. if (request) {
  108368. onError(request.status + " " + request.statusText);
  108369. }
  108370. });
  108371. }
  108372. };
  108373. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108374. var material = gltfRuntime.materials[id];
  108375. if (!material.technique) {
  108376. if (onError) {
  108377. onError("No technique found.");
  108378. }
  108379. return;
  108380. }
  108381. var technique = gltfRuntime.techniques[material.technique];
  108382. if (!technique) {
  108383. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108384. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  108385. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108386. onSuccess(defaultMaterial);
  108387. return;
  108388. }
  108389. var program = gltfRuntime.programs[technique.program];
  108390. var states = technique.states;
  108391. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  108392. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  108393. var newVertexShader = "";
  108394. var newPixelShader = "";
  108395. var vertexTokenizer = new Tokenizer(vertexShader);
  108396. var pixelTokenizer = new Tokenizer(pixelShader);
  108397. var unTreatedUniforms = {};
  108398. var uniforms = [];
  108399. var attributes = [];
  108400. var samplers = [];
  108401. // Fill uniform, sampler2D and attributes
  108402. for (var unif in technique.uniforms) {
  108403. var uniform = technique.uniforms[unif];
  108404. var uniformParameter = technique.parameters[uniform];
  108405. unTreatedUniforms[unif] = uniformParameter;
  108406. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  108407. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  108408. if (transformIndex !== -1) {
  108409. uniforms.push(babylonTransforms[transformIndex]);
  108410. delete unTreatedUniforms[unif];
  108411. }
  108412. else {
  108413. uniforms.push(unif);
  108414. }
  108415. }
  108416. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  108417. samplers.push(unif);
  108418. }
  108419. else {
  108420. uniforms.push(unif);
  108421. }
  108422. }
  108423. for (var attr in technique.attributes) {
  108424. var attribute = technique.attributes[attr];
  108425. var attributeParameter = technique.parameters[attribute];
  108426. if (attributeParameter.semantic) {
  108427. attributes.push(getAttribute(attributeParameter));
  108428. }
  108429. }
  108430. // Configure vertex shader
  108431. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  108432. var tokenType = vertexTokenizer.currentToken;
  108433. if (tokenType !== ETokenType.IDENTIFIER) {
  108434. newVertexShader += vertexTokenizer.currentString;
  108435. continue;
  108436. }
  108437. var foundAttribute = false;
  108438. for (var attr in technique.attributes) {
  108439. var attribute = technique.attributes[attr];
  108440. var attributeParameter = technique.parameters[attribute];
  108441. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  108442. newVertexShader += getAttribute(attributeParameter);
  108443. foundAttribute = true;
  108444. break;
  108445. }
  108446. }
  108447. if (foundAttribute) {
  108448. continue;
  108449. }
  108450. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  108451. }
  108452. // Configure pixel shader
  108453. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  108454. var tokenType = pixelTokenizer.currentToken;
  108455. if (tokenType !== ETokenType.IDENTIFIER) {
  108456. newPixelShader += pixelTokenizer.currentString;
  108457. continue;
  108458. }
  108459. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  108460. }
  108461. // Create shader material
  108462. var shaderPath = {
  108463. vertex: program.vertexShader + id,
  108464. fragment: program.fragmentShader + id
  108465. };
  108466. var options = {
  108467. attributes: attributes,
  108468. uniforms: uniforms,
  108469. samplers: samplers,
  108470. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  108471. };
  108472. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  108473. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  108474. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  108475. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  108476. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  108477. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108478. if (states && states.functions) {
  108479. var functions = states.functions;
  108480. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  108481. shaderMaterial.backFaceCulling = false;
  108482. }
  108483. var blendFunc = functions.blendFuncSeparate;
  108484. if (blendFunc) {
  108485. 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) {
  108486. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  108487. }
  108488. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108489. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  108490. }
  108491. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108492. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  108493. }
  108494. 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) {
  108495. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  108496. }
  108497. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108498. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  108499. }
  108500. 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) {
  108501. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  108502. }
  108503. }
  108504. }
  108505. };
  108506. return GLTFLoaderBase;
  108507. }());
  108508. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  108509. /**
  108510. * glTF V1 Loader
  108511. */
  108512. var GLTFLoader = /** @class */ (function () {
  108513. function GLTFLoader() {
  108514. // #region Stubs for IGLTFLoader interface
  108515. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  108516. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  108517. this.compileMaterials = false;
  108518. this.useClipPlane = false;
  108519. this.compileShadowGenerators = false;
  108520. this.onDisposeObservable = new BABYLON.Observable();
  108521. this.onMeshLoadedObservable = new BABYLON.Observable();
  108522. this.onTextureLoadedObservable = new BABYLON.Observable();
  108523. this.onMaterialLoadedObservable = new BABYLON.Observable();
  108524. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  108525. this.onCompleteObservable = new BABYLON.Observable();
  108526. this.onExtensionLoadedObservable = new BABYLON.Observable();
  108527. this.state = null;
  108528. }
  108529. GLTFLoader.RegisterExtension = function (extension) {
  108530. if (GLTFLoader.Extensions[extension.name]) {
  108531. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  108532. return;
  108533. }
  108534. GLTFLoader.Extensions[extension.name] = extension;
  108535. };
  108536. GLTFLoader.prototype.dispose = function () { };
  108537. // #endregion
  108538. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  108539. var _this = this;
  108540. scene.useRightHandedSystem = true;
  108541. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  108542. gltfRuntime.importOnlyMeshes = true;
  108543. if (meshesNames === "") {
  108544. gltfRuntime.importMeshesNames = [];
  108545. }
  108546. else if (typeof meshesNames === "string") {
  108547. gltfRuntime.importMeshesNames = [meshesNames];
  108548. }
  108549. else if (meshesNames && !(meshesNames instanceof Array)) {
  108550. gltfRuntime.importMeshesNames = [meshesNames];
  108551. }
  108552. else {
  108553. gltfRuntime.importMeshesNames = [];
  108554. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  108555. }
  108556. // Create nodes
  108557. _this._createNodes(gltfRuntime);
  108558. var meshes = new Array();
  108559. var skeletons = new Array();
  108560. // Fill arrays of meshes and skeletons
  108561. for (var nde in gltfRuntime.nodes) {
  108562. var node = gltfRuntime.nodes[nde];
  108563. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  108564. meshes.push(node.babylonNode);
  108565. }
  108566. }
  108567. for (var skl in gltfRuntime.skins) {
  108568. var skin = gltfRuntime.skins[skl];
  108569. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  108570. skeletons.push(skin.babylonSkeleton);
  108571. }
  108572. }
  108573. // Load buffers, shaders, materials, etc.
  108574. _this._loadBuffersAsync(gltfRuntime, function () {
  108575. _this._loadShadersAsync(gltfRuntime, function () {
  108576. importMaterials(gltfRuntime);
  108577. postLoad(gltfRuntime);
  108578. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  108579. onSuccess(meshes, [], skeletons);
  108580. }
  108581. });
  108582. }, onProgress);
  108583. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  108584. onSuccess(meshes, [], skeletons);
  108585. }
  108586. }, onError);
  108587. return true;
  108588. };
  108589. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108590. var _this = this;
  108591. return new Promise(function (resolve, reject) {
  108592. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  108593. resolve({
  108594. meshes: meshes,
  108595. particleSystems: particleSystems,
  108596. skeletons: skeletons
  108597. });
  108598. }, onProgress, function (message) {
  108599. reject(new Error(message));
  108600. });
  108601. });
  108602. };
  108603. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  108604. var _this = this;
  108605. scene.useRightHandedSystem = true;
  108606. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  108607. // Load runtime extensios
  108608. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  108609. // Create nodes
  108610. _this._createNodes(gltfRuntime);
  108611. // Load buffers, shaders, materials, etc.
  108612. _this._loadBuffersAsync(gltfRuntime, function () {
  108613. _this._loadShadersAsync(gltfRuntime, function () {
  108614. importMaterials(gltfRuntime);
  108615. postLoad(gltfRuntime);
  108616. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  108617. onSuccess();
  108618. }
  108619. });
  108620. });
  108621. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  108622. onSuccess();
  108623. }
  108624. }, onError);
  108625. }, onError);
  108626. };
  108627. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108628. var _this = this;
  108629. return new Promise(function (resolve, reject) {
  108630. _this._loadAsync(scene, data, rootUrl, function () {
  108631. resolve();
  108632. }, onProgress, function (message) {
  108633. reject(new Error(message));
  108634. });
  108635. });
  108636. };
  108637. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  108638. var hasShaders = false;
  108639. var processShader = function (sha, shader) {
  108640. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  108641. gltfRuntime.loadedShaderCount++;
  108642. if (shaderString) {
  108643. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  108644. }
  108645. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  108646. onload();
  108647. }
  108648. }, function () {
  108649. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  108650. });
  108651. };
  108652. for (var sha in gltfRuntime.shaders) {
  108653. hasShaders = true;
  108654. var shader = gltfRuntime.shaders[sha];
  108655. if (shader) {
  108656. processShader.bind(this, sha, shader)();
  108657. }
  108658. else {
  108659. BABYLON.Tools.Error("No shader named: " + sha);
  108660. }
  108661. }
  108662. if (!hasShaders) {
  108663. onload();
  108664. }
  108665. };
  108666. ;
  108667. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  108668. var hasBuffers = false;
  108669. var processBuffer = function (buf, buffer) {
  108670. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  108671. gltfRuntime.loadedBufferCount++;
  108672. if (bufferView) {
  108673. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  108674. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  108675. }
  108676. gltfRuntime.loadedBufferViews[buf] = bufferView;
  108677. }
  108678. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  108679. onLoad();
  108680. }
  108681. }, function () {
  108682. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  108683. });
  108684. };
  108685. for (var buf in gltfRuntime.buffers) {
  108686. hasBuffers = true;
  108687. var buffer = gltfRuntime.buffers[buf];
  108688. if (buffer) {
  108689. processBuffer.bind(this, buf, buffer)();
  108690. }
  108691. else {
  108692. BABYLON.Tools.Error("No buffer named: " + buf);
  108693. }
  108694. }
  108695. if (!hasBuffers) {
  108696. onLoad();
  108697. }
  108698. };
  108699. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  108700. var currentScene = gltfRuntime.currentScene;
  108701. if (currentScene) {
  108702. // Only one scene even if multiple scenes are defined
  108703. for (var i = 0; i < currentScene.nodes.length; i++) {
  108704. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108705. }
  108706. }
  108707. else {
  108708. // Load all scenes
  108709. for (var thing in gltfRuntime.scenes) {
  108710. currentScene = gltfRuntime.scenes[thing];
  108711. for (var i = 0; i < currentScene.nodes.length; i++) {
  108712. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108713. }
  108714. }
  108715. }
  108716. };
  108717. GLTFLoader.Extensions = {};
  108718. return GLTFLoader;
  108719. }());
  108720. GLTF1.GLTFLoader = GLTFLoader;
  108721. ;
  108722. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  108723. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108724. })(BABYLON || (BABYLON = {}));
  108725. //# sourceMappingURL=babylon.glTFLoader.js.map
  108726. "use strict";
  108727. var BABYLON;
  108728. (function (BABYLON) {
  108729. var GLTF1;
  108730. (function (GLTF1) {
  108731. /**
  108732. * Utils functions for GLTF
  108733. */
  108734. var GLTFUtils = /** @class */ (function () {
  108735. function GLTFUtils() {
  108736. }
  108737. /**
  108738. * Sets the given "parameter" matrix
  108739. * @param scene: the {BABYLON.Scene} object
  108740. * @param source: the source node where to pick the matrix
  108741. * @param parameter: the GLTF technique parameter
  108742. * @param uniformName: the name of the shader's uniform
  108743. * @param shaderMaterial: the shader material
  108744. */
  108745. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  108746. var mat = null;
  108747. if (parameter.semantic === "MODEL") {
  108748. mat = source.getWorldMatrix();
  108749. }
  108750. else if (parameter.semantic === "PROJECTION") {
  108751. mat = scene.getProjectionMatrix();
  108752. }
  108753. else if (parameter.semantic === "VIEW") {
  108754. mat = scene.getViewMatrix();
  108755. }
  108756. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  108757. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  108758. }
  108759. else if (parameter.semantic === "MODELVIEW") {
  108760. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  108761. }
  108762. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  108763. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  108764. }
  108765. else if (parameter.semantic === "MODELINVERSE") {
  108766. mat = source.getWorldMatrix().invert();
  108767. }
  108768. else if (parameter.semantic === "VIEWINVERSE") {
  108769. mat = scene.getViewMatrix().invert();
  108770. }
  108771. else if (parameter.semantic === "PROJECTIONINVERSE") {
  108772. mat = scene.getProjectionMatrix().invert();
  108773. }
  108774. else if (parameter.semantic === "MODELVIEWINVERSE") {
  108775. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  108776. }
  108777. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  108778. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  108779. }
  108780. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  108781. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  108782. }
  108783. else {
  108784. debugger;
  108785. }
  108786. if (mat) {
  108787. switch (parameter.type) {
  108788. case GLTF1.EParameterType.FLOAT_MAT2:
  108789. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  108790. break;
  108791. case GLTF1.EParameterType.FLOAT_MAT3:
  108792. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  108793. break;
  108794. case GLTF1.EParameterType.FLOAT_MAT4:
  108795. shaderMaterial.setMatrix(uniformName, mat);
  108796. break;
  108797. default: break;
  108798. }
  108799. }
  108800. };
  108801. /**
  108802. * Sets the given "parameter" matrix
  108803. * @param shaderMaterial: the shader material
  108804. * @param uniform: the name of the shader's uniform
  108805. * @param value: the value of the uniform
  108806. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  108807. */
  108808. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  108809. switch (type) {
  108810. case GLTF1.EParameterType.FLOAT:
  108811. shaderMaterial.setFloat(uniform, value);
  108812. return true;
  108813. case GLTF1.EParameterType.FLOAT_VEC2:
  108814. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  108815. return true;
  108816. case GLTF1.EParameterType.FLOAT_VEC3:
  108817. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  108818. return true;
  108819. case GLTF1.EParameterType.FLOAT_VEC4:
  108820. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  108821. return true;
  108822. default: return false;
  108823. }
  108824. };
  108825. /**
  108826. * Returns the wrap mode of the texture
  108827. * @param mode: the mode value
  108828. */
  108829. GLTFUtils.GetWrapMode = function (mode) {
  108830. switch (mode) {
  108831. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108832. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108833. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108834. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108835. }
  108836. };
  108837. /**
  108838. * Returns the byte stride giving an accessor
  108839. * @param accessor: the GLTF accessor objet
  108840. */
  108841. GLTFUtils.GetByteStrideFromType = function (accessor) {
  108842. // Needs this function since "byteStride" isn't requiered in glTF format
  108843. var type = accessor.type;
  108844. switch (type) {
  108845. case "VEC2": return 2;
  108846. case "VEC3": return 3;
  108847. case "VEC4": return 4;
  108848. case "MAT2": return 4;
  108849. case "MAT3": return 9;
  108850. case "MAT4": return 16;
  108851. default: return 1;
  108852. }
  108853. };
  108854. /**
  108855. * Returns the texture filter mode giving a mode value
  108856. * @param mode: the filter mode value
  108857. */
  108858. GLTFUtils.GetTextureFilterMode = function (mode) {
  108859. switch (mode) {
  108860. case GLTF1.ETextureFilterType.LINEAR:
  108861. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  108862. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  108863. case GLTF1.ETextureFilterType.NEAREST:
  108864. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  108865. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  108866. }
  108867. };
  108868. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  108869. var byteOffset = bufferView.byteOffset + byteOffset;
  108870. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  108871. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  108872. throw new Error("Buffer access is out of range");
  108873. }
  108874. var buffer = loadedBufferView.buffer;
  108875. byteOffset += loadedBufferView.byteOffset;
  108876. switch (componentType) {
  108877. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  108878. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  108879. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  108880. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  108881. default: return new Float32Array(buffer, byteOffset, byteLength);
  108882. }
  108883. };
  108884. /**
  108885. * Returns a buffer from its accessor
  108886. * @param gltfRuntime: the GLTF runtime
  108887. * @param accessor: the GLTF accessor
  108888. */
  108889. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  108890. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  108891. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  108892. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  108893. };
  108894. /**
  108895. * Decodes a buffer view into a string
  108896. * @param view: the buffer view
  108897. */
  108898. GLTFUtils.DecodeBufferToText = function (view) {
  108899. var result = "";
  108900. var length = view.byteLength;
  108901. for (var i = 0; i < length; ++i) {
  108902. result += String.fromCharCode(view[i]);
  108903. }
  108904. return result;
  108905. };
  108906. /**
  108907. * Returns the default material of gltf. Related to
  108908. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  108909. * @param scene: the Babylon.js scene
  108910. */
  108911. GLTFUtils.GetDefaultMaterial = function (scene) {
  108912. if (!GLTFUtils._DefaultMaterial) {
  108913. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  108914. "precision highp float;",
  108915. "",
  108916. "uniform mat4 worldView;",
  108917. "uniform mat4 projection;",
  108918. "",
  108919. "attribute vec3 position;",
  108920. "",
  108921. "void main(void)",
  108922. "{",
  108923. " gl_Position = projection * worldView * vec4(position, 1.0);",
  108924. "}"
  108925. ].join("\n");
  108926. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  108927. "precision highp float;",
  108928. "",
  108929. "uniform vec4 u_emission;",
  108930. "",
  108931. "void main(void)",
  108932. "{",
  108933. " gl_FragColor = u_emission;",
  108934. "}"
  108935. ].join("\n");
  108936. var shaderPath = {
  108937. vertex: "GLTFDefaultMaterial",
  108938. fragment: "GLTFDefaultMaterial"
  108939. };
  108940. var options = {
  108941. attributes: ["position"],
  108942. uniforms: ["worldView", "projection", "u_emission"],
  108943. samplers: new Array(),
  108944. needAlphaBlending: false
  108945. };
  108946. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  108947. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  108948. }
  108949. return GLTFUtils._DefaultMaterial;
  108950. };
  108951. // The GLTF default material
  108952. GLTFUtils._DefaultMaterial = null;
  108953. return GLTFUtils;
  108954. }());
  108955. GLTF1.GLTFUtils = GLTFUtils;
  108956. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108957. })(BABYLON || (BABYLON = {}));
  108958. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  108959. "use strict";
  108960. var BABYLON;
  108961. (function (BABYLON) {
  108962. var GLTF1;
  108963. (function (GLTF1) {
  108964. var GLTFLoaderExtension = /** @class */ (function () {
  108965. function GLTFLoaderExtension(name) {
  108966. this._name = name;
  108967. }
  108968. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  108969. get: function () {
  108970. return this._name;
  108971. },
  108972. enumerable: true,
  108973. configurable: true
  108974. });
  108975. /**
  108976. * Defines an override for loading the runtime
  108977. * Return true to stop further extensions from loading the runtime
  108978. */
  108979. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108980. return false;
  108981. };
  108982. /**
  108983. * Defines an onverride for creating gltf runtime
  108984. * Return true to stop further extensions from creating the runtime
  108985. */
  108986. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108987. return false;
  108988. };
  108989. /**
  108990. * Defines an override for loading buffers
  108991. * Return true to stop further extensions from loading this buffer
  108992. */
  108993. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108994. return false;
  108995. };
  108996. /**
  108997. * Defines an override for loading texture buffers
  108998. * Return true to stop further extensions from loading this texture data
  108999. */
  109000. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109001. return false;
  109002. };
  109003. /**
  109004. * Defines an override for creating textures
  109005. * Return true to stop further extensions from loading this texture
  109006. */
  109007. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  109008. return false;
  109009. };
  109010. /**
  109011. * Defines an override for loading shader strings
  109012. * Return true to stop further extensions from loading this shader data
  109013. */
  109014. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109015. return false;
  109016. };
  109017. /**
  109018. * Defines an override for loading materials
  109019. * Return true to stop further extensions from loading this material
  109020. */
  109021. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109022. return false;
  109023. };
  109024. // ---------
  109025. // Utilities
  109026. // ---------
  109027. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109028. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109029. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  109030. }, function () {
  109031. setTimeout(function () {
  109032. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  109033. });
  109034. });
  109035. };
  109036. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109037. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109038. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  109039. }, function () {
  109040. setTimeout(function () {
  109041. onSuccess();
  109042. });
  109043. });
  109044. };
  109045. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  109046. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109047. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  109048. }, function () {
  109049. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  109050. });
  109051. };
  109052. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  109053. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  109054. };
  109055. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109056. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109057. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  109058. }, function () {
  109059. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  109060. });
  109061. };
  109062. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109063. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109064. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  109065. }, function () {
  109066. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  109067. });
  109068. };
  109069. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109070. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109071. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  109072. }, function () {
  109073. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  109074. });
  109075. };
  109076. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  109077. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109078. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109079. }, function () {
  109080. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109081. });
  109082. };
  109083. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  109084. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  109085. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  109086. if (func(loaderExtension)) {
  109087. return;
  109088. }
  109089. }
  109090. defaultFunc();
  109091. };
  109092. return GLTFLoaderExtension;
  109093. }());
  109094. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  109095. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109096. })(BABYLON || (BABYLON = {}));
  109097. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  109098. "use strict";
  109099. var BABYLON;
  109100. (function (BABYLON) {
  109101. var GLTF1;
  109102. (function (GLTF1) {
  109103. var BinaryExtensionBufferName = "binary_glTF";
  109104. ;
  109105. ;
  109106. var GLTFBinaryExtension = /** @class */ (function (_super) {
  109107. __extends(GLTFBinaryExtension, _super);
  109108. function GLTFBinaryExtension() {
  109109. return _super.call(this, "KHR_binary_glTF") || this;
  109110. }
  109111. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109112. var extensionsUsed = data.json.extensionsUsed;
  109113. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  109114. return false;
  109115. }
  109116. this._bin = data.bin;
  109117. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  109118. return true;
  109119. };
  109120. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109121. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  109122. return false;
  109123. }
  109124. if (id !== BinaryExtensionBufferName) {
  109125. return false;
  109126. }
  109127. onSuccess(this._bin);
  109128. return true;
  109129. };
  109130. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109131. var texture = gltfRuntime.textures[id];
  109132. var source = gltfRuntime.images[texture.source];
  109133. if (!source.extensions || !(this.name in source.extensions)) {
  109134. return false;
  109135. }
  109136. var sourceExt = source.extensions[this.name];
  109137. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  109138. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  109139. onSuccess(buffer);
  109140. return true;
  109141. };
  109142. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109143. var shader = gltfRuntime.shaders[id];
  109144. if (!shader.extensions || !(this.name in shader.extensions)) {
  109145. return false;
  109146. }
  109147. var binaryExtensionShader = shader.extensions[this.name];
  109148. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  109149. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  109150. setTimeout(function () {
  109151. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  109152. onSuccess(shaderString);
  109153. });
  109154. return true;
  109155. };
  109156. return GLTFBinaryExtension;
  109157. }(GLTF1.GLTFLoaderExtension));
  109158. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  109159. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  109160. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109161. })(BABYLON || (BABYLON = {}));
  109162. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  109163. "use strict";
  109164. var BABYLON;
  109165. (function (BABYLON) {
  109166. var GLTF1;
  109167. (function (GLTF1) {
  109168. ;
  109169. ;
  109170. ;
  109171. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  109172. __extends(GLTFMaterialsCommonExtension, _super);
  109173. function GLTFMaterialsCommonExtension() {
  109174. return _super.call(this, "KHR_materials_common") || this;
  109175. }
  109176. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109177. if (!gltfRuntime.extensions)
  109178. return false;
  109179. var extension = gltfRuntime.extensions[this.name];
  109180. if (!extension)
  109181. return false;
  109182. // Create lights
  109183. var lights = extension.lights;
  109184. if (lights) {
  109185. for (var thing in lights) {
  109186. var light = lights[thing];
  109187. switch (light.type) {
  109188. case "ambient":
  109189. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  109190. var ambient = light.ambient;
  109191. if (ambient) {
  109192. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  109193. }
  109194. break;
  109195. case "point":
  109196. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  109197. var point = light.point;
  109198. if (point) {
  109199. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  109200. }
  109201. break;
  109202. case "directional":
  109203. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  109204. var directional = light.directional;
  109205. if (directional) {
  109206. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  109207. }
  109208. break;
  109209. case "spot":
  109210. var spot = light.spot;
  109211. if (spot) {
  109212. 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);
  109213. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  109214. }
  109215. break;
  109216. default:
  109217. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  109218. break;
  109219. }
  109220. }
  109221. }
  109222. return false;
  109223. };
  109224. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109225. var material = gltfRuntime.materials[id];
  109226. if (!material || !material.extensions)
  109227. return false;
  109228. var extension = material.extensions[this.name];
  109229. if (!extension)
  109230. return false;
  109231. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  109232. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  109233. if (extension.technique === "CONSTANT") {
  109234. standardMaterial.disableLighting = true;
  109235. }
  109236. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  109237. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  109238. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  109239. // Ambient
  109240. if (typeof extension.values.ambient === "string") {
  109241. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  109242. }
  109243. else {
  109244. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  109245. }
  109246. // Diffuse
  109247. if (typeof extension.values.diffuse === "string") {
  109248. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  109249. }
  109250. else {
  109251. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  109252. }
  109253. // Emission
  109254. if (typeof extension.values.emission === "string") {
  109255. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  109256. }
  109257. else {
  109258. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  109259. }
  109260. // Specular
  109261. if (typeof extension.values.specular === "string") {
  109262. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  109263. }
  109264. else {
  109265. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  109266. }
  109267. return true;
  109268. };
  109269. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  109270. // Create buffer from texture url
  109271. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  109272. // Create texture from buffer
  109273. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  109274. }, onError);
  109275. };
  109276. return GLTFMaterialsCommonExtension;
  109277. }(GLTF1.GLTFLoaderExtension));
  109278. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  109279. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  109280. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109281. })(BABYLON || (BABYLON = {}));
  109282. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  109283. "use strict";
  109284. var BABYLON;
  109285. (function (BABYLON) {
  109286. var GLTF2;
  109287. (function (GLTF2) {
  109288. var ArrayItem = /** @class */ (function () {
  109289. function ArrayItem() {
  109290. }
  109291. ArrayItem.Assign = function (values) {
  109292. if (values) {
  109293. for (var index = 0; index < values.length; index++) {
  109294. values[index]._index = index;
  109295. }
  109296. }
  109297. };
  109298. return ArrayItem;
  109299. }());
  109300. GLTF2.ArrayItem = ArrayItem;
  109301. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109302. })(BABYLON || (BABYLON = {}));
  109303. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  109304. "use strict";
  109305. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  109306. "use strict";
  109307. var BABYLON;
  109308. (function (BABYLON) {
  109309. var GLTF2;
  109310. (function (GLTF2) {
  109311. var GLTFLoader = /** @class */ (function () {
  109312. function GLTFLoader() {
  109313. this._completePromises = new Array();
  109314. this._disposed = false;
  109315. this._state = null;
  109316. this._extensions = {};
  109317. this._defaultSampler = {};
  109318. this._defaultBabylonMaterials = {};
  109319. this._requests = new Array();
  109320. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  109321. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  109322. this.compileMaterials = false;
  109323. this.useClipPlane = false;
  109324. this.compileShadowGenerators = false;
  109325. this.onDisposeObservable = new BABYLON.Observable();
  109326. this.onMeshLoadedObservable = new BABYLON.Observable();
  109327. this.onTextureLoadedObservable = new BABYLON.Observable();
  109328. this.onMaterialLoadedObservable = new BABYLON.Observable();
  109329. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  109330. this.onExtensionLoadedObservable = new BABYLON.Observable();
  109331. this.onCompleteObservable = new BABYLON.Observable();
  109332. }
  109333. GLTFLoader._Register = function (name, factory) {
  109334. if (GLTFLoader._Factories[name]) {
  109335. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  109336. return;
  109337. }
  109338. GLTFLoader._Factories[name] = factory;
  109339. // Keep the order of registration so that extensions registered first are called first.
  109340. GLTFLoader._Names.push(name);
  109341. };
  109342. Object.defineProperty(GLTFLoader.prototype, "state", {
  109343. get: function () {
  109344. return this._state;
  109345. },
  109346. enumerable: true,
  109347. configurable: true
  109348. });
  109349. GLTFLoader.prototype.dispose = function () {
  109350. if (this._disposed) {
  109351. return;
  109352. }
  109353. this._disposed = true;
  109354. this.onDisposeObservable.notifyObservers(this);
  109355. this.onDisposeObservable.clear();
  109356. this._clear();
  109357. };
  109358. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  109359. var _this = this;
  109360. return Promise.resolve().then(function () {
  109361. var nodes = null;
  109362. if (meshesNames) {
  109363. var nodeMap_1 = {};
  109364. if (_this._gltf.nodes) {
  109365. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  109366. var node = _a[_i];
  109367. if (node.name) {
  109368. nodeMap_1[node.name] = node;
  109369. }
  109370. }
  109371. }
  109372. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  109373. nodes = names.map(function (name) {
  109374. var node = nodeMap_1[name];
  109375. if (!node) {
  109376. throw new Error("Failed to find node '" + name + "'");
  109377. }
  109378. return node;
  109379. });
  109380. }
  109381. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  109382. return {
  109383. meshes: _this._getMeshes(),
  109384. particleSystems: [],
  109385. skeletons: _this._getSkeletons(),
  109386. };
  109387. });
  109388. });
  109389. };
  109390. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  109391. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  109392. };
  109393. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  109394. var _this = this;
  109395. return Promise.resolve().then(function () {
  109396. _this._loadExtensions();
  109397. _this._babylonScene = scene;
  109398. _this._rootUrl = rootUrl;
  109399. _this._progressCallback = onProgress;
  109400. _this._state = BABYLON.GLTFLoaderState.Loading;
  109401. _this._loadData(data);
  109402. _this._checkExtensions();
  109403. var promises = new Array();
  109404. if (nodes) {
  109405. promises.push(_this._loadNodesAsync(nodes));
  109406. }
  109407. else {
  109408. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  109409. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  109410. }
  109411. if (_this.compileMaterials) {
  109412. promises.push(_this._compileMaterialsAsync());
  109413. }
  109414. if (_this.compileShadowGenerators) {
  109415. promises.push(_this._compileShadowGeneratorsAsync());
  109416. }
  109417. var resultPromise = Promise.all(promises).then(function () {
  109418. _this._state = BABYLON.GLTFLoaderState.Ready;
  109419. _this._startAnimations();
  109420. });
  109421. resultPromise.then(function () {
  109422. _this._rootBabylonMesh.setEnabled(true);
  109423. BABYLON.Tools.SetImmediate(function () {
  109424. if (!_this._disposed) {
  109425. Promise.all(_this._completePromises).then(function () {
  109426. _this._state = BABYLON.GLTFLoaderState.Complete;
  109427. _this.onCompleteObservable.notifyObservers(_this);
  109428. _this.onCompleteObservable.clear();
  109429. _this._clear();
  109430. }).catch(function (error) {
  109431. BABYLON.Tools.Error("glTF Loader: " + error.message);
  109432. _this._clear();
  109433. });
  109434. }
  109435. });
  109436. });
  109437. return resultPromise;
  109438. }).catch(function (error) {
  109439. BABYLON.Tools.Error("glTF Loader: " + error.message);
  109440. _this._clear();
  109441. throw error;
  109442. });
  109443. };
  109444. GLTFLoader.prototype._loadExtensions = function () {
  109445. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  109446. var name_1 = _a[_i];
  109447. var extension = GLTFLoader._Factories[name_1](this);
  109448. this._extensions[name_1] = extension;
  109449. this.onExtensionLoadedObservable.notifyObservers(extension);
  109450. }
  109451. this.onExtensionLoadedObservable.clear();
  109452. };
  109453. GLTFLoader.prototype._loadData = function (data) {
  109454. this._gltf = data.json;
  109455. this._setupData();
  109456. if (data.bin) {
  109457. var buffers = this._gltf.buffers;
  109458. if (buffers && buffers[0] && !buffers[0].uri) {
  109459. var binaryBuffer = buffers[0];
  109460. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  109461. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  109462. }
  109463. binaryBuffer._data = Promise.resolve(data.bin);
  109464. }
  109465. else {
  109466. BABYLON.Tools.Warn("Unexpected BIN chunk");
  109467. }
  109468. }
  109469. };
  109470. GLTFLoader.prototype._setupData = function () {
  109471. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  109472. GLTF2.ArrayItem.Assign(this._gltf.animations);
  109473. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  109474. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  109475. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  109476. GLTF2.ArrayItem.Assign(this._gltf.images);
  109477. GLTF2.ArrayItem.Assign(this._gltf.materials);
  109478. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  109479. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  109480. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  109481. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  109482. GLTF2.ArrayItem.Assign(this._gltf.skins);
  109483. GLTF2.ArrayItem.Assign(this._gltf.textures);
  109484. if (this._gltf.nodes) {
  109485. var nodeParents = {};
  109486. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  109487. var node = _a[_i];
  109488. if (node.children) {
  109489. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  109490. var index = _c[_b];
  109491. nodeParents[index] = node._index;
  109492. }
  109493. }
  109494. }
  109495. var rootNode = this._createRootNode();
  109496. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  109497. var node = _e[_d];
  109498. var parentIndex = nodeParents[node._index];
  109499. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  109500. }
  109501. }
  109502. };
  109503. GLTFLoader.prototype._checkExtensions = function () {
  109504. if (this._gltf.extensionsRequired) {
  109505. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  109506. var name_2 = _a[_i];
  109507. var extension = this._extensions[name_2];
  109508. if (!extension || !extension.enabled) {
  109509. throw new Error("Require extension " + name_2 + " is not available");
  109510. }
  109511. }
  109512. }
  109513. };
  109514. GLTFLoader.prototype._createRootNode = function () {
  109515. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  109516. this._rootBabylonMesh.setEnabled(false);
  109517. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  109518. switch (this.coordinateSystemMode) {
  109519. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  109520. if (!this._babylonScene.useRightHandedSystem) {
  109521. rootNode.rotation = [0, 1, 0, 0];
  109522. rootNode.scale = [1, 1, -1];
  109523. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  109524. }
  109525. break;
  109526. }
  109527. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  109528. this._babylonScene.useRightHandedSystem = true;
  109529. break;
  109530. }
  109531. default: {
  109532. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  109533. }
  109534. }
  109535. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  109536. return rootNode;
  109537. };
  109538. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  109539. var promises = new Array();
  109540. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  109541. var node = nodes_1[_i];
  109542. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  109543. }
  109544. promises.push(this._loadAnimationsAsync());
  109545. return Promise.all(promises).then(function () { });
  109546. };
  109547. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  109548. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  109549. if (promise) {
  109550. return promise;
  109551. }
  109552. var promises = new Array();
  109553. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  109554. var index = _a[_i];
  109555. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  109556. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  109557. }
  109558. promises.push(this._loadAnimationsAsync());
  109559. return Promise.all(promises).then(function () { });
  109560. };
  109561. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  109562. if (node._primitiveBabylonMeshes) {
  109563. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  109564. var babylonMesh = _a[_i];
  109565. callback(babylonMesh);
  109566. }
  109567. }
  109568. else {
  109569. callback(node._babylonMesh);
  109570. }
  109571. };
  109572. GLTFLoader.prototype._getMeshes = function () {
  109573. var meshes = new Array();
  109574. // Root mesh is always first.
  109575. meshes.push(this._rootBabylonMesh);
  109576. var nodes = this._gltf.nodes;
  109577. if (nodes) {
  109578. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  109579. var node = nodes_2[_i];
  109580. if (node._babylonMesh) {
  109581. meshes.push(node._babylonMesh);
  109582. }
  109583. if (node._primitiveBabylonMeshes) {
  109584. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  109585. var babylonMesh = _b[_a];
  109586. meshes.push(babylonMesh);
  109587. }
  109588. }
  109589. }
  109590. }
  109591. return meshes;
  109592. };
  109593. GLTFLoader.prototype._getSkeletons = function () {
  109594. var skeletons = new Array();
  109595. var skins = this._gltf.skins;
  109596. if (skins) {
  109597. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  109598. var skin = skins_1[_i];
  109599. if (skin._babylonSkeleton) {
  109600. skeletons.push(skin._babylonSkeleton);
  109601. }
  109602. }
  109603. }
  109604. return skeletons;
  109605. };
  109606. GLTFLoader.prototype._startAnimations = function () {
  109607. var animations = this._gltf.animations;
  109608. if (!animations) {
  109609. return;
  109610. }
  109611. switch (this.animationStartMode) {
  109612. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  109613. // do nothing
  109614. break;
  109615. }
  109616. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  109617. var animation = animations[0];
  109618. animation._babylonAnimationGroup.start(true);
  109619. break;
  109620. }
  109621. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  109622. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  109623. var animation = animations_1[_i];
  109624. animation._babylonAnimationGroup.start(true);
  109625. }
  109626. break;
  109627. }
  109628. default: {
  109629. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  109630. return;
  109631. }
  109632. }
  109633. };
  109634. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  109635. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  109636. if (promise) {
  109637. return promise;
  109638. }
  109639. if (node._babylonMesh) {
  109640. throw new Error(context + ": Invalid recursive node hierarchy");
  109641. }
  109642. var promises = new Array();
  109643. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  109644. node._babylonMesh = babylonMesh;
  109645. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  109646. node._babylonAnimationTargets.push(babylonMesh);
  109647. GLTFLoader._LoadTransform(node, babylonMesh);
  109648. if (node.mesh != undefined) {
  109649. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  109650. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  109651. }
  109652. if (node.children) {
  109653. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  109654. var index = _a[_i];
  109655. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  109656. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  109657. }
  109658. }
  109659. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  109660. return Promise.all(promises).then(function () { });
  109661. };
  109662. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  109663. // TODO: instancing
  109664. var _this = this;
  109665. var promises = new Array();
  109666. var primitives = mesh.primitives;
  109667. if (!primitives || primitives.length === 0) {
  109668. throw new Error(context + ": Primitives are missing");
  109669. }
  109670. GLTF2.ArrayItem.Assign(primitives);
  109671. if (primitives.length === 1) {
  109672. var primitive = primitives[0];
  109673. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  109674. }
  109675. else {
  109676. node._primitiveBabylonMeshes = [];
  109677. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  109678. var primitive = primitives_1[_i];
  109679. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  109680. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  109681. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  109682. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  109683. }
  109684. }
  109685. if (node.skin != undefined) {
  109686. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  109687. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  109688. }
  109689. return Promise.all(promises).then(function () {
  109690. _this._forEachPrimitive(node, function (babylonMesh) {
  109691. babylonMesh._refreshBoundingInfo(true);
  109692. });
  109693. });
  109694. };
  109695. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  109696. var _this = this;
  109697. var promises = new Array();
  109698. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  109699. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  109700. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  109701. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  109702. }));
  109703. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  109704. if (primitive.material == undefined) {
  109705. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  109706. }
  109707. else {
  109708. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  109709. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  109710. babylonMesh.material = babylonMaterial;
  109711. }));
  109712. }
  109713. return Promise.all(promises).then(function () { });
  109714. };
  109715. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109716. var _this = this;
  109717. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  109718. if (promise) {
  109719. return promise;
  109720. }
  109721. var attributes = primitive.attributes;
  109722. if (!attributes) {
  109723. throw new Error(context + ": Attributes are missing");
  109724. }
  109725. var promises = new Array();
  109726. var babylonVertexData = new BABYLON.VertexData();
  109727. if (primitive.indices == undefined) {
  109728. var positionAccessorIndex = attributes["POSITION"];
  109729. if (positionAccessorIndex != undefined) {
  109730. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  109731. babylonVertexData.indices = new Uint32Array(accessor.count);
  109732. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  109733. babylonVertexData.indices[i] = i;
  109734. }
  109735. }
  109736. }
  109737. else {
  109738. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  109739. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  109740. babylonVertexData.indices = data;
  109741. }));
  109742. }
  109743. var loadAttribute = function (attribute, kind) {
  109744. if (attributes[attribute] == undefined) {
  109745. return;
  109746. }
  109747. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109748. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109749. babylonMesh._delayInfo.push(kind);
  109750. }
  109751. if (attribute === "COLOR_0") {
  109752. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  109753. babylonMesh.hasVertexAlpha = true;
  109754. }
  109755. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109756. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109757. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  109758. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  109759. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  109760. }
  109761. babylonVertexData.set(attributeData, kind);
  109762. }));
  109763. };
  109764. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109765. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109766. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109767. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109768. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109769. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109770. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109771. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  109772. return Promise.all(promises).then(function () {
  109773. return babylonVertexData;
  109774. });
  109775. };
  109776. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  109777. if (!primitive.targets) {
  109778. return;
  109779. }
  109780. if (node._numMorphTargets == undefined) {
  109781. node._numMorphTargets = primitive.targets.length;
  109782. }
  109783. else if (primitive.targets.length !== node._numMorphTargets) {
  109784. throw new Error(context + ": Primitives do not have the same number of targets");
  109785. }
  109786. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  109787. for (var index = 0; index < primitive.targets.length; index++) {
  109788. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  109789. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  109790. // TODO: tell the target whether it has positions, normals, tangents
  109791. }
  109792. };
  109793. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  109794. if (!primitive.targets) {
  109795. return Promise.resolve();
  109796. }
  109797. var promises = new Array();
  109798. var morphTargetManager = babylonMesh.morphTargetManager;
  109799. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  109800. var babylonMorphTarget = morphTargetManager.getTarget(index);
  109801. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  109802. }
  109803. return Promise.all(promises).then(function () { });
  109804. };
  109805. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  109806. var _this = this;
  109807. var promises = new Array();
  109808. var loadAttribute = function (attribute, setData) {
  109809. if (attributes[attribute] == undefined) {
  109810. return;
  109811. }
  109812. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109813. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109814. setData(data);
  109815. }));
  109816. };
  109817. loadAttribute("POSITION", function (data) {
  109818. if (babylonVertexData.positions) {
  109819. for (var i = 0; i < data.length; i++) {
  109820. data[i] += babylonVertexData.positions[i];
  109821. }
  109822. babylonMorphTarget.setPositions(data);
  109823. }
  109824. });
  109825. loadAttribute("NORMAL", function (data) {
  109826. if (babylonVertexData.normals) {
  109827. for (var i = 0; i < data.length; i++) {
  109828. data[i] += babylonVertexData.normals[i];
  109829. }
  109830. babylonMorphTarget.setNormals(data);
  109831. }
  109832. });
  109833. loadAttribute("TANGENT", function (data) {
  109834. if (babylonVertexData.tangents) {
  109835. // Tangent data for morph targets is stored as xyz delta.
  109836. // The vertexData.tangent is stored as xyzw.
  109837. // So we need to skip every fourth vertexData.tangent.
  109838. for (var i = 0, j = 0; i < data.length; i++) {
  109839. data[i] += babylonVertexData.tangents[j++];
  109840. if ((i + 1) % 3 == 0) {
  109841. j++;
  109842. }
  109843. }
  109844. babylonMorphTarget.setTangents(data);
  109845. }
  109846. });
  109847. return Promise.all(promises).then(function () { });
  109848. };
  109849. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  109850. if (accessor.componentType == 5126 /* FLOAT */) {
  109851. return data;
  109852. }
  109853. var factor = 1;
  109854. if (accessor.normalized) {
  109855. switch (accessor.componentType) {
  109856. case 5121 /* UNSIGNED_BYTE */: {
  109857. factor = 1 / 255;
  109858. break;
  109859. }
  109860. case 5123 /* UNSIGNED_SHORT */: {
  109861. factor = 1 / 65535;
  109862. break;
  109863. }
  109864. default: {
  109865. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  109866. }
  109867. }
  109868. }
  109869. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  109870. for (var i = 0; i < result.length; i++) {
  109871. result[i] = data[i] * factor;
  109872. }
  109873. return result;
  109874. };
  109875. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  109876. var result = new Float32Array(data.length / 3 * 4);
  109877. var offset = 0;
  109878. for (var i = 0; i < result.length; i++) {
  109879. if ((i + 1) % 4 === 0) {
  109880. result[i] = 1;
  109881. }
  109882. else {
  109883. result[i] = data[offset++];
  109884. }
  109885. }
  109886. return result;
  109887. };
  109888. GLTFLoader._LoadTransform = function (node, babylonNode) {
  109889. var position = BABYLON.Vector3.Zero();
  109890. var rotation = BABYLON.Quaternion.Identity();
  109891. var scaling = BABYLON.Vector3.One();
  109892. if (node.matrix) {
  109893. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  109894. matrix.decompose(scaling, rotation, position);
  109895. }
  109896. else {
  109897. if (node.translation)
  109898. position = BABYLON.Vector3.FromArray(node.translation);
  109899. if (node.rotation)
  109900. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  109901. if (node.scale)
  109902. scaling = BABYLON.Vector3.FromArray(node.scale);
  109903. }
  109904. babylonNode.position = position;
  109905. babylonNode.rotationQuaternion = rotation;
  109906. babylonNode.scaling = scaling;
  109907. };
  109908. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  109909. var _this = this;
  109910. var assignSkeleton = function () {
  109911. _this._forEachPrimitive(node, function (babylonMesh) {
  109912. babylonMesh.skeleton = skin._babylonSkeleton;
  109913. });
  109914. node._babylonMesh.parent = _this._rootBabylonMesh;
  109915. node._babylonMesh.position = BABYLON.Vector3.Zero();
  109916. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  109917. node._babylonMesh.scaling = BABYLON.Vector3.One();
  109918. };
  109919. if (skin._loaded) {
  109920. return skin._loaded.then(function () {
  109921. assignSkeleton();
  109922. });
  109923. }
  109924. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  109925. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  109926. var skeletonId = "skeleton" + skin._index;
  109927. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  109928. skin._babylonSkeleton = babylonSkeleton;
  109929. _this._loadBones(context, skin, inverseBindMatricesData);
  109930. assignSkeleton();
  109931. }));
  109932. };
  109933. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  109934. if (skin.inverseBindMatrices == undefined) {
  109935. return Promise.resolve(null);
  109936. }
  109937. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  109938. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109939. return data;
  109940. });
  109941. };
  109942. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  109943. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  109944. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  109945. node._babylonAnimationTargets.push(babylonBone);
  109946. return babylonBone;
  109947. };
  109948. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  109949. var babylonBones = {};
  109950. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  109951. var index = _a[_i];
  109952. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  109953. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  109954. }
  109955. };
  109956. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  109957. var babylonBone = babylonBones[node._index];
  109958. if (babylonBone) {
  109959. return babylonBone;
  109960. }
  109961. var boneIndex = skin.joints.indexOf(node._index);
  109962. var baseMatrix = BABYLON.Matrix.Identity();
  109963. if (inverseBindMatricesData && boneIndex !== -1) {
  109964. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  109965. baseMatrix.invertToRef(baseMatrix);
  109966. }
  109967. var babylonParentBone = null;
  109968. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  109969. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  109970. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  109971. }
  109972. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  109973. babylonBones[node._index] = babylonBone;
  109974. return babylonBone;
  109975. };
  109976. GLTFLoader.prototype._getNodeMatrix = function (node) {
  109977. return node.matrix ?
  109978. BABYLON.Matrix.FromArray(node.matrix) :
  109979. 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());
  109980. };
  109981. GLTFLoader.prototype._loadAnimationsAsync = function () {
  109982. var animations = this._gltf.animations;
  109983. if (!animations) {
  109984. return Promise.resolve();
  109985. }
  109986. var promises = new Array();
  109987. for (var index = 0; index < animations.length; index++) {
  109988. var animation = animations[index];
  109989. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  109990. }
  109991. return Promise.all(promises).then(function () { });
  109992. };
  109993. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  109994. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  109995. animation._babylonAnimationGroup = babylonAnimationGroup;
  109996. var promises = new Array();
  109997. GLTF2.ArrayItem.Assign(animation.channels);
  109998. GLTF2.ArrayItem.Assign(animation.samplers);
  109999. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  110000. var channel = _a[_i];
  110001. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  110002. }
  110003. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  110004. return Promise.all(promises).then(function () {
  110005. babylonAnimationGroup.normalize();
  110006. });
  110007. };
  110008. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  110009. var _this = this;
  110010. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  110011. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  110012. return Promise.resolve();
  110013. }
  110014. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  110015. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  110016. var targetPath;
  110017. var animationType;
  110018. switch (channel.target.path) {
  110019. case "translation" /* TRANSLATION */: {
  110020. targetPath = "position";
  110021. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  110022. break;
  110023. }
  110024. case "rotation" /* ROTATION */: {
  110025. targetPath = "rotationQuaternion";
  110026. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  110027. break;
  110028. }
  110029. case "scale" /* SCALE */: {
  110030. targetPath = "scaling";
  110031. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  110032. break;
  110033. }
  110034. case "weights" /* WEIGHTS */: {
  110035. targetPath = "influence";
  110036. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  110037. break;
  110038. }
  110039. default: {
  110040. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  110041. }
  110042. }
  110043. var outputBufferOffset = 0;
  110044. var getNextOutputValue;
  110045. switch (targetPath) {
  110046. case "position": {
  110047. getNextOutputValue = function () {
  110048. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  110049. outputBufferOffset += 3;
  110050. return value;
  110051. };
  110052. break;
  110053. }
  110054. case "rotationQuaternion": {
  110055. getNextOutputValue = function () {
  110056. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  110057. outputBufferOffset += 4;
  110058. return value;
  110059. };
  110060. break;
  110061. }
  110062. case "scaling": {
  110063. getNextOutputValue = function () {
  110064. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  110065. outputBufferOffset += 3;
  110066. return value;
  110067. };
  110068. break;
  110069. }
  110070. case "influence": {
  110071. getNextOutputValue = function () {
  110072. var value = new Array(targetNode._numMorphTargets);
  110073. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  110074. value[i] = data.output[outputBufferOffset++];
  110075. }
  110076. return value;
  110077. };
  110078. break;
  110079. }
  110080. }
  110081. var getNextKey;
  110082. switch (data.interpolation) {
  110083. case "STEP" /* STEP */: {
  110084. getNextKey = function (frameIndex) { return ({
  110085. frame: data.input[frameIndex],
  110086. value: getNextOutputValue(),
  110087. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  110088. }); };
  110089. break;
  110090. }
  110091. case "LINEAR" /* LINEAR */: {
  110092. getNextKey = function (frameIndex) { return ({
  110093. frame: data.input[frameIndex],
  110094. value: getNextOutputValue()
  110095. }); };
  110096. break;
  110097. }
  110098. case "CUBICSPLINE" /* CUBICSPLINE */: {
  110099. getNextKey = function (frameIndex) { return ({
  110100. frame: data.input[frameIndex],
  110101. inTangent: getNextOutputValue(),
  110102. value: getNextOutputValue(),
  110103. outTangent: getNextOutputValue()
  110104. }); };
  110105. break;
  110106. }
  110107. }
  110108. var keys = new Array(data.input.length);
  110109. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  110110. keys[frameIndex] = getNextKey(frameIndex);
  110111. }
  110112. if (targetPath === "influence") {
  110113. var _loop_1 = function (targetIndex) {
  110114. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  110115. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  110116. babylonAnimation.setKeys(keys.map(function (key) { return ({
  110117. frame: key.frame,
  110118. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  110119. value: key.value[targetIndex],
  110120. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  110121. }); }));
  110122. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  110123. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  110124. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  110125. });
  110126. };
  110127. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  110128. _loop_1(targetIndex);
  110129. }
  110130. }
  110131. else {
  110132. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  110133. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  110134. babylonAnimation.setKeys(keys);
  110135. if (targetNode._babylonAnimationTargets) {
  110136. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  110137. var target = _a[_i];
  110138. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  110139. }
  110140. }
  110141. }
  110142. });
  110143. };
  110144. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  110145. if (sampler._data) {
  110146. return sampler._data;
  110147. }
  110148. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  110149. switch (interpolation) {
  110150. case "STEP" /* STEP */:
  110151. case "LINEAR" /* LINEAR */:
  110152. case "CUBICSPLINE" /* CUBICSPLINE */: {
  110153. break;
  110154. }
  110155. default: {
  110156. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  110157. }
  110158. }
  110159. var inputData;
  110160. var outputData;
  110161. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  110162. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  110163. sampler._data = Promise.all([
  110164. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  110165. inputData = data;
  110166. }),
  110167. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  110168. outputData = data;
  110169. })
  110170. ]).then(function () {
  110171. return {
  110172. input: inputData,
  110173. interpolation: interpolation,
  110174. output: outputData,
  110175. };
  110176. });
  110177. return sampler._data;
  110178. };
  110179. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  110180. if (buffer._data) {
  110181. return buffer._data;
  110182. }
  110183. if (!buffer.uri) {
  110184. throw new Error(context + ": Uri is missing");
  110185. }
  110186. buffer._data = this._loadUriAsync(context, buffer.uri);
  110187. return buffer._data;
  110188. };
  110189. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  110190. if (bufferView._data) {
  110191. return bufferView._data;
  110192. }
  110193. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  110194. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  110195. try {
  110196. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  110197. }
  110198. catch (e) {
  110199. throw new Error(context + ": " + e.message);
  110200. }
  110201. });
  110202. return bufferView._data;
  110203. };
  110204. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  110205. var _this = this;
  110206. if (accessor.sparse) {
  110207. throw new Error(context + ": Sparse accessors are not currently supported");
  110208. }
  110209. if (accessor._data) {
  110210. return accessor._data;
  110211. }
  110212. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  110213. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  110214. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  110215. var byteOffset = accessor.byteOffset || 0;
  110216. var byteStride = bufferView.byteStride;
  110217. if (byteStride === 0) {
  110218. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  110219. }
  110220. try {
  110221. switch (accessor.componentType) {
  110222. case 5120 /* BYTE */: {
  110223. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  110224. }
  110225. case 5121 /* UNSIGNED_BYTE */: {
  110226. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  110227. }
  110228. case 5122 /* SHORT */: {
  110229. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  110230. }
  110231. case 5123 /* UNSIGNED_SHORT */: {
  110232. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  110233. }
  110234. case 5125 /* UNSIGNED_INT */: {
  110235. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  110236. }
  110237. case 5126 /* FLOAT */: {
  110238. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  110239. }
  110240. default: {
  110241. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  110242. }
  110243. }
  110244. }
  110245. catch (e) {
  110246. throw new Error(context + ": " + e.messsage);
  110247. }
  110248. });
  110249. return accessor._data;
  110250. };
  110251. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  110252. byteOffset += data.byteOffset;
  110253. var targetLength = count * numComponents;
  110254. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  110255. return new typedArray(data.buffer, byteOffset, targetLength);
  110256. }
  110257. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  110258. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  110259. var targetBuffer = new typedArray(targetLength);
  110260. var sourceIndex = 0;
  110261. var targetIndex = 0;
  110262. while (targetIndex < targetLength) {
  110263. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  110264. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  110265. targetIndex++;
  110266. }
  110267. sourceIndex += elementStride;
  110268. }
  110269. return targetBuffer;
  110270. };
  110271. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  110272. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  110273. if (!babylonMaterial) {
  110274. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  110275. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  110276. babylonMaterial.metallic = 1;
  110277. babylonMaterial.roughness = 1;
  110278. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110279. }
  110280. return babylonMaterial;
  110281. };
  110282. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  110283. var promises = new Array();
  110284. // Ensure metallic workflow
  110285. babylonMaterial.metallic = 1;
  110286. babylonMaterial.roughness = 1;
  110287. var properties = material.pbrMetallicRoughness;
  110288. if (properties) {
  110289. if (properties.baseColorFactor) {
  110290. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  110291. babylonMaterial.alpha = properties.baseColorFactor[3];
  110292. }
  110293. else {
  110294. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110295. }
  110296. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  110297. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  110298. if (properties.baseColorTexture) {
  110299. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  110300. babylonMaterial.albedoTexture = texture;
  110301. }));
  110302. }
  110303. if (properties.metallicRoughnessTexture) {
  110304. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  110305. babylonMaterial.metallicTexture = texture;
  110306. }));
  110307. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  110308. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  110309. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  110310. }
  110311. }
  110312. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  110313. return Promise.all(promises).then(function () { });
  110314. };
  110315. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  110316. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  110317. if (promise) {
  110318. return promise;
  110319. }
  110320. material._babylonData = material._babylonData || {};
  110321. var babylonData = material._babylonData[babylonDrawMode];
  110322. if (!babylonData) {
  110323. var promises = new Array();
  110324. var name_3 = material.name || "materialSG_" + material._index;
  110325. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  110326. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  110327. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  110328. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110329. babylonData = {
  110330. material: babylonMaterial,
  110331. meshes: [],
  110332. loaded: Promise.all(promises).then(function () { })
  110333. };
  110334. material._babylonData[babylonDrawMode] = babylonData;
  110335. }
  110336. babylonData.meshes.push(babylonMesh);
  110337. assign(babylonData.material);
  110338. return babylonData.loaded;
  110339. };
  110340. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  110341. var babylonMaterial = new type(name, this._babylonScene);
  110342. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  110343. babylonMaterial.fillMode = drawMode;
  110344. return babylonMaterial;
  110345. };
  110346. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  110347. var promises = new Array();
  110348. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  110349. if (material.doubleSided) {
  110350. babylonMaterial.backFaceCulling = false;
  110351. babylonMaterial.twoSidedLighting = true;
  110352. }
  110353. if (material.normalTexture) {
  110354. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  110355. babylonMaterial.bumpTexture = texture;
  110356. }));
  110357. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  110358. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  110359. if (material.normalTexture.scale != undefined) {
  110360. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  110361. }
  110362. }
  110363. if (material.occlusionTexture) {
  110364. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  110365. babylonMaterial.ambientTexture = texture;
  110366. }));
  110367. babylonMaterial.useAmbientInGrayScale = true;
  110368. if (material.occlusionTexture.strength != undefined) {
  110369. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  110370. }
  110371. }
  110372. if (material.emissiveTexture) {
  110373. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  110374. babylonMaterial.emissiveTexture = texture;
  110375. }));
  110376. }
  110377. return Promise.all(promises).then(function () { });
  110378. };
  110379. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  110380. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  110381. switch (alphaMode) {
  110382. case "OPAQUE" /* OPAQUE */: {
  110383. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  110384. break;
  110385. }
  110386. case "MASK" /* MASK */: {
  110387. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  110388. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  110389. if (babylonMaterial.alpha) {
  110390. if (babylonMaterial.alpha === 0) {
  110391. babylonMaterial.alphaCutOff = 1;
  110392. }
  110393. else {
  110394. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  110395. }
  110396. babylonMaterial.alpha = 1;
  110397. }
  110398. if (babylonMaterial.albedoTexture) {
  110399. babylonMaterial.albedoTexture.hasAlpha = true;
  110400. }
  110401. break;
  110402. }
  110403. case "BLEND" /* BLEND */: {
  110404. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  110405. if (babylonMaterial.albedoTexture) {
  110406. babylonMaterial.albedoTexture.hasAlpha = true;
  110407. babylonMaterial.useAlphaFromAlbedoTexture = true;
  110408. }
  110409. break;
  110410. }
  110411. default: {
  110412. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  110413. }
  110414. }
  110415. };
  110416. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  110417. var _this = this;
  110418. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  110419. context = "#/textures/" + textureInfo.index;
  110420. var promises = new Array();
  110421. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  110422. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  110423. var deferred = new BABYLON.Deferred();
  110424. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  110425. if (!_this._disposed) {
  110426. deferred.resolve();
  110427. }
  110428. }, function (message, exception) {
  110429. if (!_this._disposed) {
  110430. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  110431. }
  110432. });
  110433. promises.push(deferred.promise);
  110434. babylonTexture.name = texture.name || "texture" + texture._index;
  110435. babylonTexture.wrapU = samplerData.wrapU;
  110436. babylonTexture.wrapV = samplerData.wrapV;
  110437. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  110438. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  110439. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  110440. babylonTexture.updateURL(objectURL);
  110441. }));
  110442. assign(babylonTexture);
  110443. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  110444. return Promise.all(promises).then(function () { });
  110445. };
  110446. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  110447. if (!sampler._data) {
  110448. sampler._data = {
  110449. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  110450. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  110451. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  110452. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  110453. };
  110454. }
  110455. ;
  110456. return sampler._data;
  110457. };
  110458. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  110459. if (image._objectURL) {
  110460. return image._objectURL;
  110461. }
  110462. var promise;
  110463. if (image.uri) {
  110464. promise = this._loadUriAsync(context, image.uri);
  110465. }
  110466. else {
  110467. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  110468. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  110469. }
  110470. image._objectURL = promise.then(function (data) {
  110471. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  110472. });
  110473. return image._objectURL;
  110474. };
  110475. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  110476. var _this = this;
  110477. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  110478. if (promise) {
  110479. return promise;
  110480. }
  110481. if (!GLTFLoader._ValidateUri(uri)) {
  110482. throw new Error(context + ": Uri '" + uri + "' is invalid");
  110483. }
  110484. if (BABYLON.Tools.IsBase64(uri)) {
  110485. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  110486. }
  110487. return new Promise(function (resolve, reject) {
  110488. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  110489. if (!_this._disposed) {
  110490. resolve(new Uint8Array(data));
  110491. }
  110492. }, function (event) {
  110493. if (!_this._disposed) {
  110494. try {
  110495. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  110496. request._lengthComputable = event.lengthComputable;
  110497. request._loaded = event.loaded;
  110498. request._total = event.total;
  110499. _this._onProgress();
  110500. }
  110501. }
  110502. catch (e) {
  110503. reject(e);
  110504. }
  110505. }
  110506. }, _this._babylonScene.database, true, function (request, exception) {
  110507. if (!_this._disposed) {
  110508. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  110509. }
  110510. });
  110511. _this._requests.push(request);
  110512. });
  110513. };
  110514. GLTFLoader.prototype._onProgress = function () {
  110515. if (!this._progressCallback) {
  110516. return;
  110517. }
  110518. var lengthComputable = true;
  110519. var loaded = 0;
  110520. var total = 0;
  110521. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  110522. var request = _a[_i];
  110523. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  110524. return;
  110525. }
  110526. lengthComputable = lengthComputable && request._lengthComputable;
  110527. loaded += request._loaded;
  110528. total += request._total;
  110529. }
  110530. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  110531. };
  110532. GLTFLoader._GetProperty = function (context, array, index) {
  110533. if (!array || index == undefined || !array[index]) {
  110534. throw new Error(context + ": Failed to find index (" + index + ")");
  110535. }
  110536. return array[index];
  110537. };
  110538. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  110539. // Set defaults if undefined
  110540. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  110541. switch (mode) {
  110542. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  110543. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  110544. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  110545. default:
  110546. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  110547. return BABYLON.Texture.WRAP_ADDRESSMODE;
  110548. }
  110549. };
  110550. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  110551. // Set defaults if undefined
  110552. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  110553. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  110554. if (magFilter === 9729 /* LINEAR */) {
  110555. switch (minFilter) {
  110556. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  110557. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  110558. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  110559. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  110560. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  110561. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  110562. default:
  110563. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  110564. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  110565. }
  110566. }
  110567. else {
  110568. if (magFilter !== 9728 /* NEAREST */) {
  110569. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  110570. }
  110571. switch (minFilter) {
  110572. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  110573. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  110574. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  110575. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  110576. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  110577. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  110578. default:
  110579. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  110580. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  110581. }
  110582. }
  110583. };
  110584. GLTFLoader._GetNumComponents = function (context, type) {
  110585. switch (type) {
  110586. case "SCALAR": return 1;
  110587. case "VEC2": return 2;
  110588. case "VEC3": return 3;
  110589. case "VEC4": return 4;
  110590. case "MAT2": return 4;
  110591. case "MAT3": return 9;
  110592. case "MAT4": return 16;
  110593. }
  110594. throw new Error(context + ": Invalid type (" + type + ")");
  110595. };
  110596. GLTFLoader._ValidateUri = function (uri) {
  110597. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  110598. };
  110599. GLTFLoader._GetDrawMode = function (context, mode) {
  110600. mode = mode || 4 /* TRIANGLES */;
  110601. switch (mode) {
  110602. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  110603. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  110604. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  110605. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  110606. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  110607. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  110608. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  110609. }
  110610. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  110611. };
  110612. GLTFLoader.prototype._compileMaterialsAsync = function () {
  110613. var promises = new Array();
  110614. if (this._gltf.materials) {
  110615. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  110616. var material = _a[_i];
  110617. if (material._babylonData) {
  110618. for (var babylonDrawMode in material._babylonData) {
  110619. var babylonData = material._babylonData[babylonDrawMode];
  110620. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  110621. var babylonMesh = _c[_b];
  110622. // Ensure nonUniformScaling is set if necessary.
  110623. babylonMesh.computeWorldMatrix(true);
  110624. var babylonMaterial = babylonData.material;
  110625. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  110626. if (this.useClipPlane) {
  110627. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  110628. }
  110629. }
  110630. }
  110631. }
  110632. }
  110633. }
  110634. return Promise.all(promises).then(function () { });
  110635. };
  110636. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  110637. var promises = new Array();
  110638. var lights = this._babylonScene.lights;
  110639. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  110640. var light = lights_1[_i];
  110641. var generator = light.getShadowGenerator();
  110642. if (generator) {
  110643. promises.push(generator.forceCompilationAsync());
  110644. }
  110645. }
  110646. return Promise.all(promises).then(function () { });
  110647. };
  110648. GLTFLoader.prototype._clear = function () {
  110649. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  110650. var request = _a[_i];
  110651. request.abort();
  110652. }
  110653. this._requests.length = 0;
  110654. if (this._gltf && this._gltf.images) {
  110655. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  110656. var image = _c[_b];
  110657. if (image._objectURL) {
  110658. image._objectURL.then(function (value) {
  110659. URL.revokeObjectURL(value);
  110660. });
  110661. image._objectURL = undefined;
  110662. }
  110663. }
  110664. }
  110665. delete this._gltf;
  110666. delete this._babylonScene;
  110667. this._completePromises.length = 0;
  110668. for (var name_4 in this._extensions) {
  110669. this._extensions[name_4].dispose();
  110670. }
  110671. this._extensions = {};
  110672. delete this._rootBabylonMesh;
  110673. delete this._progressCallback;
  110674. this.onMeshLoadedObservable.clear();
  110675. this.onTextureLoadedObservable.clear();
  110676. this.onMaterialLoadedObservable.clear();
  110677. };
  110678. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  110679. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  110680. var name_5 = _a[_i];
  110681. var extension = this._extensions[name_5];
  110682. if (extension.enabled) {
  110683. var promise = actionAsync(extension);
  110684. if (promise) {
  110685. return promise;
  110686. }
  110687. }
  110688. }
  110689. return null;
  110690. };
  110691. GLTFLoader._Names = new Array();
  110692. GLTFLoader._Factories = {};
  110693. return GLTFLoader;
  110694. }());
  110695. GLTF2.GLTFLoader = GLTFLoader;
  110696. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  110697. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110698. })(BABYLON || (BABYLON = {}));
  110699. //# sourceMappingURL=babylon.glTFLoader.js.map
  110700. "use strict";
  110701. var BABYLON;
  110702. (function (BABYLON) {
  110703. var GLTF2;
  110704. (function (GLTF2) {
  110705. var GLTFLoaderExtension = /** @class */ (function () {
  110706. function GLTFLoaderExtension(loader) {
  110707. this.enabled = true;
  110708. this._loader = loader;
  110709. }
  110710. GLTFLoaderExtension.prototype.dispose = function () {
  110711. delete this._loader;
  110712. };
  110713. // #region Overridable Methods
  110714. /** Override this method to modify the default behavior for loading scenes. */
  110715. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  110716. /** Override this method to modify the default behavior for loading nodes. */
  110717. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  110718. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  110719. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  110720. /** Override this method to modify the default behavior for loading materials. */
  110721. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  110722. /** Override this method to modify the default behavior for loading uris. */
  110723. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  110724. // #endregion
  110725. /** Helper method called by a loader extension to load an glTF extension. */
  110726. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  110727. if (!property.extensions) {
  110728. return null;
  110729. }
  110730. var extensions = property.extensions;
  110731. var extension = extensions[this.name];
  110732. if (!extension) {
  110733. return null;
  110734. }
  110735. // Clear out the extension before executing the action to avoid recursing into the same property.
  110736. delete extensions[this.name];
  110737. try {
  110738. return actionAsync(context + "/extensions/" + this.name, extension);
  110739. }
  110740. finally {
  110741. // Restore the extension after executing the action.
  110742. extensions[this.name] = extension;
  110743. }
  110744. };
  110745. /** Helper method called by the loader to allow extensions to override loading scenes. */
  110746. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  110747. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  110748. };
  110749. /** Helper method called by the loader to allow extensions to override loading nodes. */
  110750. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  110751. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  110752. };
  110753. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  110754. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  110755. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  110756. };
  110757. /** Helper method called by the loader to allow extensions to override loading materials. */
  110758. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  110759. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  110760. };
  110761. /** Helper method called by the loader to allow extensions to override loading uris. */
  110762. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  110763. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  110764. };
  110765. return GLTFLoaderExtension;
  110766. }());
  110767. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  110768. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110769. })(BABYLON || (BABYLON = {}));
  110770. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  110771. "use strict";
  110772. var BABYLON;
  110773. (function (BABYLON) {
  110774. var GLTF2;
  110775. (function (GLTF2) {
  110776. var Extensions;
  110777. (function (Extensions) {
  110778. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  110779. var NAME = "MSFT_lod";
  110780. var MSFT_lod = /** @class */ (function (_super) {
  110781. __extends(MSFT_lod, _super);
  110782. function MSFT_lod() {
  110783. var _this = _super !== null && _super.apply(this, arguments) || this;
  110784. _this.name = NAME;
  110785. /**
  110786. * Maximum number of LODs to load, starting from the lowest LOD.
  110787. */
  110788. _this.maxLODsToLoad = Number.MAX_VALUE;
  110789. _this._loadingNodeLOD = null;
  110790. _this._loadNodeSignals = {};
  110791. _this._loadingMaterialLOD = null;
  110792. _this._loadMaterialSignals = {};
  110793. return _this;
  110794. }
  110795. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  110796. var _this = this;
  110797. return this._loadExtensionAsync(context, node, function (context, extension) {
  110798. var firstPromise;
  110799. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  110800. var _loop_1 = function (indexLOD) {
  110801. var nodeLOD = nodeLODs[indexLOD];
  110802. if (indexLOD !== 0) {
  110803. _this._loadingNodeLOD = nodeLOD;
  110804. if (!_this._loadNodeSignals[nodeLOD._index]) {
  110805. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  110806. }
  110807. }
  110808. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  110809. if (indexLOD !== 0) {
  110810. var previousNodeLOD = nodeLODs[indexLOD - 1];
  110811. if (previousNodeLOD._babylonMesh) {
  110812. previousNodeLOD._babylonMesh.dispose();
  110813. delete previousNodeLOD._babylonMesh;
  110814. }
  110815. }
  110816. if (indexLOD !== nodeLODs.length - 1) {
  110817. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  110818. if (_this._loadNodeSignals[nodeIndex]) {
  110819. _this._loadNodeSignals[nodeIndex].resolve();
  110820. delete _this._loadNodeSignals[nodeIndex];
  110821. }
  110822. }
  110823. });
  110824. if (indexLOD === 0) {
  110825. firstPromise = promise;
  110826. }
  110827. else {
  110828. _this._loader._completePromises.push(promise);
  110829. _this._loadingNodeLOD = null;
  110830. }
  110831. };
  110832. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  110833. _loop_1(indexLOD);
  110834. }
  110835. return firstPromise;
  110836. });
  110837. };
  110838. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  110839. var _this = this;
  110840. // Don't load material LODs if already loading a node LOD.
  110841. if (this._loadingNodeLOD) {
  110842. return null;
  110843. }
  110844. return this._loadExtensionAsync(context, material, function (context, extension) {
  110845. var firstPromise;
  110846. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  110847. var _loop_2 = function (indexLOD) {
  110848. var materialLOD = materialLODs[indexLOD];
  110849. if (indexLOD !== 0) {
  110850. _this._loadingMaterialLOD = materialLOD;
  110851. if (!_this._loadMaterialSignals[materialLOD._index]) {
  110852. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  110853. }
  110854. }
  110855. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  110856. if (indexLOD !== 0) {
  110857. var babylonDataLOD = materialLOD._babylonData;
  110858. assign(babylonDataLOD[babylonDrawMode].material);
  110859. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  110860. if (previousBabylonDataLOD[babylonDrawMode]) {
  110861. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  110862. delete previousBabylonDataLOD[babylonDrawMode];
  110863. }
  110864. }
  110865. if (indexLOD !== materialLODs.length - 1) {
  110866. var materialIndex = materialLODs[indexLOD + 1]._index;
  110867. if (_this._loadMaterialSignals[materialIndex]) {
  110868. _this._loadMaterialSignals[materialIndex].resolve();
  110869. delete _this._loadMaterialSignals[materialIndex];
  110870. }
  110871. }
  110872. });
  110873. if (indexLOD === 0) {
  110874. firstPromise = promise;
  110875. }
  110876. else {
  110877. _this._loader._completePromises.push(promise);
  110878. _this._loadingMaterialLOD = null;
  110879. }
  110880. };
  110881. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  110882. _loop_2(indexLOD);
  110883. }
  110884. return firstPromise;
  110885. });
  110886. };
  110887. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  110888. var _this = this;
  110889. // Defer the loading of uris if loading a material or node LOD.
  110890. if (this._loadingMaterialLOD) {
  110891. var index = this._loadingMaterialLOD._index;
  110892. return this._loadMaterialSignals[index].promise.then(function () {
  110893. return _this._loader._loadUriAsync(context, uri);
  110894. });
  110895. }
  110896. else if (this._loadingNodeLOD) {
  110897. var index = this._loadingNodeLOD._index;
  110898. return this._loadNodeSignals[index].promise.then(function () {
  110899. return _this._loader._loadUriAsync(context, uri);
  110900. });
  110901. }
  110902. return null;
  110903. };
  110904. /**
  110905. * Gets an array of LOD properties from lowest to highest.
  110906. */
  110907. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  110908. if (this.maxLODsToLoad <= 0) {
  110909. throw new Error("maxLODsToLoad must be greater than zero");
  110910. }
  110911. var properties = new Array();
  110912. for (var i = ids.length - 1; i >= 0; i--) {
  110913. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  110914. if (properties.length === this.maxLODsToLoad) {
  110915. return properties;
  110916. }
  110917. }
  110918. properties.push(property);
  110919. return properties;
  110920. };
  110921. return MSFT_lod;
  110922. }(GLTF2.GLTFLoaderExtension));
  110923. Extensions.MSFT_lod = MSFT_lod;
  110924. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  110925. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110926. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110927. })(BABYLON || (BABYLON = {}));
  110928. //# sourceMappingURL=MSFT_lod.js.map
  110929. "use strict";
  110930. var BABYLON;
  110931. (function (BABYLON) {
  110932. var GLTF2;
  110933. (function (GLTF2) {
  110934. var Extensions;
  110935. (function (Extensions) {
  110936. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  110937. var NAME = "KHR_draco_mesh_compression";
  110938. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  110939. __extends(KHR_draco_mesh_compression, _super);
  110940. function KHR_draco_mesh_compression(loader) {
  110941. var _this = _super.call(this, loader) || this;
  110942. _this.name = NAME;
  110943. _this._dracoCompression = null;
  110944. // Disable extension if decoder is not available.
  110945. if (!BABYLON.DracoCompression.DecoderUrl) {
  110946. _this.enabled = false;
  110947. }
  110948. return _this;
  110949. }
  110950. KHR_draco_mesh_compression.prototype.dispose = function () {
  110951. if (this._dracoCompression) {
  110952. this._dracoCompression.dispose();
  110953. }
  110954. _super.prototype.dispose.call(this);
  110955. };
  110956. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  110957. var _this = this;
  110958. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  110959. if (primitive.mode != undefined) {
  110960. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  110961. primitive.mode !== 4 /* TRIANGLES */) {
  110962. throw new Error(context + ": Unsupported mode " + primitive.mode);
  110963. }
  110964. // TODO: handle triangle strips
  110965. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  110966. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  110967. }
  110968. }
  110969. var attributes = {};
  110970. var loadAttribute = function (name, kind) {
  110971. var uniqueId = extension.attributes[name];
  110972. if (uniqueId == undefined) {
  110973. return;
  110974. }
  110975. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  110976. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  110977. babylonMesh._delayInfo.push(kind);
  110978. }
  110979. attributes[kind] = uniqueId;
  110980. };
  110981. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  110982. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  110983. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  110984. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  110985. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  110986. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  110987. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  110988. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  110989. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  110990. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110991. try {
  110992. if (!_this._dracoCompression) {
  110993. _this._dracoCompression = new BABYLON.DracoCompression();
  110994. }
  110995. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  110996. }
  110997. catch (e) {
  110998. throw new Error(context + ": " + e.message);
  110999. }
  111000. });
  111001. });
  111002. };
  111003. return KHR_draco_mesh_compression;
  111004. }(GLTF2.GLTFLoaderExtension));
  111005. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  111006. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  111007. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111008. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111009. })(BABYLON || (BABYLON = {}));
  111010. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  111011. "use strict";
  111012. var BABYLON;
  111013. (function (BABYLON) {
  111014. var GLTF2;
  111015. (function (GLTF2) {
  111016. var Extensions;
  111017. (function (Extensions) {
  111018. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  111019. var NAME = "KHR_materials_pbrSpecularGlossiness";
  111020. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  111021. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  111022. function KHR_materials_pbrSpecularGlossiness() {
  111023. var _this = _super !== null && _super.apply(this, arguments) || this;
  111024. _this.name = NAME;
  111025. return _this;
  111026. }
  111027. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  111028. var _this = this;
  111029. return this._loadExtensionAsync(context, material, function (context, extension) {
  111030. material._babylonData = material._babylonData || {};
  111031. var babylonData = material._babylonData[babylonDrawMode];
  111032. if (!babylonData) {
  111033. var promises = new Array();
  111034. var name_1 = material.name || "materialSG_" + material._index;
  111035. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  111036. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  111037. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension, babylonMaterial));
  111038. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  111039. babylonData = {
  111040. material: babylonMaterial,
  111041. meshes: [],
  111042. loaded: Promise.all(promises).then(function () { })
  111043. };
  111044. material._babylonData[babylonDrawMode] = babylonData;
  111045. }
  111046. babylonData.meshes.push(babylonMesh);
  111047. assign(babylonData.material);
  111048. return babylonData.loaded;
  111049. });
  111050. };
  111051. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  111052. var promises = new Array();
  111053. if (properties.diffuseFactor) {
  111054. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  111055. babylonMaterial.alpha = properties.diffuseFactor[3];
  111056. }
  111057. else {
  111058. babylonMaterial.albedoColor = BABYLON.Color3.White();
  111059. }
  111060. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  111061. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  111062. if (properties.diffuseTexture) {
  111063. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  111064. babylonMaterial.albedoTexture = texture;
  111065. }));
  111066. }
  111067. if (properties.specularGlossinessTexture) {
  111068. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  111069. babylonMaterial.reflectivityTexture = texture;
  111070. }));
  111071. babylonMaterial.reflectivityTexture.hasAlpha = true;
  111072. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  111073. }
  111074. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  111075. return Promise.all(promises).then(function () { });
  111076. };
  111077. return KHR_materials_pbrSpecularGlossiness;
  111078. }(GLTF2.GLTFLoaderExtension));
  111079. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  111080. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  111081. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111082. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111083. })(BABYLON || (BABYLON = {}));
  111084. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  111085. "use strict";
  111086. var BABYLON;
  111087. (function (BABYLON) {
  111088. var GLTF2;
  111089. (function (GLTF2) {
  111090. var Extensions;
  111091. (function (Extensions) {
  111092. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  111093. var NAME = "KHR_lights";
  111094. var LightType;
  111095. (function (LightType) {
  111096. LightType["AMBIENT"] = "ambient";
  111097. LightType["DIRECTIONAL"] = "directional";
  111098. LightType["POINT"] = "point";
  111099. LightType["SPOT"] = "spot";
  111100. })(LightType || (LightType = {}));
  111101. var KHR_lights = /** @class */ (function (_super) {
  111102. __extends(KHR_lights, _super);
  111103. function KHR_lights() {
  111104. var _this = _super !== null && _super.apply(this, arguments) || this;
  111105. _this.name = NAME;
  111106. return _this;
  111107. }
  111108. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  111109. var _this = this;
  111110. return this._loadExtensionAsync(context, scene, function (context, extension) {
  111111. var promise = _this._loader._loadSceneAsync(context, scene);
  111112. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  111113. if (light.type !== LightType.AMBIENT) {
  111114. throw new Error(context + ": Only ambient lights are allowed on a scene");
  111115. }
  111116. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  111117. return promise;
  111118. });
  111119. };
  111120. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  111121. var _this = this;
  111122. return this._loadExtensionAsync(context, node, function (context, extension) {
  111123. var promise = _this._loader._loadNodeAsync(context, node);
  111124. var babylonLight;
  111125. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  111126. var name = node._babylonMesh.name;
  111127. switch (light.type) {
  111128. case LightType.AMBIENT: {
  111129. throw new Error(context + ": Ambient lights are not allowed on a node");
  111130. }
  111131. case LightType.DIRECTIONAL: {
  111132. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  111133. break;
  111134. }
  111135. case LightType.POINT: {
  111136. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  111137. break;
  111138. }
  111139. case LightType.SPOT: {
  111140. var spotLight = light;
  111141. // TODO: support inner and outer cone angles
  111142. //const innerConeAngle = spotLight.innerConeAngle || 0;
  111143. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  111144. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  111145. break;
  111146. }
  111147. default: {
  111148. throw new Error(context + ": Invalid light type (" + light.type + ")");
  111149. }
  111150. }
  111151. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  111152. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  111153. babylonLight.parent = node._babylonMesh;
  111154. return promise;
  111155. });
  111156. };
  111157. Object.defineProperty(KHR_lights.prototype, "_lights", {
  111158. get: function () {
  111159. var extensions = this._loader._gltf.extensions;
  111160. if (!extensions || !extensions[this.name]) {
  111161. throw new Error("#/extensions: '" + this.name + "' not found");
  111162. }
  111163. var extension = extensions[this.name];
  111164. return extension.lights;
  111165. },
  111166. enumerable: true,
  111167. configurable: true
  111168. });
  111169. return KHR_lights;
  111170. }(GLTF2.GLTFLoaderExtension));
  111171. Extensions.KHR_lights = KHR_lights;
  111172. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  111173. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111174. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111175. })(BABYLON || (BABYLON = {}));
  111176. //# sourceMappingURL=KHR_lights.js.map
  111177. return BABYLON;
  111178. });
  111179. /***/ }),
  111180. /* 33 */
  111181. /***/ (function(module, exports, __webpack_require__) {
  111182. /*!
  111183. * PEP v0.4.3 | https://github.com/jquery/PEP
  111184. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  111185. */
  111186. !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);
  111187. // define inherited MouseEvent properties
  111188. // skip bubbles and cancelable since they're set above in initEvent()
  111189. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  111190. // Spec requires that pointers without pressure specified use 0.5 for down
  111191. // state and 0 for up state.
  111192. var f=0;
  111193. // add x/y properties aliased to clientX/Y
  111194. // define the properties of the PointerEvent interface
  111195. 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(){
  111196. // only activate if this platform does not have pointer events
  111197. 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}})}/**
  111198. * This is the constructor for new PointerEvents.
  111199. *
  111200. * New Pointer Events must be given a type, and an optional dictionary of
  111201. * initialization properties.
  111202. *
  111203. * Due to certain platform requirements, events returned from the constructor
  111204. * identify as MouseEvents.
  111205. *
  111206. * @constructor
  111207. * @param {String} inType The type of the event to create.
  111208. * @param {Object} [inDict] An optional dictionary of initial event properties.
  111209. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  111210. */
  111211. 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},
  111212. // return value, key, map
  111213. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  111214. // MouseEvent
  111215. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  111216. // DOM Level 3
  111217. "buttons",
  111218. // PointerEvent
  111219. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  111220. // event instance
  111221. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  111222. // MouseEvent
  111223. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  111224. // DOM Level 3
  111225. 0,
  111226. // PointerEvent
  111227. 0,0,0,0,0,0,"",0,!1,
  111228. // event instance
  111229. "",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),
  111230. // Scope objects for native events.
  111231. // This exists for ease of testing.
  111232. eventSources:Object.create(null),eventSourceList:[],/**
  111233. * Add a new event source that will generate pointer events.
  111234. *
  111235. * `inSource` must contain an array of event names named `events`, and
  111236. * functions with the names specified in the `events` array.
  111237. * @param {string} name A name for the event source
  111238. * @param {Object} source A new source of platform events.
  111239. */
  111240. 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++)
  111241. // call eventsource register
  111242. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  111243. // call eventsource register
  111244. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  111245. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  111246. return!1}},
  111247. // EVENTS
  111248. 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)},
  111249. // LISTENER LOGIC
  111250. eventHandler:function(a){
  111251. // This is used to prevent multiple dispatch of pointerevents from
  111252. // platform events. This can happen when two elements in different scopes
  111253. // are set up to create pointer events, which is relevant to Shadow DOM.
  111254. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  111255. // set up event listeners
  111256. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  111257. // remove event listeners
  111258. 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)},
  111259. // EVENT CREATION AND TRACKING
  111260. /**
  111261. * Creates a new Event of type `inType`, based on the information in
  111262. * `inEvent`.
  111263. *
  111264. * @param {string} inType A string representing the type of event to create
  111265. * @param {Event} inEvent A platform event with a target
  111266. * @return {Event} A PointerEvent of type `inType`
  111267. */
  111268. makeEvent:function(b,c){
  111269. // relatedTarget must be null if pointer is captured
  111270. 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},
  111271. // make and dispatch an event in one call
  111272. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  111273. * Returns a snapshot of inEvent, with writable properties.
  111274. *
  111275. * @param {Event} inEvent An event that contains properties to copy.
  111276. * @return {Object} An object containing shallow copies of `inEvent`'s
  111277. * properties.
  111278. */
  111279. 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],
  111280. // Work around SVGInstanceElement shadow tree
  111281. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  111282. // This is the behavior implemented by Firefox.
  111283. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  111284. // keep the semantics of preventDefault
  111285. 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){
  111286. // Order of conditions due to document.contains() missing in IE.
  111287. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  111288. // Touch: Do not propagate if node is detached.
  111289. 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)}},/**
  111290. * Dispatches the event to its target.
  111291. *
  111292. * @param {Event} inEvent The event to be dispatched.
  111293. * @return {Boolean} True if an event handler returns true, false otherwise.
  111294. */
  111295. 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(
  111296. // is element a shadow host?
  111297. e=this.targetingShadow(f);e;){if(
  111298. // find the the element inside the shadow root
  111299. d=e.elementFromPoint(b,c)){
  111300. // shadowed element may contain a shadow root
  111301. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  111302. // check for older shadows
  111303. e=this.olderShadow(e)}
  111304. // light dom element is the target
  111305. return f}},owner:function(a){
  111306. // walk up until you hit the shadow root or document
  111307. for(var b=a;b.parentNode;)b=b.parentNode;
  111308. // the owner element is expected to be a Document or ShadowRoot
  111309. 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);
  111310. // if x, y is not in this root, fall back to document search
  111311. 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){
  111312. // Only watch scopes that can target find, as these are top-level.
  111313. // Otherwise we can see duplicate additions and removals that add noise.
  111314. //
  111315. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  111316. // a removal without an insertion when a node is redistributed among
  111317. // shadows. Since it all ends up correct in the document, watching only
  111318. // the document will yield the correct mutations to watch.
  111319. 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))},
  111320. // register all touch-action = none nodes on document load
  111321. 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){
  111322. // find children with touch-action
  111323. var b=x(a,this.findElements,this);
  111324. // flatten the list
  111325. // make sure the added nodes are accounted for
  111326. 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){}
  111327. // handler block for native mouse events
  111328. 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:[],
  111329. // collide with the global mouse listener
  111330. 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++){
  111331. // simulated mouse events will be swallowed near a primary touchend
  111332. 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);
  111333. // Update buttons state after possible out-of-document mouseup.
  111334. 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];
  111335. // Produces wrong state of buttons in Browsers without `buttons` support
  111336. // when a mouse button that was pressed outside the document is released
  111337. // inside and other buttons are still pressed down.
  111338. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  111339. // Support: Firefox <=44 only
  111340. // FF Ubuntu includes the lifted button in the `buttons` property on
  111341. // mouseup.
  111342. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  111343. 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),
  111344. // set touch-action on shadows as well
  111345. 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),
  111346. // remove touch-action from shadow
  111347. 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);
  111348. // simply update scrollType if listeners are already established
  111349. 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){
  111350. // set primary touch if there no pointers, or the only pointer is the mouse
  111351. (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,
  111352. // forward modifier keys
  111353. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  111354. // forward touch preventDefaults
  111355. 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))},
  111356. // For single axis scrollers, determines whether the element should emit
  111357. // pointer events or behave as a scroller
  111358. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  111359. // this element is a touch-action: none, should never scroll
  111360. b=!1;else if("XY"===c)
  111361. // this element should always scroll
  111362. 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]);
  111363. // if delta in the scroll axis > delta other axis, scroll instead of
  111364. // making events
  111365. 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},
  111366. // In some instances, a touchstart can happen without a touchend. This
  111367. // leaves the pointermap in a broken state.
  111368. // Therefore, on every touchstart, we remove the touches that did not fire a
  111369. // touchend event.
  111370. // To keep state globally consistent, we fire a
  111371. // pointercancel for this "abandoned" touch
  111372. vacuumTouches:function(a){var b=a.touches;
  111373. // pointermap.size should be < tl.length here, as the touchstart has not
  111374. // been processed yet.
  111375. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  111376. // Never remove pointerId == 1, which is mouse.
  111377. // Touch identifiers are 2 smaller than their pointerId, which is the
  111378. // index in pointermap.
  111379. 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);
  111380. // a finger drifted off the screen, ignore it
  111381. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  111382. // recover from retargeting by shadow
  111383. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  111384. // clean up case when finger leaves the screen
  111385. 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)},
  111386. // prevent synth mouse events from creating pointer events
  111387. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  111388. // only the primary finger will synth mouse events
  111389. if(this.isPrimaryTouch(c)){
  111390. // remember x/y of last touch
  111391. 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});
  111392. /***/ }),
  111393. /* 34 */
  111394. /***/ (function(module, exports, __webpack_require__) {
  111395. "use strict";
  111396. Object.defineProperty(exports, "__esModule", { value: true });
  111397. var defaultViewer_1 = __webpack_require__(4);
  111398. var mappers_1 = __webpack_require__(1);
  111399. function InitTags(selector) {
  111400. if (selector === void 0) { selector = 'babylon'; }
  111401. var elements = document.querySelectorAll(selector);
  111402. for (var i = 0; i < elements.length; ++i) {
  111403. var element = elements.item(i);
  111404. var configMapper = mappers_1.mapperManager.getMapper('dom');
  111405. var config = configMapper.map(element);
  111406. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  111407. }
  111408. }
  111409. exports.InitTags = InitTags;
  111410. /***/ })
  111411. /******/ ]);
  111412. return BabylonViewer;
  111413. });